コード例 #1
0
ファイル: Program.cs プロジェクト: cvs1989/hooyeswidget
 static void UseWcf()
 {
     /*
      动态下载服务元数据
      */
     MetadataExchangeClient metaExchangeClient =
         new MetadataExchangeClient(
             new Uri("http://localhost:8002/ManualService"),
             MetadataExchangeClientMode.HttpGet
         );
     //下载元数据
     MetadataSet metadataSet = metaExchangeClient.GetMetadata();
     WsdlImporter importer = new WsdlImporter(metadataSet);
     ServiceEndpointCollection endpointCollection = importer.ImportAllEndpoints();
     IManulService manulProxy = null;
     foreach (ServiceEndpoint endPointItem in endpointCollection)
     {
         manulProxy = new ChannelFactory<IManulService>(
             endPointItem.Binding,
             endPointItem.Address
             ).CreateChannel();
         ((IChannel)manulProxy).Open();
         Console.WriteLine("WCF调用结果为:{0}",
             manulProxy.GetData());
         ((IChannel)manulProxy).Close();
     }
 }
コード例 #2
0
		private static void GenerateCodeDomTree(WsdlImporter wsdlImporter, ServiceContractGenerator contractGenerator)
		{
			Collection<ContractDescription> contracts = wsdlImporter.ImportAllContracts();
			Collection<Binding> bindings = wsdlImporter.ImportAllBindings();
			ServiceEndpointCollection endpoints = wsdlImporter.ImportAllEndpoints();

			if (wsdlImporter.Errors.Any(e => !e.IsWarning))
			{
				throw new CodeGenerationException(wsdlImporter.Errors);
			}

			foreach (ContractDescription contract in contracts)
			{
				//TODO:Alex:Make the naming scheme customisable.
				contract.Name = "I" + contract.Name.Replace("Interface", string.Empty);
				contractGenerator.GenerateServiceContractType(contract);
			}

			foreach (Binding binding in bindings)
			{
				string bindingSectionName, configurationName;
				contractGenerator.GenerateBinding(binding, out bindingSectionName, out configurationName);
			}

			foreach (ServiceEndpoint endpoint in endpoints)
			{
				ChannelEndpointElement channelElement;
				contractGenerator.GenerateServiceEndpoint(endpoint, out channelElement);
			}
		}
コード例 #3
0
ファイル: MetadataResolver.cs プロジェクト: raj581/Marvin
        private static ServiceEndpointCollection ResolveContracts(
            IEnumerable <ContractDescription> contracts,
            Func <MetadataSet> metadataGetter)
        {
            if (contracts == null)
            {
                throw new ArgumentNullException("contracts");
            }

            List <ContractDescription> list = new List <ContractDescription> (contracts);

            if (list.Count == 0)
            {
                throw new ArgumentException("There must be atleast one ContractDescription", "contracts");
            }

            MetadataSet  metadata = metadataGetter();
            WsdlImporter importer = new WsdlImporter(metadata);
            ServiceEndpointCollection endpoints = importer.ImportAllEndpoints();

            ServiceEndpointCollection ret = new ServiceEndpointCollection();

            foreach (ContractDescription contract in list)
            {
                Collection <ServiceEndpoint> colln =
                    endpoints.FindAll(new QName(contract.Name, contract.Namespace));

                for (int i = 0; i < colln.Count; i++)
                {
                    ret.Add(colln [i]);
                }
            }

            return(ret);
        }
コード例 #4
0
ファイル: MetadataHelper.cs プロジェクト: Helen1987/edu
		static ServiceEndpointCollection QueryMexEndpoint(string mexAddress, BindingElement bindingElement)
		{
			var binding = new CustomBinding(bindingElement);
			var MEXClient = new MetadataExchangeClient(binding);
			var metadata = MEXClient.GetMetadata(new EndpointAddress(mexAddress));
			var importer = new WsdlImporter(metadata);
			return importer.ImportAllEndpoints();
		}
        public ServiceMetadataInformation ImportMetadata(Collection<MetadataSection> metadataCollection, MetadataImporterSerializerFormatMode formatMode)
        {
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            CodeDomProvider codeDomProvider = m_CodeDomProviderFactory.CreateProvider();

            WsdlImporter importer = new WsdlImporter(new MetadataSet(metadataCollection));
            switch (formatMode)
            {
                case MetadataImporterSerializerFormatMode.DataContractSerializer:
                    AddStateForDataContractSerializerImport(importer, formatMode, codeCompileUnit, codeDomProvider);
                    break;
                case MetadataImporterSerializerFormatMode.XmlSerializer:
                    AddStateForXmlSerializerImport(importer, codeCompileUnit, codeDomProvider);
                    break;
                case MetadataImporterSerializerFormatMode.Auto:
                    AddStateForDataContractSerializerImport(importer, formatMode, codeCompileUnit, codeDomProvider);
                    AddStateForXmlSerializerImport(importer, codeCompileUnit, codeDomProvider);
                    break;
            }

            if (!importer.State.ContainsKey(typeof(WrappedOptions)))
            {
                importer.State.Add(typeof(WrappedOptions), new WrappedOptions
                {
                    WrappedFlag = false
                });
            }

            Collection<Binding> bindings = importer.ImportAllBindings();
            Collection<ContractDescription> contracts = importer.ImportAllContracts();
            ServiceEndpointCollection endpoints = importer.ImportAllEndpoints();
            Collection<MetadataConversionError> importErrors = importer.Errors;

            bool success = true;
            if (importErrors != null)
            {
                foreach (MetadataConversionError error in importErrors)
                {
                    if (!error.IsWarning)
                    {
                        success = false;
                        break;
                    }
                }
            }
            if (!success)
            {
                //TODO: Throw exception
            }
               return new ServiceMetadataInformation(codeCompileUnit, codeDomProvider)
               {
                   Bindings = bindings,
                   Contracts = contracts,
                   Endpoints = endpoints
               };
        }
コード例 #6
0
ファイル: Client.cs プロジェクト: baulig/Provcon-Faust
        public static void Run(Uri uri, string cache)
        {
            ServicePointManager.ServerCertificateValidationCallback = Validator;

            MetadataSet doc;
            string tempfile = null;
            bool needsDownload;
            if (cache == null) {
                needsDownload = true;
                tempfile = Path.GetTempFileName ();
                cache = tempfile;
            } else {
                needsDownload = !File.Exists (cache);
            }

            if (needsDownload) {
                Console.WriteLine ("Downloading service metadata ...");
                DownloadXml (uri, cache);
                Console.WriteLine ("Downloaded service metadata into {0}.", cache);
            }

            try {
                doc = LoadMetadata (uri, cache);
            } finally {
                if (tempfile != null)
                    File.Delete (tempfile);
            }

            var importer = new WsdlImporter (doc);

            var bindings = importer.ImportAllBindings ();
            var endpoints = importer.ImportAllEndpoints ();

            foreach (var error in importer.Errors) {
                if (error.IsWarning)
                    Console.WriteLine ("WARNING: {0}", error.Message);
                else
                    Console.WriteLine ("ERROR: {0}", error.Message);
            }

            Console.WriteLine ("DONE IMPORTING: {0} {1}", bindings.Count, endpoints.Count);

            foreach (var binding in bindings)
                Console.WriteLine ("BINDING: {0}", binding);
            foreach (var endpoint in endpoints)
                Console.WriteLine ("ENDPOINT: {0}", endpoint.Address);

            foreach (var endpoint in endpoints) {
                try {
                    Run (endpoint);
                } catch (Exception ex) {
                    Console.WriteLine ("ERROR ({0}): {1}", endpoint.Address, ex);
                }
            }
        }
コード例 #7
0
      static ServiceEndpointCollection QueryMexEndpoint(string mexAddress,Binding binding,TokenProvider tokenProvider)
      {
         dynamic extendedBinding = binding;
         extendedBinding.MaxReceivedMessageSize *= MessageSizeMultiplier;

         MetadataExchangeClient mexClient = new MetadataExchangeClient(extendedBinding);
         mexClient.SetServiceBusCredentials(tokenProvider);
         MetadataSet metadata = mexClient.GetMetadata(new EndpointAddress(mexAddress));
         MetadataImporter importer = new WsdlImporter(metadata);
         return importer.ImportAllEndpoints();
      }
コード例 #8
0
ファイル: MetadataHelper.cs プロジェクト: ittray/LocalDemo
      static ServiceEndpointCollection QueryMexEndpoint(string mexAddress,BindingElement bindingElement)
      {
         dynamic element = bindingElement;
         element.MaxReceivedMessageSize *= MessageSizeMultiplier;

         CustomBinding binding = new CustomBinding(element);
         
         MetadataExchangeClient mexClient = new MetadataExchangeClient(binding);
         MetadataSet metadata = mexClient.GetMetadata(new EndpointAddress(mexAddress));
         MetadataImporter importer = new WsdlImporter(metadata);
         return importer.ImportAllEndpoints();
      }
コード例 #9
0
ファイル: TestUtils.cs プロジェクト: baulig/wcf-config
        public static void GenerateFromWsdl(Uri uri, string wsdlFilename,
		                                     string xmlFilename, string xsdFilename)
        {
            var doc = Utils.LoadMetadata (uri, wsdlFilename);
            var importer = new WsdlImporter (doc);
            var endpoints = importer.ImportAllEndpoints ();

            var config = new Configuration ();
            foreach (var endpoint in endpoints)
                config.AddEndpoint (endpoint);

            Generator.Write (xmlFilename, xsdFilename, config);
        }
コード例 #10
0
ファイル: Utils.cs プロジェクト: baulig/Provcon-Faust
        public static void GenerateConfig(MetadataSet metadata, Configuration config)
        {
            WsdlImporter importer = new WsdlImporter (metadata);

            var endpoints = importer.ImportAllEndpoints ();

            var generator = new ServiceContractGenerator (config);
            generator.Options = ServiceContractGenerationOptions.None;

            foreach (var endpoint in endpoints) {
                ChannelEndpointElement channelElement;
                generator.GenerateServiceEndpoint (endpoint, out channelElement);
            }
        }
コード例 #11
0
ファイル: WebService.cs プロジェクト: kmcgain/WsdlGenerator
        public WebService(string path)
        {
            var metadataAddress = new EndpointAddress(path);
            var mexClient = new MetadataExchangeClient(metadataAddress.Uri, MetadataExchangeClientMode.HttpGet);
            mexClient.ResolveMetadataReferences = true;

            var metadata = mexClient.GetMetadata(metadataAddress.Uri, MetadataExchangeClientMode.HttpGet);
            var metadataSet = new MetadataSet(metadata.MetadataSections);

            var importer = new WsdlImporter(metadataSet);

            AllWsdlDocuments = importer.WsdlDocuments;
            AllContracts = importer.ImportAllContracts();
            AllBindings = importer.ImportAllBindings();
            AllEndpoints = importer.ImportAllEndpoints();

            //AllContracts.First().Operations.First().
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: huoxudong125/WCF-Demo
 static void Main(string[] args)
 {
     Binding binding = MetadataExchangeBindings.CreateMexHttpBinding();
     EndpointAddress address = new EndpointAddress("http://127.0.0.1:9999/calculatorservice/mex");
     MetadataExchangeClient metadataExchangeClient = new MetadataExchangeClient(binding);
     MetadataSet metadata = metadataExchangeClient.GetMetadata(address);
     WsdlImporter wsdlImporter = new WsdlImporter(metadata);
     //添加已知契约类型
     ContractDescription contract = ContractDescription.GetContract(typeof(ICalculator));
     wsdlImporter.KnownContracts.Add(new XmlQualifiedName(contract.Name, contract.Namespace), contract);
     ServiceEndpointCollection endpoints = wsdlImporter.ImportAllEndpoints();
     using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(endpoints[0]))
     {
         ICalculator calculator = channelFactory.CreateChannel();
         Console.WriteLine("x + y = {2} when x = {0} and y = {1}", 1, 2, calculator.Add(1, 2));
     }
     Console.Read();
 }
コード例 #13
0
      static ServiceEndpointCollection QueryMexEndpoint(string mexAddress,Binding binding,string issuer,string secret)
      {
         Binding extendedBinding = null;

         if(binding is NetTcpRelayBinding)
         {
            NetTcpRelayBinding actualBinding = binding as NetTcpRelayBinding;
            actualBinding.MaxReceivedMessageSize *= MessageSizeMultiplier;
            extendedBinding = actualBinding;
         }
         if(binding is WS2007HttpRelayBinding)
         {
            WS2007HttpRelayBinding actualBinding = binding as WS2007HttpRelayBinding;
            actualBinding.MaxReceivedMessageSize *= MessageSizeMultiplier;
            extendedBinding = actualBinding;
         }

         MetadataExchangeClient mexClient = new MetadataExchangeClient(extendedBinding);
         mexClient.SetServiceBusCredentials(issuer,secret);
         MetadataSet metadata = mexClient.GetMetadata(new EndpointAddress(mexAddress));
         MetadataImporter importer = new WsdlImporter(metadata);
         return importer.ImportAllEndpoints();
      }
コード例 #14
0
ファイル: client.cs プロジェクト: tian1ll1/WPF_Examples
        static void Main()
        {
            // Create a MetadataExchangeClient for retrieving metadata.
            EndpointAddress mexAddress = new EndpointAddress(ConfigurationManager.AppSettings["mexAddress"]);
            MetadataExchangeClient mexClient = new MetadataExchangeClient(mexAddress);

            // Retrieve the metadata for all endpoints using metadata exchange protocol (mex).
            MetadataSet metadataSet = mexClient.GetMetadata();

            //Convert the metadata into endpoints
            WsdlImporter importer = new WsdlImporter(metadataSet);
            ServiceEndpointCollection endpoints = importer.ImportAllEndpoints();

            CalculatorClient client = null;
            ContractDescription contract = ContractDescription.GetContract(typeof(ICalculator));
            // Communicate with each endpoint that supports the ICalculator contract.
            foreach (ServiceEndpoint ep in endpoints)
            {
                if (ep.Contract.Namespace.Equals(contract.Namespace) && ep.Contract.Name.Equals(contract.Name))
                {
                    // Create a client using the endpoint address and binding.
                    client = new CalculatorClient(ep.Binding, new EndpointAddress(ep.Address.Uri));
                    Console.WriteLine("Communicate with endpoint: ");
                    Console.WriteLine("   AddressPath={0}", ep.Address.Uri.PathAndQuery);
                    Console.WriteLine("   Binding={0}", ep.Binding.Name);
                    // call operations
                    DoCalculations(client);

                    //Closing the client gracefully closes the connection and cleans up resources
                    client.Close();
                }
            }

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();
        }
コード例 #15
0
		static void BasicHttpBinding_inner (
			TestContext context, MetadataSet doc, BasicHttpSecurityMode security,
			WSMessageEncoding encoding, HttpClientCredentialType clientCred,
			AuthenticationSchemes authScheme, bool isHttps, TestLabel label)
		{
			var sd = (WS.ServiceDescription)doc.MetadataSections [0].Metadata;

			label.EnterScope ("wsdl");
			label.EnterScope ("bindings");
			Assert.That (sd.Bindings.Count, Is.EqualTo (1), label.Get ());

			var binding = sd.Bindings [0];
			Assert.That (binding.ExtensibleAttributes, Is.Null, label.Get ());
			Assert.That (binding.Extensions, Is.Not.Null, label.Get ());

			bool hasPolicyXml;

			switch (security) {
			case BasicHttpSecurityMode.None:
				if (isHttps)
					throw new InvalidOperationException ();
				hasPolicyXml = encoding == WSMessageEncoding.Mtom;
				break;
			case BasicHttpSecurityMode.Message:
			case BasicHttpSecurityMode.Transport:
			case BasicHttpSecurityMode.TransportWithMessageCredential:
				if (encoding == WSMessageEncoding.Mtom)
					throw new InvalidOperationException ();
				hasPolicyXml = true;
				break;
			case BasicHttpSecurityMode.TransportCredentialOnly:
				if (isHttps)
					throw new InvalidOperationException ();
				hasPolicyXml = true;
				break;
			default:
				throw new InvalidOperationException ();
			}
			label.LeaveScope ();

			WS.SoapBinding soap = null;
			XmlElement xml = null;

			foreach (var ext in binding.Extensions) {
				if (ext is WS.SoapBinding)
					soap = (WS.SoapBinding)ext;
				else if (ext is XmlElement)
					xml = (XmlElement)ext;
			}

			CheckSoapBinding (soap, WS.SoapBinding.HttpTransport, label);
			label.LeaveScope ();

			label.EnterScope ("policy-xml");
			if (!hasPolicyXml)
				Assert.That (xml, Is.Null, label.Get ());
			else {
				Assert.That (xml, Is.Not.Null, label.Get ());
				var assertions = AssertPolicy (sd, xml, label);
				Assert.That (assertions, Is.Not.Null, label.Get ());
				if (clientCred == HttpClientCredentialType.Ntlm)
					AssertPolicy (assertions, NtlmAuthenticationQName, label);
				if (encoding == WSMessageEncoding.Mtom)
					AssertPolicy (assertions, MtomEncodingQName, label);
				switch (security) {
				case BasicHttpSecurityMode.Message:
					AssertPolicy (assertions, AsymmetricBindingQName, label);
					AssertPolicy (assertions, Wss10QName, label);
					break;
				case BasicHttpSecurityMode.Transport:
					AssertPolicy (assertions, TransportBindingQName, label);
					break;
				case BasicHttpSecurityMode.TransportWithMessageCredential:
					AssertPolicy (assertions, SignedSupportingQName, label);
					AssertPolicy (assertions, TransportBindingQName, label);
					AssertPolicy (assertions, Wss10QName, label);
					break;
				default:
					break;
				}
				Assert.That (assertions.Count, Is.EqualTo (0), label.Get ());
			}
			label.LeaveScope ();

			label.EnterScope ("services");
			Assert.That (sd.Services, Is.Not.Null, label.Get ());
			Assert.That (sd.Services.Count, Is.EqualTo (1), label.Get ());
			var service = sd.Services [0];
			Assert.That (service.Ports, Is.Not.Null, label.Get ());
			Assert.That (service.Ports.Count, Is.EqualTo (1), label.Get ());
			var port = service.Ports [0];
			
			label.EnterScope ("port");
			Assert.That (port.Extensions, Is.Not.Null, label.Get ());
			Assert.That (port.Extensions.Count, Is.EqualTo (1), label.Get ());
			
			WS.SoapAddressBinding soap_addr_binding = null;
			foreach (var extension in port.Extensions) {
				if (extension is WS.SoapAddressBinding)
					soap_addr_binding = (WS.SoapAddressBinding)extension;
				else
					Assert.Fail (label.Get ());
			}
			Assert.That (soap_addr_binding, Is.Not.Null, label.Get ());
			label.LeaveScope ();

			label.LeaveScope (); // wsdl

			var importer = new WsdlImporter (doc);

			label.EnterScope ("bindings");
			var bindings = importer.ImportAllBindings ();
			CheckImportErrors (importer, label);

			Assert.That (bindings, Is.Not.Null, label.Get ());
			Assert.That (bindings.Count, Is.EqualTo (1), label.Get ());

			string scheme;
			if ((security == BasicHttpSecurityMode.Transport) ||
			    (security == BasicHttpSecurityMode.TransportWithMessageCredential))
				scheme = "https";
			else
				scheme = "http";

			CheckBasicHttpBinding (
				bindings [0], scheme, security, encoding, clientCred,
				authScheme, label);
			label.LeaveScope ();

			label.EnterScope ("endpoints");
			var endpoints = importer.ImportAllEndpoints ();
			CheckImportErrors (importer, label);

			Assert.That (endpoints, Is.Not.Null, label.Get ());
			Assert.That (endpoints.Count, Is.EqualTo (1), label.Get ());

			var uri = isHttps ? MetadataSamples.HttpsUri : MetadataSamples.HttpUri;

			CheckEndpoint (endpoints [0], uri, label);
			label.LeaveScope ();
		}
コード例 #16
0
 private void ImportMetadata(WsdlImporter wsdlImporter,
     out ServiceEndpointCollection endpoints, 
     out Collection<System.ServiceModel.Channels.Binding> bindings, 
     out Collection<ContractDescription> contracts)
 {
     endpoints = wsdlImporter.ImportAllEndpoints();
     bindings = wsdlImporter.ImportAllBindings();
     contracts = wsdlImporter.ImportAllContracts();
     ThrowOnMetadataConversionErrors(wsdlImporter.Errors);
 }
コード例 #17
0
ファイル: MetadataHelper.cs プロジェクト: jcde/WCF
        public static ServiceEndpoint[] GetEndpoints(string mexAddress)
        {
            if(string.IsNullOrWhiteSpace(mexAddress))
             {
            throw new ArgumentException("mexAddress");
             }

             Uri address = new Uri(mexAddress);
             ServiceEndpointCollection endpoints = null;
             BindingElement bindingElement = null;

             //Try over HTTP-GET first
             if(address.Scheme == Uri.UriSchemeHttp || address.Scheme == Uri.UriSchemeHttps)
             {
            string getAddress = mexAddress;
            if(mexAddress.EndsWith("?wsdl") == false)
            {
               getAddress += "?wsdl";
            }
            if(address.Scheme == Uri.UriSchemeHttp)
            {
               HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
               httpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
               bindingElement = httpBindingElement;
            }
            else
            {
               HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
               httpsBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
               bindingElement = httpsBindingElement;
            }
            CustomBinding binding = new CustomBinding(bindingElement);

            MetadataExchangeClient mexClient = new MetadataExchangeClient(binding);
            MetadataSet metadata = mexClient.GetMetadata(new Uri(getAddress),MetadataExchangeClientMode.HttpGet);
            MetadataImporter importer = new WsdlImporter(metadata);
            endpoints = importer.ImportAllEndpoints();
            return endpoints.ToArray();
             }

             //Try MEX endpoint:

             if(address.Scheme == Uri.UriSchemeHttp)
             {
            bindingElement = new HttpTransportBindingElement();
             }
             if(address.Scheme == Uri.UriSchemeHttps)
             {
            bindingElement = new HttpsTransportBindingElement();
             }
             if(address.Scheme == Uri.UriSchemeNetTcp)
             {
            bindingElement = new TcpTransportBindingElement();
             }
             if(address.Scheme == Uri.UriSchemeNetPipe)
             {
            bindingElement = new NamedPipeTransportBindingElement();
             }

             endpoints = QueryMexEndpoint(mexAddress,bindingElement);
             return endpoints.ToArray();
        }
コード例 #18
0
		internal static Binding GetBindingFromMetadata(EndpointDiscoveryMetadata metadata)
		{
			var metadataExtension = 
				(from extension in metadata.Extensions
				 where extension.Name == WcfConstants.EndpointMetadata
				 select extension).FirstOrDefault();
			if (metadataExtension == null) return null;

			var endpointMetadata = metadataExtension.Elements().FirstOrDefault();
			if (endpointMetadata == null) return null;

			using (var xmlReader = endpointMetadata.CreateReader())
			{
				var metadataSet = MetadataSet.ReadFrom(xmlReader);
				var importer = new WsdlImporter(metadataSet);
				var endpoints = importer.ImportAllEndpoints();
				if (endpoints.Count > 0)
				{
					return endpoints[0].Binding;
				}
			}

			return null;
		}
コード例 #19
0
        protected void btnFetchRequests_Click(object sender, EventArgs e)
        {
            txtRequest.Text = string.Empty;
            txtResponse.Text = string.Empty;
            string wsdlUrl = txtUrl.Text;
            if (wsdlUrl != null && wsdlUrl != string.Empty && wsdlUrl.IndexOf("wsdl") != -1)// && ValidateRequestURL())
            {
                lblWarning.Visible = false;
                try
                {
                    WSHttpBinding binding = new WSHttpBinding(SecurityMode.None);
                    binding.MaxReceivedMessageSize = 2147483647;
                    MetadataExchangeClient metClient = new MetadataExchangeClient(binding);
                    metClient.ResolveMetadataReferences = true;
                    MetadataSet metSet = metClient.GetMetadata(new Uri(wsdlUrl), MetadataExchangeClientMode.HttpGet);
                    WsdlImporter wsdlImporter = new WsdlImporter(metSet);
                    CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                    ServiceContractGenerator generator = new ServiceContractGenerator(codeCompileUnit);

                    Collection<ContractDescription> contracts = wsdlImporter.ImportAllContracts();
                    ServiceEndpointCollection endpoints = wsdlImporter.ImportAllEndpoints();

                    List<string> opsList = new List<string>();
                    string serviceName = string.Empty;
                    string nameSpace = string.Empty;

                    foreach (ContractDescription contract in contracts)
                    {
                        foreach (OperationDescription op in contract.Operations)
                        {
                            opsList.Add(op.Name);
                        }
                        generator.GenerateServiceContractType(contract);
                        serviceName = contract.Name;
                        nameSpace = contract.Namespace;
                        break;
                    }
                    ddlOperations.DataSource = opsList;
                    ddlOperations.DataBind();
                    ddlOperations.Visible = true;
                    lblOperations.Visible = true;

                    ViewState.Add("ServiceName", serviceName);
                    ViewState.Add("Namespace", nameSpace);

                    CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
                    StringWriter ws = new StringWriter();
                    provider1.GenerateCodeFromCompileUnit(codeCompileUnit, ws, new CodeGeneratorOptions());

                    string serverRoot = System.Configuration.ConfigurationManager.AppSettings["ServerRoot"];
                    string[] assemblyNames = new string[] { "System.Configuration.dll", "System.Xml.dll", Server.MapPath( serverRoot + "bin/") + "System.Runtime.Serialization.dll",
                        "System.dll", "System.Web.Services.dll", "System.Data.dll", Server.MapPath( serverRoot + "bin/") + "System.ServiceModel.dll" };
                    CompilerParameters options = new CompilerParameters(assemblyNames);
                    options.WarningLevel = 0;
                    options.GenerateInMemory = true;

                    string sourceCode = ws.ToString();
                    CompilerResults results = provider1.CompileAssemblyFromSource(options, sourceCode);

                    if (!results.Errors.HasErrors)
                    {
                        Assembly compiledAssembly = results.CompiledAssembly;
                        Type objClientType = compiledAssembly.GetType(serviceName);

                        foreach (MethodInfo minfo in objClientType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
                        {
                            StringBuilder sb = new StringBuilder();

                            if (nameSpace != null && nameSpace != string.Empty)
                            {
                                sb.Append("<" + minfo.Name + " xmlns=\"" + nameSpace + "\">");
                            }
                            else
                            {
                                sb.Append("<" + minfo.Name + ">");
                            }

                            ParameterInfo[] paramInfos = minfo.GetParameters();
                            if (paramInfos != null && paramInfos.Length > 0)
                            {
                                foreach (ParameterInfo param in paramInfos)
                                {
                                    ConstructorInfo cons = param.ParameterType.GetConstructor(new Type[] { });
                                    if (cons != null)
                                    {
                                        if (param.ParameterType.IsSerializable)
                                        {
                                            sb.Append("<" + param.Name + ">");
                                            object obj = cons.Invoke(new object[] { });
                                            LoadPropertyMembers(obj, sb, compiledAssembly);
                                            sb.Append("</" + param.Name + ">");
                                        }
                                        else
                                        {
                                            object obj = cons.Invoke(new object[] { });
                                            LoadPropertyMembers(obj, sb, compiledAssembly);
                                        }

                                    }
                                    else
                                    {
                                        if (param.ParameterType.IsEnum)
                                        {
                                            sb.Append("<" + param.Name + ">");
                                            object obj = Activator.CreateInstance(compiledAssembly.GetType(param.ParameterType.FullName));
                                            sb.Append(obj.ToString());
                                            sb.Append("</" + param.Name + ">");
                                        }
                                        else if (param.ParameterType.IsValueType)
                                        {
                                            sb.Append("<" + param.Name + ">");
                                            switch (param.ParameterType.Name)
                                            {
                                                case "Int16":
                                                case "Int32":
                                                case "Int64":
                                                case "Double":
                                                case "Decimal":
                                                    sb.Append("0");
                                                    break;

                                                case "Boolean":
                                                    sb.Append("false");
                                                    break;

                                                case "DateTime":
                                                    sb.Append(DateTime.Now.ToString("yyyy-MM-dd"));
                                                    break;
                                            }
                                            sb.Append("</" + param.Name + ">");
                                        }
                                        else if (param.ParameterType.IsArray)
                                        {
                                            sb.Append("<" + param.Name + ">");
                                            string propName = param.ParameterType.Name;
                                            propName = propName.Replace("[]", string.Empty);
                                            sb.Append("<" + propName + ">");
                                            sb.Append("</" + propName + ">");
                                            sb.Append("</" + param.Name + ">");
                                        }
                                        else
                                        {
                                            sb.Append("<" + param.Name + ">");
                                            sb.Append("</" + param.Name + ">");
                                        }
                                    }
                                }
                            }
                            sb.Append("</" + minfo.Name + ">");


                            string data = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body>";
                            data += sb.ToString();
                            data += "</soap:Body></soap:Envelope>";

                            ViewState.Add(minfo.Name + "Request", data);
                        }
                        txtRequest.Text = IndentXMLString(ViewState[ddlOperations.SelectedValue + "Request"].ToString());
                        ws.Flush();
                        ws.Close();
                    }
                    else
                    {
                        lblWarning.Text = "There was an error in loading XML requests from the assembly." + "\n" +
                            "You can still provide XML request by copy and pasting it in the Request textbox.";
                        lblWarning.Visible = true;
                        //ViewState.Clear();
                    }

                }
                catch (Exception ex)
                {
                    lblWarning.Text = "Following error occured. " + ex.Message;
                    lblWarning.Visible = true;
                    ViewState.Clear();
                    return;
                }
            }
            else
            {
                lblWarning.Text = "Service URL is either empty or incorrect. Please provide a URL with \"wsdl\" extension. Example: http://servicename.com/service.svc?wsdl";
                lblWarning.Visible = true;
                lblWarning.ForeColor = System.Drawing.Color.Red;
                txtRequest.Text = string.Empty;
                txtResponse.Text = string.Empty;
                ddlOperations.Items.Clear();
            }
        }
コード例 #20
0
ファイル: ExplorerForm.cs プロジェクト: ittray/LocalDemo
      void Explore(string mexAddress)
      {     
         ServiceNode existingNode = null;

         try
         {
            Uri address = new Uri(mexAddress);
            ServiceEndpointCollection endpoints = null;            

            //Find if tree already contain this address
            foreach(ServiceNode node in m_MexTree.Nodes)
            {
               if(node.MexAddress == mexAddress)
               {
                  if(node.Text == "Unspecified Base Address" || node.Text == "Invalid Address")
                  {
                     node.ImageIndex = node.SelectedImageIndex = ServiceIndex;
                  }
                  existingNode = node;
                  break;
               }
            }
            if(address.Scheme == "http")
            {
               HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
               httpBindingElement.MaxReceivedMessageSize *= MessageMultiplier;

               //Try the HTTP MEX Endpoint
               try
               {
                  endpoints = GetEndpoints(httpBindingElement);
               }
               catch
               {}
               //Try over HTTP-GET
               if(endpoints == null)
               {
                  string httpGetAddress = mexAddress;
                  if(mexAddress.EndsWith("?wsdl") == false)
                  {
                     httpGetAddress += "?wsdl";
                  }
                  CustomBinding binding = new CustomBinding(httpBindingElement);
                  MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                  MetadataSet metadata = MEXClient.GetMetadata(new Uri(httpGetAddress),MetadataExchangeClientMode.HttpGet);
                  MetadataImporter importer = new WsdlImporter(metadata);
                  endpoints = importer.ImportAllEndpoints();
               }
            }
            if(address.Scheme == "https")
            {
               HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
               httpsBindingElement.MaxReceivedMessageSize *= MessageMultiplier;

               //Try the HTTPS MEX Endpoint
               try
               {
                  endpoints = GetEndpoints(httpsBindingElement);
               }
               catch
               {
               }
               //Try over HTTP-GET
               if(endpoints == null)
               {
                  string httpsGetAddress = mexAddress;
                  if(mexAddress.EndsWith("?wsdl") == false)
                  {
                     httpsGetAddress += "?wsdl";
                  }
                  CustomBinding binding = new CustomBinding(httpsBindingElement);
                  MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                  MetadataSet metadata = MEXClient.GetMetadata(new Uri(httpsGetAddress),MetadataExchangeClientMode.HttpGet);
                  MetadataImporter importer = new WsdlImporter(metadata);
                  endpoints = importer.ImportAllEndpoints();
               }
            }
            if(address.Scheme == "net.tcp")
            {
               TcpTransportBindingElement tcpBindingElement = new TcpTransportBindingElement();
               tcpBindingElement.MaxReceivedMessageSize *= MessageMultiplier;
               endpoints = GetEndpoints(tcpBindingElement);
            }
            if(address.Scheme == "net.pipe")
            {
               NamedPipeTransportBindingElement ipcBindingElement = new NamedPipeTransportBindingElement();
               ipcBindingElement.MaxReceivedMessageSize *= MessageMultiplier;
               endpoints = GetEndpoints(ipcBindingElement);
            }
            ProcessMetaData(existingNode,mexAddress,endpoints);
         }
         catch
         {
            if(existingNode == null)
            {
               CurrentNode = new ServiceNode(mexAddress,this,"Invalid Address",ServiceError,ServiceError);
               m_MexTree.Nodes.Add(CurrentNode);
            }
            else
            {
               CurrentNode.Text = "Invalid Address";
               CurrentNode.Nodes.Clear();
               CurrentNode.ImageIndex = CurrentNode.SelectedImageIndex = ServiceError;
            }
         }
      } 
コード例 #21
0
        private void ImportMetadata()
        {
            this.codeCompileUnit = new CodeCompileUnit();
            CreateCodeDomProvider();

            WsdlImporter importer = new WsdlImporter(new MetadataSet(metadataCollection));
            AddStateForDataContractSerializerImport(importer);
            AddStateForXmlSerializerImport(importer);

            this.bindings = importer.ImportAllBindings();
            this.contracts = importer.ImportAllContracts();
            this.endpoints = importer.ImportAllEndpoints();
            this.importWarnings = importer.Errors;

            bool success = true;
            if (this.importWarnings != null)
            {
                foreach (MetadataConversionError error in this.importWarnings)
                {
                    if (!error.IsWarning)
                    {
                        success = false;
                        break;
                    }
                }
            }

            if (!success)
            {
                DynamicProxyException exception = new DynamicProxyException(
                    Constants.ErrorMessages.ImportError);
                exception.MetadataImportErrors = this.importWarnings;
                throw exception;
            }
        }
コード例 #22
0
ファイル: ExplorerForm.cs プロジェクト: spzenk/sfdocsamples
      void OnExplore(object sender,EventArgs e)
      {
         m_ExploreButton.Enabled = false;

         string mexAddress = m_MexAddressTextBox.Text;
         if(String.IsNullOrEmpty(mexAddress))
         {
            Debug.Assert(false,"Empty address");
         }
         m_MexTree.Nodes.Clear();
         DisplayBlankControl();

         SplashScreen splash = new SplashScreen(Resources.Progress);         
         try
         {
            Uri address = new Uri(mexAddress);
            ServiceEndpointCollection endpoints = null;

            if(address.Scheme == "http")
            {
               HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
               httpBindingElement.MaxReceivedMessageSize *= MessageMultiplier;

               //Try the HTTP MEX Endpoint
               try
               {
                  endpoints = GetEndpoints(httpBindingElement);
               }
               catch
               {}
               //Try over HTTP-GET
               if(endpoints == null)
               {
                  string httpGetAddress = mexAddress;
                  if(mexAddress.EndsWith("?wsdl") == false)
                  {
                     httpGetAddress += "?wsdl";
                  }
                  CustomBinding binding = new CustomBinding(httpBindingElement);
                  MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                  MetadataSet metadata = MEXClient.GetMetadata(new Uri(httpGetAddress),MetadataExchangeClientMode.HttpGet);
                  MetadataImporter importer = new WsdlImporter(metadata);
                  endpoints = importer.ImportAllEndpoints();
               }
            }
            if(address.Scheme == "https")
            {
               HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
               httpsBindingElement.MaxReceivedMessageSize *= MessageMultiplier;

               //Try the HTTPS MEX Endpoint
               try
               {
                  endpoints = GetEndpoints(httpsBindingElement);
               }
               catch
               {
               }
               //Try over HTTP-GET
               if(endpoints == null)
               {
                  string httpsGetAddress = mexAddress;
                  if(mexAddress.EndsWith("?wsdl") == false)
                  {
                     httpsGetAddress += "?wsdl";
                  }
                  CustomBinding binding = new CustomBinding(httpsBindingElement);
                  MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                  MetadataSet metadata = MEXClient.GetMetadata(new Uri(httpsGetAddress),MetadataExchangeClientMode.HttpGet);
                  MetadataImporter importer = new WsdlImporter(metadata);
                  endpoints = importer.ImportAllEndpoints();
               }
            }
            if(address.Scheme == "net.tcp")
            {
               TcpTransportBindingElement tcpBindingElement = new TcpTransportBindingElement();
               tcpBindingElement.MaxReceivedMessageSize *= MessageMultiplier;
               endpoints = GetEndpoints(tcpBindingElement);
            }
            if(address.Scheme == "net.pipe")
            {
               NamedPipeTransportBindingElement ipcBindingElement = new NamedPipeTransportBindingElement();
               ipcBindingElement.MaxReceivedMessageSize *= MessageMultiplier;
               endpoints = GetEndpoints(ipcBindingElement);
            }
            ProcessMetaData(endpoints);
         }
         catch
         {
            m_MexTree.Nodes.Clear();

            m_Root = new ServiceNode(this,"Invalid Base Address",ServiceError,ServiceError);
            m_MexTree.Nodes.Add(m_Root);
            return;
         }
         finally
         {
            splash.Close();
            m_ExploreButton.Enabled = true;
         }
      }
コード例 #23
0
ファイル: TestEngine.cs プロジェクト: huoxudong125/WCFLoadUI
        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]);
        }
コード例 #24
0
		private static ServiceEndpointCollection ResolveContracts (
				IEnumerable<ContractDescription> contracts,
				Func<MetadataSet> metadataGetter)
		{
			if (contracts == null)
				throw new ArgumentNullException ("contracts");

			List<ContractDescription> list = new List<ContractDescription> (contracts);
			if (list.Count == 0)
				throw new ArgumentException ("There must be atleast one ContractDescription", "contracts");

			MetadataSet metadata = metadataGetter ();
			WsdlImporter importer = new WsdlImporter (metadata);
			ServiceEndpointCollection endpoints = importer.ImportAllEndpoints ();
			
			ServiceEndpointCollection ret = new ServiceEndpointCollection ();

			foreach (ContractDescription contract in list) {
				Collection<ServiceEndpoint> colln = 
					endpoints.FindAll (new QName (contract.Name, contract.Namespace));

				for (int i = 0; i < colln.Count; i ++)
					ret.Add (colln [i]);
			}

			return ret;
		}
コード例 #25
0
        /// <summary>
        /// compile our wsdl file
        /// </summary>
        /// <param name="astrWebServiceURI"></param>
        /// <param name="astrUsername"></param>
        /// <param name="astrPassword"></param>
        /// <param name="astrMethod"></param>
        /// <returns></returns>
        private compiledAssembly generateCompiledAssembly(string astrWebServiceURI, string astrUsername, string astrPassword, string astrMethod)
        {
            CompilerResults result = null;

            // Define the WSDL Get address, contract name and parameters, with this we can extract WSDL details any time
            //Uri address = new Uri("http://ifbenp.indfish.co.nz:16201/mws-ws/services/Vessel?wsdl"); //("http://localhost:64508/Service1.svc?wsdl");
            Uri address = new Uri(astrWebServiceURI);
            // For HttpGet endpoints use a Service WSDL address a mexMode of .HttpGet and for MEX endpoints use a MEX address and a mexMode of .MetadataExchange
            MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;

            // Get the metadata file from the service.
            MetadataExchangeClient metadataExchangeClient = new MetadataExchangeClient(address, mexMode);
            metadataExchangeClient.ResolveMetadataReferences = true;

            //One can also provide credentials if service needs that by the help following two lines.
            ICredentials networkCredential = new NetworkCredential(astrUsername, astrPassword, "");
            metadataExchangeClient.HttpCredentials = networkCredential;

            //Gets the meta data information of the service.
            MetadataSet metadataSet = metadataExchangeClient.GetMetadata();

            // Import all contracts and endpoints.
            WsdlImporter wsdlImporter = new WsdlImporter(metadataSet);

            //Import all contracts.
            Collection<ContractDescription> contracts = wsdlImporter.ImportAllContracts();

            //Import all end points.
            ServiceEndpointCollection allEndpoints = wsdlImporter.ImportAllEndpoints();

            // Generate type information for each contract.
            ServiceContractGenerator serviceContractGenerator = new ServiceContractGenerator();

            //Dictinary has been defined to keep all the contract endpoints present, contract name is key of the dictionary item.
            var endpointsForContracts = new Dictionary<string, IEnumerable<ServiceEndpoint>>();

            string contractName = null;

            foreach (ContractDescription contract in contracts)
            {
                serviceContractGenerator.GenerateServiceContractType(contract);
                // Keep a list of each contract's endpoints.
                endpointsForContracts[contract.Name] = allEndpoints.Where(ep => ep.Contract.Name == contract.Name).ToList();
                contractName = contract.Name;
            }

            // Generate a code file for the contracts.
            CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions();
            codeGeneratorOptions.BracingStyle = "C";

            // Create Compiler instance of a specified language.
            CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#");

            // Adding WCF-related assemblies references as copiler parameters, so as to do the compilation of particular service contract.
            CompilerParameters compilerParameters = new CompilerParameters(new string[] { "System.dll", "System.ServiceModel.dll", "System.Runtime.Serialization.dll" });
            compilerParameters.GenerateInMemory = true;

            //Gets the compiled assembly.
            result = codeDomProvider.CompileAssemblyFromDom(compilerParameters, serviceContractGenerator.TargetCompileUnit);

            object proxyInstance = null;

            if (result.Errors.Count <= 0)
            {

                // Find the proxy type that was generated for the specified contract (identified by a class that implements the contract and ICommunicationbject - this is contract
                //implemented by all the communication oriented objects).
                Type proxyType = result.CompiledAssembly.GetTypes().First(t => t.IsClass && t.GetInterface(contractName) != null &&
                    t.GetInterface(typeof(ICommunicationObject).Name) != null);

                // Now we get the first service endpoint for the particular contract.
                ServiceEndpoint serviceEndpoint = endpointsForContracts[contractName].First();

                BasicHttpBinding newBinding = new BasicHttpBinding();

                newBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
                newBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
                newBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                newBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;

                newBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

                serviceEndpoint.Binding = newBinding;

                // Create an instance of the proxy by passing the endpoint binding and address as parameters.
                proxyInstance = result.CompiledAssembly.CreateInstance(proxyType.Name, false, System.Reflection.BindingFlags.CreateInstance, null,
                    new object[] { serviceEndpoint.Binding, serviceEndpoint.Address }, CultureInfo.CurrentCulture, null);

                PropertyInfo clientCredentials = proxyType.GetProperty("ClientCredentials");
                if(null != clientCredentials)
                {
                    ClientCredentials credentials = new ClientCredentials();
                    credentials.UserName.UserName = astrUsername;
                    credentials.UserName.Password = astrPassword;

                    object objCredentials = clientCredentials.GetValue(proxyInstance);
                    credentials = objCredentials as ClientCredentials;

                    if (null != credentials)
                    {
                        credentials.UserName.Password = astrPassword;
                        credentials.UserName.UserName = astrUsername;
                    }
                }
            }

            compiledAssembly finalResults = new compiledAssembly() { compilerResults = result, instantiatedObject = proxyInstance };

            return (finalResults);
        }
コード例 #26
0
ファイル: ExplorerForm.cs プロジェクト: ittray/LocalDemo
      ServiceEndpointCollection GetEndpoints(BindingElement bindingElement)
      {
         CustomBinding binding = new CustomBinding(bindingElement);

         MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
         MetadataSet metadata = MEXClient.GetMetadata(new EndpointAddress(m_MexAddressTextBox.Text));
         MetadataImporter importer = new WsdlImporter(metadata);
         return importer.ImportAllEndpoints();
      }
コード例 #27
0
		public static void NetTcpBinding (
			TestContext context, MetadataSet doc, SecurityMode security,
			bool reliableSession, TransferMode transferMode, TestLabel label)
		{
			label.EnterScope ("netTcpBinding");

			var sd = (WS.ServiceDescription)doc.MetadataSections [0].Metadata;

			label.EnterScope ("wsdl");

			label.EnterScope ("bindings");
			Assert.That (sd.Bindings.Count, Is.EqualTo (1), label.Get ());
			var binding = sd.Bindings [0];
			Assert.That (binding.ExtensibleAttributes, Is.Null, label.Get ());
			Assert.That (binding.Extensions, Is.Not.Null, label.Get ());

			WS.Soap12Binding soap = null;
			XmlElement xml = null;
			
			foreach (var ext in binding.Extensions) {
				if (ext is WS.Soap12Binding)
					soap = (WS.Soap12Binding)ext;
				else if (ext is XmlElement)
					xml = (XmlElement)ext;
			}
			
			CheckSoapBinding (soap, "http://schemas.microsoft.com/soap/tcp", label);

			label.EnterScope ("policy-xml");
			Assert.That (xml, Is.Not.Null, label.Get ());
			var assertions = AssertPolicy (sd, xml, label);
			Assert.That (assertions, Is.Not.Null, label.Get ());
			AssertPolicy (assertions, BinaryEncodingQName, label);
			AssertPolicy (assertions, UsingAddressingQName, label);
			if (transferMode == TransferMode.Streamed)
				AssertPolicy (assertions, StreamedTransferQName, label);
			switch (security) {
			case SecurityMode.Message:
				AssertPolicy (assertions, SymmetricBindingQName, label);
				AssertPolicy (assertions, Wss11QName, label);
				AssertPolicy (assertions, Trust10QName, label);
				break;
			case SecurityMode.Transport:
				AssertPolicy (assertions, TransportBindingQName, label);
				break;
			case SecurityMode.TransportWithMessageCredential:
				AssertPolicy (assertions, TransportBindingQName, label);
				AssertPolicy (assertions, EndorsingSupportingQName, label);
				AssertPolicy (assertions, Wss11QName, label);
				AssertPolicy (assertions, Trust10QName, label);
				break;
			default:
				break;
			}
			if (reliableSession)
				AssertPolicy (assertions, ReliableSessionQName, label);
			Assert.That (assertions.Count, Is.EqualTo (0), label.Get ());
			label.LeaveScope ();

			label.EnterScope ("services");
			Assert.That (sd.Services, Is.Not.Null, label.Get ());
			Assert.That (sd.Services.Count, Is.EqualTo (1), label.Get ());
			var service = sd.Services [0];
			Assert.That (service.Ports, Is.Not.Null, label.Get ());
			Assert.That (service.Ports.Count, Is.EqualTo (1), label.Get ());
			var port = service.Ports [0];

			label.EnterScope ("port");
			Assert.That (port.Extensions, Is.Not.Null, label.Get ());
			Assert.That (port.Extensions.Count, Is.EqualTo (2), label.Get ());

			WS.Soap12AddressBinding soap_addr_binding = null;
			XmlElement port_xml = null;
			foreach (var extension in port.Extensions) {
				if (extension is WS.Soap12AddressBinding)
					soap_addr_binding = (WS.Soap12AddressBinding)extension;
				else if (extension is XmlElement)
					port_xml = (XmlElement)extension;
				else
					Assert.Fail (label.Get ());
			}
			Assert.That (soap_addr_binding, Is.Not.Null, label.Get ());
			Assert.That (port_xml, Is.Not.Null, label.Get ());
			Assert.That (port_xml.NamespaceURI, Is.EqualTo (Wsa10Namespace), label.Get ());
			Assert.That (port_xml.LocalName, Is.EqualTo ("EndpointReference"), label.Get ());
			label.LeaveScope ();
			label.LeaveScope ();

			label.LeaveScope (); // wsdl

			var importer = new WsdlImporter (doc);

			label.EnterScope ("bindings");
			var bindings = importer.ImportAllBindings ();
			CheckImportErrors (importer, label);
			Assert.That (bindings, Is.Not.Null, label.Get ());
			Assert.That (bindings.Count, Is.EqualTo (1), label.Get ());
			
			CheckNetTcpBinding (
				bindings [0], security, reliableSession,
				transferMode, label);
			label.LeaveScope ();

			label.EnterScope ("endpoints");
			var endpoints = importer.ImportAllEndpoints ();
			CheckImportErrors (importer, label);
			Assert.That (endpoints, Is.Not.Null, label.Get ());
			Assert.That (endpoints.Count, Is.EqualTo (1), label.Get ());
			
			CheckEndpoint (endpoints [0], MetadataSamples.NetTcpUri, label);
			label.LeaveScope ();

			label.LeaveScope ();
		}
コード例 #28
0
ファイル: MetadataHelper.cs プロジェクト: gpanayir/sffwk
        public static ServiceEndpoint[] GetEndpoints(string mexAddress)
        {
            if (String.IsNullOrEmpty(mexAddress))
            {
                Debug.Assert(false, "Empty address");
                return null;
            }
            Uri address = new Uri(mexAddress);
            ServiceEndpointCollection endpoints = null;

            if (address.Scheme == "http")
            {
                HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
                httpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;

                //Try the HTTP MEX Endpoint
                try
                {
                    endpoints = QueryMexEndpoint(mexAddress, httpBindingElement);
                }
                catch
                { }

                //Try over HTTP-GET
                if (endpoints == null)
                {
                    string httpGetAddress = mexAddress;
                    if (mexAddress.EndsWith("?wsdl") == false)
                    {
                        httpGetAddress += "?wsdl";
                    }
                    CustomBinding binding = new CustomBinding(httpBindingElement);
                    MetadataExchangeClient mexClient = new MetadataExchangeClient(binding);
                    MetadataSet metadata = mexClient.GetMetadata(new Uri(httpGetAddress), MetadataExchangeClientMode.HttpGet);
                    MetadataImporter importer = new WsdlImporter(metadata);
                    endpoints = importer.ImportAllEndpoints();
                }
            }
            if (address.Scheme == "https")
            {
                HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
                httpsBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;

                //Try the HTTPS MEX Endpoint
                try
                {
                    endpoints = QueryMexEndpoint(mexAddress, httpsBindingElement);
                }
                catch
                { }

                //Try over HTTPS-GET
                if (endpoints == null)
                {
                    string httpsGetAddress = mexAddress;
                    if (mexAddress.EndsWith("?wsdl") == false)
                    {
                        httpsGetAddress += "?wsdl";
                    }
                    CustomBinding binding = new CustomBinding(httpsBindingElement);
                    MetadataExchangeClient mexClient = new MetadataExchangeClient(binding);
                    MetadataSet metadata = mexClient.GetMetadata(new Uri(httpsGetAddress), MetadataExchangeClientMode.HttpGet);
                    MetadataImporter importer = new WsdlImporter(metadata);
                    endpoints = importer.ImportAllEndpoints();
                }
            }
            if (address.Scheme == "net.tcp")
            {
                TcpTransportBindingElement tcpBindingElement = new TcpTransportBindingElement();
                tcpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                endpoints = QueryMexEndpoint(mexAddress, tcpBindingElement);
            }
            if (address.Scheme == "net.pipe")
            {
                NamedPipeTransportBindingElement ipcBindingElement = new NamedPipeTransportBindingElement();
                ipcBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                endpoints = QueryMexEndpoint(mexAddress, ipcBindingElement);
            }
            return endpoints.ToArray();
        }
コード例 #29
0
ファイル: ConfigurationHelper.cs プロジェクト: DesmondNgW/API
 /// <summary>
 /// 根据元数据发布地址生成代理类
 /// </summary>
 /// <param name="address">元数据地址</param>
 /// <param name="mode">交换元数据方式</param>
 /// <param name="outPutProxyFile">代理文件路径</param>
 /// <param name="outPutConfigFile">配置文件路径</param>
 private static void GenerateWCfProxyAndConfig(string address, Entities.MetadataExchangeClientMode mode, string outPutProxyFile, string outPutConfigFile)
 {
     var mexClient = new MetadataExchangeClient(new Uri(address), (System.ServiceModel.Description.MetadataExchangeClientMode) mode);
     var metadataSet = mexClient.GetMetadata();
     var importer = new WsdlImporter(metadataSet);
     var codeCompileUnit = new CodeCompileUnit();
     var config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = outPutConfigFile }, ConfigurationUserLevel.None);
     var generator = new ServiceContractGenerator(codeCompileUnit, config);
     foreach (var endpoint in importer.ImportAllEndpoints())
     {
         generator.GenerateServiceContractType(endpoint.Contract);
         ChannelEndpointElement element;
         generator.GenerateServiceEndpoint(endpoint, out element);
     }
     generator.Configuration.Save();
     var provider = CodeDomProvider.CreateProvider("CSharp");
     using (var sw = new StreamWriter(outPutProxyFile))
     {
         var textWriter = new IndentedTextWriter(sw);
         var options = new CodeGeneratorOptions();
         provider.GenerateCodeFromCompileUnit(codeCompileUnit, textWriter, options);
     }
 }
コード例 #30
0
        /// <summary>
        /// Given a WSDL importer, a set of metadata files and a compile unit, import the metadata
        /// files.
        /// </summary>
        /// <param name="importer"></param>
        /// <param name="compileUnit"></param>
        /// <param name="generationErrors">
        /// Errors encountered whie importing the model. Any new errors will be appended to this list.
        /// </param>
        /// <param name="serviceEndpointList">List of endpoints imported</param>
        /// <param name="bindingCollection">The collection of bindings imported</param>
        /// <param name="contractCollection">The collection of contracts imported</param>
        protected static void ImportWCFModel(WsdlImporter importer,
                                          System.CodeDom.CodeCompileUnit compileUnit,
                                          IList<ProxyGenerationError> generationErrors,
                                          out List<ServiceEndpoint> serviceEndpointList,
                                          out IEnumerable<System.ServiceModel.Channels.Binding> bindingCollection,
                                          out IEnumerable<ContractDescription> contractCollection)
        {
            // We want to remove soap1.2 endpoints for ASMX references, but we can't use the "normal" way 
            // of using a IWsdlImportExtension to do so since BeforeImport is called too late (DevDiv 7857)
            // If DevDiv 7857 is fixed, we can remove the following two lines and instead add the 
            // AsmxEndpointPickerExtension to the importer's wsdl import extensions...
            IWsdlImportExtension asmxFixerUpper = new AsmxEndpointPickerExtension();
            asmxFixerUpper.BeforeImport(importer.WsdlDocuments, null, null);

            // NOTE: we should import Endpoint before Contracts, otherwise some information (related to binding) will be lost in the model (devdiv: 22396)
            serviceEndpointList = new List<ServiceEndpoint>();

            //
            // First we import all the endpoints (ports). This is required so that any WsdlImportExtension's BeforeImport
            // gets called before we actually try to import anything from the WSDL object model. 
            // If we don't do this, we run into problems if any wsdl import extensions want to delete a specific port
            // and this port happens to be the first port we try to import (you can't interrupt the import)
            importer.ImportAllEndpoints();

            //
            // We need to go through each endpoint element and "re-import" it in order to get the mapping
            // between the wsdlPort and the ServiceEndpoint... Importing the same endpoint twice is a no-op
            // as far as the endpoint collection is concerned - it is simply a hashtable lookup to retreive 
            // the already generated information...
            //
            foreach (System.Web.Services.Description.ServiceDescription wsdlServiceDescription in importer.WsdlDocuments)
            {
                foreach (System.Web.Services.Description.Service wsdlService in wsdlServiceDescription.Services)
                {
                    foreach (System.Web.Services.Description.Port servicePort in wsdlService.Ports)
                    {
                        try
                        {
                            ServiceEndpoint newEndpoint = importer.ImportEndpoint(servicePort);
                            serviceEndpointList.Add(newEndpoint);
                        }
                        catch (InvalidOperationException)
                        {
                            // Invalid operation exceptions should already be in the errors collection for the importer, so we don't
                            // need to add another generationError. The most probable cause for this is that the we failed to import 
                            // the endpoint...
                        }
                        catch (Exception ex)
                        { // It is bad, because WsdlImporter.WsdlImportException is a private class
                            generationErrors.Add(new ProxyGenerationError(ProxyGenerationError.GeneratorState.GenerateCode, wsdlServiceDescription.RetrievalUrl, ex));
                        }
                    }
                }
            }


            bindingCollection = importer.ImportAllBindings();
            System.Diagnostics.Debug.Assert(bindingCollection != null, "The importer should never return a NULL binding collection!");

            contractCollection = importer.ImportAllContracts();
            System.Diagnostics.Debug.Assert(contractCollection != null, "The importer should never return a NULL contract collection!");

            foreach (MetadataConversionError error in importer.Errors)
            {
                generationErrors.Add(new ProxyGenerationError(error));
            }
        }
コード例 #31
0
ファイル: Driver.cs プロジェクト: Zman0169/mono
		void Run (string [] args)
		{
			co.ProcessArgs (args);
			if (co.Usage) {
				co.DoUsage ();
				return;
			}

			if (co.Version) {
				co.DoVersion ();
				return;
			}

			if (co.Help || co.RemainingArguments.Count == 0) {
				co.DoHelp ();
				return;
			}
			if (!co.NoLogo)
				co.ShowBanner ();

			CodeCompileUnit ccu = new CodeCompileUnit ();
			CodeNamespace cns = new CodeNamespace (co.Namespace);
			ccu.Namespaces.Add (cns);

			generator = new ServiceContractGenerator (ccu);
			generator.Options = GetGenerationOption ();
			generator.Options |=ServiceContractGenerationOptions.ChannelInterface;

			code_provider = GetCodeProvider ();
			MetadataSet metadata = null;

			// For now only assemblyPath is supported.
			foreach (string arg in co.RemainingArguments) {
				if (!File.Exists (arg)) {
					Uri uri = null;
					if (Uri.TryCreate (arg, UriKind.Absolute, out uri)) {
						metadata = ResolveWithDisco (arg);
						if (metadata == null)
							metadata = ResolveWithWSMex (arg);

							continue;
					}
				} else {
					FileInfo fi = new FileInfo (arg);
					switch (fi.Extension) {
					case ".exe":
					case ".dll":
						GenerateContractType (fi.FullName);
						break;
					default:
						throw new NotSupportedException ("Not supported file extension: " + fi.Extension);
					}
				}
			}

			if (metadata != null)
			{
				List<IWsdlImportExtension> list = new List<IWsdlImportExtension> ();
				list.Add (new TransportBindingElementImporter ());
				//list.Add (new DataContractSerializerMessageContractImporter ());
				list.Add (new XmlSerializerMessageContractImporter ());

				//WsdlImporter importer = new WsdlImporter (metadata, null, list);
				WsdlImporter importer = new WsdlImporter (metadata);
				ServiceEndpointCollection endpoints = importer.ImportAllEndpoints ();
				Collection<ContractDescription> contracts = new Collection<ContractDescription> ();
				if (endpoints.Count > 0) {
					foreach (var se in endpoints)
						contracts.Add (se.Contract);
				} else {
					foreach (var cd in importer.ImportAllContracts ())
						contracts.Add (cd);
				}

				Console.WriteLine ("Generating files..");

				// FIXME: could better become IWsdlExportExtension
				foreach (ContractDescription cd in contracts) {
					if (co.GenerateMoonlightProxy) {
						var moonctx = new MoonlightChannelBaseContext ();
						cd.Behaviors.Add (new MoonlightChannelBaseContractExtension (moonctx, co.GenerateMonoTouchProxy));
						foreach (var od in cd.Operations)
							od.Behaviors.Add (new MoonlightChannelBaseOperationExtension (moonctx, co.GenerateMonoTouchProxy));
						generator.GenerateServiceContractType (cd);
						moonctx.Fixup ();
					}
					else
						generator.GenerateServiceContractType (cd);
				}
			}
			/*if (cns.Types.Count == 0) {
				Console.Error.WriteLine ("Argument assemblies have no types.");
				Environment.Exit (1);
			}*/

			//FIXME: Generate .config 

			Console.WriteLine (GetOutputFilename ());
			using (TextWriter w = File.CreateText (GetOutputFilename ())) {
				code_provider.GenerateCodeFromCompileUnit (ccu, w, null);
			}
		}