Exemple #1
0
        //MetadataExchangeClient can only download data from a local wsdl file, if it is a file we user the DiscoveryClientProtocol
        void DownloadFile(out List<wsdlDescription.ServiceDescription> descriptions, out List<XmlSchema> schemas)
        {
            descriptions = new List<wsdlDescription.ServiceDescription>();
            schemas = new List<XmlSchema>();

            DiscoveryClientProtocol client = new DiscoveryClientProtocol();

            //download document
            client.AllowAutoRedirect = true;
            client.Timeout = _timeoutInSeconds * 1000;

            client.Documents.Clear();
            client.DiscoverAny(_wsdlEndpoint);

            client.ResolveAll();

            foreach (var v in client.Documents.Values) {
                if (v is wsdlDescription.ServiceDescription) {
                    descriptions.Add((wsdlDescription.ServiceDescription)v);
                }
                else if (v is XmlSchema) {
                    schemas.Add((XmlSchema)v);
                }
            }
        }
        DiscoveryClientDocumentCollection DiscoverDocuments()
        {
            var protocol = new DiscoveryClientProtocol {
                AllowAutoRedirect = true,
                Credentials = credentials ?? CredentialCache.DefaultCredentials
            };

            protocol.DiscoverAny(uri);
            protocol.ResolveAll();

            return protocol.Documents;
        }
		/// <summary>Read the specified protocol into an ServiceDescriptionImporter.</summary>
		/// <param name="protocol">A DiscoveryClientProtocol containing the service protocol detail.</param>
		/// <returns>A ServiceDescriptionImporter for the specified protocol.</returns>
		public static ServiceDescriptionImporter ReadServiceDescriptionImporter(DiscoveryClientProtocol protocol)
		{
   			// Service Description Importer
			ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
			importer.ProtocolName = "Soap";
			// Add all the schemas and service descriptions to the importer
			protocol.ResolveAll ();
			foreach (object doc in protocol.Documents.Values)
			{
				if (doc is ServiceDescription)
					importer.AddServiceDescription((ServiceDescription)doc, null, null);
				else if (doc is XmlSchema)
					importer.Schemas.Add((XmlSchema)doc);
			}			
			return importer;
		}
		/// <summary>
		/// Resolves metadata from the specified URL.
		/// </summary>
		/// <param name="url">The URL.</param>
		/// <returns>A list of metadata sections.</returns>
		public static IEnumerable<MetadataSection> Resolve(string url)
		{
			MetadataSet metadataSet = new MetadataSet();
			DiscoveryClientProtocol discoveryClient = new DiscoveryClientProtocol
			{
				UseDefaultCredentials = true,
				AllowAutoRedirect = true
			};
			discoveryClient.DiscoverAny(url);
			discoveryClient.ResolveAll();
			foreach (object document in discoveryClient.Documents.Values)
			{
				AddDocumentToSet(metadataSet, document);
			}

			return metadataSet.MetadataSections;
		}
        /// <summary>
        /// Gets the web service description from the supplied URL.
        /// </summary>
        /// <param name="url">
        /// The URL where XML Web services discovery begins.
        /// </param>
        /// <param name="username">
        /// The username.
        /// </param>
        /// <param name="password">
        /// The password.
        /// </param>
        /// <returns>
        /// The <see cref="WebServiceDescription"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="url"/> parameter is null.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// The <paramref name="url"/> parameter is a valid URL, but does not point to a valid discovery document, service description, or XSD schema.
        /// </exception>
        public WebServiceDescription GetServiceDescription(string url, string username, string password)
        {
            if (url == null)
                throw new ArgumentNullException("url");

            url = url.Trim();

            var protocol = new DiscoveryClientProtocol { AllowAutoRedirect = true, Credentials = CredentialCache.DefaultCredentials };
            if (!string.IsNullOrEmpty(username))
                protocol.Credentials = new NetworkCredential(username, password);

            try
            {
                protocol.DiscoverAny(url);
            }
            catch (InvalidOperationException)
            {
                if (!url.EndsWith("?WSDL", StringComparison.InvariantCultureIgnoreCase))
                    protocol.DiscoverAny(url + "?WSDL");
                else
                    throw;
            }

            protocol.ResolveAll();

            var serviceDescription = new WebServiceDescription();

            foreach (DictionaryEntry entry in protocol.References)
            {
                var contractReference = entry.Value as ContractReference;

                if (contractReference != null)
                    serviceDescription.ServiceDescriptions.Add(contractReference.Contract);

                var schemaReference = entry.Value as SchemaReference;

                if (schemaReference != null)
                    serviceDescription.XmlSchemas.Add(schemaReference.Schema);
            }

            return serviceDescription;
        }
Exemple #6
0
		/// <summary>Read the specified protocol into an ServiceDescriptionImporter.</summary>
		/// <param name="protocol">A DiscoveryClientProtocol containing the service protocol detail.</param>
		/// <returns>A ServiceDescriptionImporter for the specified protocol.</returns>
		public static ServiceDescriptionImporter ReadServiceDescriptionImporter(DiscoveryClientProtocol protocol)
		{
   			// Service Description Importer
			var importer = new ServiceDescriptionImporter();
			importer.ProtocolName = "Soap";
			// Add all the schemas and service descriptions to the importer
			protocol.ResolveAll ();
			foreach (object doc in protocol.Documents.Values)
			{
				var serviceDescription = doc as ServiceDescription;
				if (serviceDescription != null)
					importer.AddServiceDescription (serviceDescription, null, null);
				else {
					var xmlSchema = doc as XmlSchema;
					if (xmlSchema != null)
						importer.Schemas.Add (xmlSchema);
				}
			}			
			return importer;
		}
		public void ReadWriteTest ()
		{
			string directory = Path.Combine (Path.GetTempPath (), Path.GetRandomFileName ());
			Directory.CreateDirectory (directory);
			try {
				string url = "http://www.w3schools.com/WebServices/TempConvert.asmx";
				var p1 = new DiscoveryClientProtocol ();
				p1.DiscoverAny (url);
				p1.ResolveAll ();

				p1.WriteAll (directory, "Reference.map");

				var p2 = new DiscoveryClientProtocol ();
				var results = p2.ReadAll (Path.Combine (directory, "Reference.map"));

				Assert.AreEqual (2, results.Count);
				Assert.AreEqual ("TempConvert.disco", results [0].Filename);
				Assert.AreEqual ("TempConvert.wsdl", results [1].Filename);
			} finally {
				Directory.Delete (directory, true);
			}
		}
        public Collection<MetadataSection> DownloadMetadata(string serviceUrl)
        {
            Uri serviceUri = new Uri(serviceUrl);

            Collection<MetadataSection> metadataSections;
            if (TryDownloadByMetadataExchangeClient(serviceUri, out metadataSections))
            {
                return metadataSections;
            }
            else
            {
                if (TryDownloadByMetadataExchangeClient(GetDefaultMexUri(serviceUri), out metadataSections))
                {
                    return metadataSections;
                }
            }

            bool supporstDiscoveryClientProtocol = serviceUri.Scheme == Uri.UriSchemeHttp || serviceUri.Scheme == Uri.UriSchemeHttps;
            if (supporstDiscoveryClientProtocol)
            {
                DiscoveryClientProtocol disco = new DiscoveryClientProtocol();
                disco.AllowAutoRedirect = true;
                disco.UseDefaultCredentials = true;
                disco.DiscoverAny(serviceUrl);
                disco.ResolveAll();

                Collection<MetadataSection> result = new Collection<MetadataSection>();
                if (disco.Documents.Values != null)
                {
                    foreach (object document in disco.Documents.Values)
                    {
                        AddDocumentToResults(document, result);
                    }
                }
                return result;
            }
            return null;
        }
Exemple #9
0
        public model.WebSvc Generate(string filePath)
        {
            List<wsdlDescription.ServiceDescription> descriptions = new List<wsdlDescription.ServiceDescription>();
            List<XmlSchema> schemas = new List<XmlSchema>();

            DiscoveryClientProtocol client = new DiscoveryClientProtocol();

            //load Document from file
            client.AllowAutoRedirect = true;
            client.Documents.Clear();
            client.DiscoverAny(filePath);
            client.ResolveAll();

            foreach (var v in client.Documents.Values) {
                if (v is wsdlDescription.ServiceDescription) {
                    descriptions.Add((wsdlDescription.ServiceDescription)v);
                }
                else if (v is XmlSchema) {
                    schemas.Add((XmlSchema)v);
                }
            }

            return Generate(filePath, descriptions, schemas);
        }
        /// <summary>
        /// Gets XML Web Services documents from a Spring resource.
        /// </summary>
        private DiscoveryClientDocumentCollection GetWsDocuments(IResource resource)
        {
            try
            {
                if (ServiceUri is UrlResource || 
                    ServiceUri is FileSystemResource)
                {
                    DiscoveryClientProtocol dcProtocol = new DiscoveryClientProtocol();
                    dcProtocol.AllowAutoRedirect = true;
                    dcProtocol.Credentials = CreateCredentials();
                    dcProtocol.Proxy = ConfigureProxy();
                    dcProtocol.DiscoverAny(resource.Uri.AbsoluteUri);
                    dcProtocol.ResolveAll();

                    return dcProtocol.Documents;
                }
                else
                {
                    DiscoveryClientDocumentCollection dcdc = new DiscoveryClientDocumentCollection();
                    dcdc[resource.Description] = ServiceDescription.Read(resource.InputStream);
                    return dcdc;
                }
            }
            catch (Exception ex)
            {
                throw new ArgumentException(String.Format("Couldn't retrieve the description of the web service located at '{0}'.", resource.Description), ex);
            }
        }
        private static CodeCompileUnit ImportServiceDescription(string url)
        {
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
            importer.ProtocolName = "Soap";
            importer.Style = ServiceDescriptionImportStyle.Client;

            DiscoveryClientProtocol dcc = new DiscoveryClientProtocol();
            dcc.DiscoverAny(url);
            dcc.ResolveAll();

            foreach (object doc in dcc.Documents.Values)
            {
                if(doc is ServiceDescription)
                    importer.AddServiceDescription(doc as ServiceDescription, string.Empty, string.Empty);

                else if(doc is XmlSchema)
                    importer.Schemas.Add(doc as XmlSchema);
            }

            if (importer.ServiceDescriptions.Count == 0)
            {
                throw new Exception("No WSDL document was found at the url " + url);
            }

            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(new CodeNamespace(RootNamespace));

            ServiceDescriptionImportWarnings warnings = importer.Import(ccu.Namespaces[0], ccu);

            if ((warnings & ServiceDescriptionImportWarnings.NoCodeGenerated) > 0)
            {
                throw new Exception("No code generated");
            }

            return ccu;
        }
        private void DoMex()
        {
            string mexAddress;
            string mexBindingSectionName;
            string mexBindingConfiguration;
            string contract;
            string contractNamespace;
            string binding;
            string bindingNamespace;
            string address;
            string spnIdentity = null;
            string upnIdentity = null;
            string dnsIdentity = null;
            string mexSpnIdentity = null;
            string mexUpnIdentity = null;
            string mexDnsIdentity = null;
            string serializer = null;

            EndpointIdentity identity = null;
            EndpointIdentity mexIdentity = null;

            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Contract, out contract);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.ContractNamespace, out contractNamespace);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.BindingNamespace, out bindingNamespace);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Binding, out binding);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexAddress, out mexAddress);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexBinding, out mexBindingSectionName);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexBindingConfiguration, out mexBindingConfiguration);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Address, out address);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.SpnIdentity, out spnIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.UpnIdentity, out upnIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.DnsIdentity, out dnsIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexSpnIdentity, out mexSpnIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexUpnIdentity, out mexUpnIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexDnsIdentity, out mexDnsIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Serializer, out serializer);

            if (string.IsNullOrEmpty(mexAddress))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerMexAddressNotSpecified)));

            if (!string.IsNullOrEmpty(mexSpnIdentity))
            {
                if ((!string.IsNullOrEmpty(mexUpnIdentity)) || (!string.IsNullOrEmpty(mexDnsIdentity)))
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentityForMex)));
                mexIdentity = EndpointIdentity.CreateSpnIdentity(mexSpnIdentity);
            }
            else if (!string.IsNullOrEmpty(mexUpnIdentity))
            {
                if ((!string.IsNullOrEmpty(mexSpnIdentity)) || (!string.IsNullOrEmpty(mexDnsIdentity)))
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentityForMex)));
                mexIdentity = EndpointIdentity.CreateUpnIdentity(mexUpnIdentity);
            }
            else if (!string.IsNullOrEmpty(mexDnsIdentity))
            {
                if ((!string.IsNullOrEmpty(mexSpnIdentity)) || (!string.IsNullOrEmpty(mexUpnIdentity)))
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentityForMex)));
                mexIdentity = EndpointIdentity.CreateDnsIdentity(mexDnsIdentity);
            }
            else
                mexIdentity = null;

            if (string.IsNullOrEmpty(address))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerAddressNotSpecified)));

            if (string.IsNullOrEmpty(contract))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerContractNotSpecified)));

            if (string.IsNullOrEmpty(binding))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerBindingNotSpecified)));

            if (string.IsNullOrEmpty(bindingNamespace))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerBindingNamespacetNotSpecified)));

            if (!string.IsNullOrEmpty(spnIdentity))
            {
                if ((!string.IsNullOrEmpty(upnIdentity)) || (!string.IsNullOrEmpty(dnsIdentity)))
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity)));
                identity = EndpointIdentity.CreateSpnIdentity(spnIdentity);
            }
            else if (!string.IsNullOrEmpty(upnIdentity))
            {
                if ((!string.IsNullOrEmpty(spnIdentity)) || (!string.IsNullOrEmpty(dnsIdentity)))
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity)));
                identity = EndpointIdentity.CreateUpnIdentity(upnIdentity);
            }
            else if (!string.IsNullOrEmpty(dnsIdentity))
            {
                if ((!string.IsNullOrEmpty(spnIdentity)) || (!string.IsNullOrEmpty(upnIdentity)))
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity)));
                identity = EndpointIdentity.CreateDnsIdentity(dnsIdentity);
            }
            else
                identity = null;

            MetadataExchangeClient resolver = null;
            EndpointAddress mexEndpointAddress = new EndpointAddress(new Uri(mexAddress), mexIdentity);

            if (!string.IsNullOrEmpty(mexBindingSectionName))
            {
                Binding mexBinding = null;
                try
                {
                    mexBinding = ConfigLoader.LookupBinding(mexBindingSectionName, mexBindingConfiguration);
                }
                catch (System.Configuration.ConfigurationErrorsException)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MexBindingNotFoundInConfig, mexBindingSectionName)));
                }


                if (null == mexBinding)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MexBindingNotFoundInConfig, mexBindingSectionName)));

                resolver = new MetadataExchangeClient(mexBinding);
            }
            else if (string.IsNullOrEmpty(mexBindingConfiguration))
                resolver = new MetadataExchangeClient(mexEndpointAddress);
            else
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerMexBindingSectionNameNotSpecified)));

            if (null != mexIdentity)
            {
                // To disable AllowNtlm warning.
#pragma warning disable 618
                resolver.SoapCredentials.Windows.AllowNtlm = false;
#pragma warning restore 618

            }

            bool removeXmlSerializerImporter = false;

            if (!String.IsNullOrEmpty(serializer))
            {
                if ("xml" != serializer && "datacontract" != serializer)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorectSerializer)));

                if ("xml" == serializer)
                    useXmlSerializer = true;
                else
                    removeXmlSerializerImporter = true; // specifying datacontract will explicitly remove the Xml importer
                // if this parameter is not set we will simply use indigo defaults
            }

            ServiceEndpoint endpoint = null;
            ServiceEndpointCollection serviceEndpointsRetrieved = null;

            WsdlImporter importer;

            try
            {
                MetadataSet metadataSet = resolver.GetMetadata(mexEndpointAddress);

                if (useXmlSerializer)
                    importer = CreateXmlSerializerImporter(metadataSet);
                else
                {
                    if (removeXmlSerializerImporter)
                        importer = CreateDataContractSerializerImporter(metadataSet);
                    else
                        importer = new WsdlImporter(metadataSet);
                }

                serviceEndpointsRetrieved = this.ImportWsdlPortType(new XmlQualifiedName(contract, contractNamespace), importer);
                ComPlusMexChannelBuilderMexCompleteTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationMexMonikerMetadataExchangeComplete, SR.TraceCodeComIntegrationMexMonikerMetadataExchangeComplete, serviceEndpointsRetrieved);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                    throw;

                if (UriSchemeSupportsDisco(mexEndpointAddress.Uri))
                {
                    try
                    {
                        DiscoNS.DiscoveryClientProtocol discoClient = new DiscoNS.DiscoveryClientProtocol();
                        discoClient.UseDefaultCredentials = true;
                        discoClient.AllowAutoRedirect = true;

                        discoClient.DiscoverAny(mexEndpointAddress.Uri.AbsoluteUri);
                        discoClient.ResolveAll();
                        MetadataSet metadataSet = new MetadataSet();

                        foreach (object document in discoClient.Documents.Values)
                        {
                            AddDocumentToSet(metadataSet, document);
                        }

                        if (useXmlSerializer)
                            importer = CreateXmlSerializerImporter(metadataSet);
                        else
                        {
                            if (removeXmlSerializerImporter)
                                importer = CreateDataContractSerializerImporter(metadataSet);
                            else
                                importer = new WsdlImporter(metadataSet);
                        }

                        serviceEndpointsRetrieved = this.ImportWsdlPortType(new XmlQualifiedName(contract, contractNamespace), importer);
                        ComPlusMexChannelBuilderMexCompleteTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationMexMonikerMetadataExchangeComplete, SR.TraceCodeComIntegrationMexMonikerMetadataExchangeComplete, serviceEndpointsRetrieved);
                    }
                    catch (Exception ex)
                    {
                        if (Fx.IsFatal(ex))
                            throw;

                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerFailedToDoMexRetrieve, ex.Message)));
                    }
                }
                else
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerFailedToDoMexRetrieve, e.Message)));
            }

            if (serviceEndpointsRetrieved.Count == 0)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerContractNotFoundInRetreivedMex)));

            foreach (ServiceEndpoint retrievedEndpoint in serviceEndpointsRetrieved)
            {
                Binding bindingSelected = retrievedEndpoint.Binding;
                if ((bindingSelected.Name == binding) && (bindingSelected.Namespace == bindingNamespace))
                {
                    endpoint = retrievedEndpoint;
                    break;
                }
            }

            if (endpoint == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerNoneOfTheBindingMatchedTheSpecifiedBinding)));

            contractDescription = endpoint.Contract;
            this.serviceEndpoint = new ServiceEndpoint(contractDescription, endpoint.Binding, new EndpointAddress(new Uri(address), identity, (AddressHeaderCollection)null));

            ComPlusMexChannelBuilderTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationMexChannelBuilderLoaded,
                SR.TraceCodeComIntegrationMexChannelBuilderLoaded, endpoint.Contract, endpoint.Binding, address);
        }
 private void ProcessRemoteUrls(DiscoveryClientProtocol client, StringCollection urls, XmlSchemas schemas,
                                ServiceDescriptionCollection descriptions)
 {
     foreach (string text1 in urls)
     {
         try
         {
             DiscoveryDocument document1 = client.DiscoverAny(text1);
             client.ResolveAll();
             continue;
         }
         catch (Exception exception1)
         {
             throw new InvalidOperationException("General Error " + text1, exception1);
         }
     }
     foreach (DictionaryEntry entry1 in client.Documents)
     {
         AddDocument((string) entry1.Key, entry1.Value, schemas, descriptions);
     }
 }
        private void DoMex()
        {
            string mexAddress;
            string mexBindingSectionName;
            string mexBindingConfiguration;
            string contract;
            string contractNamespace;
            string binding;
            string bindingNamespace;
            string address;
            string spnIdentity    = null;
            string upnIdentity    = null;
            string dnsIdentity    = null;
            string mexSpnIdentity = null;
            string mexUpnIdentity = null;
            string mexDnsIdentity = null;
            string serializer     = null;

            EndpointIdentity identity    = null;
            EndpointIdentity mexIdentity = null;

            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Contract, out contract);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.ContractNamespace, out contractNamespace);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.BindingNamespace, out bindingNamespace);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Binding, out binding);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexAddress, out mexAddress);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexBinding, out mexBindingSectionName);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexBindingConfiguration, out mexBindingConfiguration);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Address, out address);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.SpnIdentity, out spnIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.UpnIdentity, out upnIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.DnsIdentity, out dnsIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexSpnIdentity, out mexSpnIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexUpnIdentity, out mexUpnIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexDnsIdentity, out mexDnsIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Serializer, out serializer);

            if (string.IsNullOrEmpty(mexAddress))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerMexAddressNotSpecified)));
            }

            if (!string.IsNullOrEmpty(mexSpnIdentity))
            {
                if ((!string.IsNullOrEmpty(mexUpnIdentity)) || (!string.IsNullOrEmpty(mexDnsIdentity)))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentityForMex)));
                }
                mexIdentity = EndpointIdentity.CreateSpnIdentity(mexSpnIdentity);
            }
            else if (!string.IsNullOrEmpty(mexUpnIdentity))
            {
                if ((!string.IsNullOrEmpty(mexSpnIdentity)) || (!string.IsNullOrEmpty(mexDnsIdentity)))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentityForMex)));
                }
                mexIdentity = EndpointIdentity.CreateUpnIdentity(mexUpnIdentity);
            }
            else if (!string.IsNullOrEmpty(mexDnsIdentity))
            {
                if ((!string.IsNullOrEmpty(mexSpnIdentity)) || (!string.IsNullOrEmpty(mexUpnIdentity)))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentityForMex)));
                }
                mexIdentity = EndpointIdentity.CreateDnsIdentity(mexDnsIdentity);
            }
            else
            {
                mexIdentity = null;
            }

            if (string.IsNullOrEmpty(address))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerAddressNotSpecified)));
            }

            if (string.IsNullOrEmpty(contract))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerContractNotSpecified)));
            }

            if (string.IsNullOrEmpty(binding))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerBindingNotSpecified)));
            }

            if (string.IsNullOrEmpty(bindingNamespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerBindingNamespacetNotSpecified)));
            }

            if (!string.IsNullOrEmpty(spnIdentity))
            {
                if ((!string.IsNullOrEmpty(upnIdentity)) || (!string.IsNullOrEmpty(dnsIdentity)))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity)));
                }
                identity = EndpointIdentity.CreateSpnIdentity(spnIdentity);
            }
            else if (!string.IsNullOrEmpty(upnIdentity))
            {
                if ((!string.IsNullOrEmpty(spnIdentity)) || (!string.IsNullOrEmpty(dnsIdentity)))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity)));
                }
                identity = EndpointIdentity.CreateUpnIdentity(upnIdentity);
            }
            else if (!string.IsNullOrEmpty(dnsIdentity))
            {
                if ((!string.IsNullOrEmpty(spnIdentity)) || (!string.IsNullOrEmpty(upnIdentity)))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity)));
                }
                identity = EndpointIdentity.CreateDnsIdentity(dnsIdentity);
            }
            else
            {
                identity = null;
            }

            MetadataExchangeClient resolver           = null;
            EndpointAddress        mexEndpointAddress = new EndpointAddress(new Uri(mexAddress), mexIdentity);

            if (!string.IsNullOrEmpty(mexBindingSectionName))
            {
                Binding mexBinding = null;
                try
                {
                    mexBinding = ConfigLoader.LookupBinding(mexBindingSectionName, mexBindingConfiguration);
                }
                catch (System.Configuration.ConfigurationErrorsException)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MexBindingNotFoundInConfig, mexBindingSectionName)));
                }


                if (null == mexBinding)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MexBindingNotFoundInConfig, mexBindingSectionName)));
                }

                resolver = new MetadataExchangeClient(mexBinding);
            }
            else if (string.IsNullOrEmpty(mexBindingConfiguration))
            {
                resolver = new MetadataExchangeClient(mexEndpointAddress);
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerMexBindingSectionNameNotSpecified)));
            }

            if (null != mexIdentity)
            {
                // To disable AllowNtlm warning.
#pragma warning disable 618
                resolver.SoapCredentials.Windows.AllowNtlm = false;
#pragma warning restore 618
            }

            bool removeXmlSerializerImporter = false;

            if (!String.IsNullOrEmpty(serializer))
            {
                if ("xml" != serializer && "datacontract" != serializer)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorectSerializer)));
                }

                if ("xml" == serializer)
                {
                    useXmlSerializer = true;
                }
                else
                {
                    removeXmlSerializerImporter = true; // specifying datacontract will explicitly remove the Xml importer
                }
                // if this parameter is not set we will simply use indigo defaults
            }

            ServiceEndpoint           endpoint = null;
            ServiceEndpointCollection serviceEndpointsRetrieved = null;

            WsdlImporter importer;

            try
            {
                MetadataSet metadataSet = resolver.GetMetadata(mexEndpointAddress);

                if (useXmlSerializer)
                {
                    importer = CreateXmlSerializerImporter(metadataSet);
                }
                else
                {
                    if (removeXmlSerializerImporter)
                    {
                        importer = CreateDataContractSerializerImporter(metadataSet);
                    }
                    else
                    {
                        importer = new WsdlImporter(metadataSet);
                    }
                }

                serviceEndpointsRetrieved = this.ImportWsdlPortType(new XmlQualifiedName(contract, contractNamespace), importer);
                ComPlusMexChannelBuilderMexCompleteTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationMexMonikerMetadataExchangeComplete, SR.TraceCodeComIntegrationMexMonikerMetadataExchangeComplete, serviceEndpointsRetrieved);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                if (UriSchemeSupportsDisco(mexEndpointAddress.Uri))
                {
                    try
                    {
                        DiscoNS.DiscoveryClientProtocol discoClient = new DiscoNS.DiscoveryClientProtocol();
                        discoClient.UseDefaultCredentials = true;
                        discoClient.AllowAutoRedirect     = true;

                        discoClient.DiscoverAny(mexEndpointAddress.Uri.AbsoluteUri);
                        discoClient.ResolveAll();
                        MetadataSet metadataSet = new MetadataSet();

                        foreach (object document in discoClient.Documents.Values)
                        {
                            AddDocumentToSet(metadataSet, document);
                        }

                        if (useXmlSerializer)
                        {
                            importer = CreateXmlSerializerImporter(metadataSet);
                        }
                        else
                        {
                            if (removeXmlSerializerImporter)
                            {
                                importer = CreateDataContractSerializerImporter(metadataSet);
                            }
                            else
                            {
                                importer = new WsdlImporter(metadataSet);
                            }
                        }

                        serviceEndpointsRetrieved = this.ImportWsdlPortType(new XmlQualifiedName(contract, contractNamespace), importer);
                        ComPlusMexChannelBuilderMexCompleteTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationMexMonikerMetadataExchangeComplete, SR.TraceCodeComIntegrationMexMonikerMetadataExchangeComplete, serviceEndpointsRetrieved);
                    }
                    catch (Exception ex)
                    {
                        if (Fx.IsFatal(ex))
                        {
                            throw;
                        }

                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerFailedToDoMexRetrieve, ex.Message)));
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerFailedToDoMexRetrieve, e.Message)));
                }
            }

            if (serviceEndpointsRetrieved.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerContractNotFoundInRetreivedMex)));
            }

            foreach (ServiceEndpoint retrievedEndpoint in serviceEndpointsRetrieved)
            {
                Binding bindingSelected = retrievedEndpoint.Binding;
                if ((bindingSelected.Name == binding) && (bindingSelected.Namespace == bindingNamespace))
                {
                    endpoint = retrievedEndpoint;
                    break;
                }
            }

            if (endpoint == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerNoneOfTheBindingMatchedTheSpecifiedBinding)));
            }

            contractDescription  = endpoint.Contract;
            this.serviceEndpoint = new ServiceEndpoint(contractDescription, endpoint.Binding, new EndpointAddress(new Uri(address), identity, (AddressHeaderCollection)null));

            ComPlusMexChannelBuilderTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationMexChannelBuilderLoaded,
                                                SR.TraceCodeComIntegrationMexChannelBuilderLoaded, endpoint.Contract, endpoint.Binding, address);
        }
		/// <summary>
		/// Checks the for imports.
		/// </summary>
		/// <param name="baseWSDLUrl">Base WSDL URL.</param>
		private void CheckForImports(string baseWSDLUrl)
		{
			DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
			dcp.DiscoverAny(baseWSDLUrl);
			dcp.ResolveAll();

			foreach (object osd in dcp.Documents.Values)
			{
				if (osd is ServiceDescription) sdi.AddServiceDescription((ServiceDescription)osd, null, null);
				if (osd is XmlSchema) 
				{
					// store in global schemas variable
					if (schemas == null) schemas = new XmlSchemas();
					schemas.Add((XmlSchema)osd);

					sdi.Schemas.Add((XmlSchema)osd);
				}
			}
		}
		private void ResolveDiscovery(DiscoveryClientProtocol discovery, Uri address)
		{
			discovery.UseDefaultCredentials = true;
			discovery.AllowAutoRedirect = true;
			discovery.DiscoverAny(address.AbsoluteUri);
			discovery.ResolveAll();
			ThrowOnDiscoveryErrors(discovery.Errors, address.IsFile);
		}
Exemple #17
0
		private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName)
		{
			object obj = null;
			Assembly assembly;
			DiscoveryClientProtocol discoveryClientProtocol = new DiscoveryClientProtocol();
			if (this._usedefaultcredential.IsPresent)
			{
				discoveryClientProtocol.UseDefaultCredentials = true;
			}
			if (base.ParameterSetName.Equals("Credential", StringComparison.OrdinalIgnoreCase))
			{
				discoveryClientProtocol.Credentials = this._credential.GetNetworkCredential();
			}
			try
			{
				discoveryClientProtocol.AllowAutoRedirect = true;
				discoveryClientProtocol.DiscoverAny(this._uri.ToString());
				discoveryClientProtocol.ResolveAll();
				goto Label0;
			}
			catch (WebException webException1)
			{
				WebException webException = webException1;
				ErrorRecord errorRecord = new ErrorRecord(webException, "WebException", ErrorCategory.ObjectNotFound, this._uri);
				if (webException.InnerException != null)
				{
					errorRecord.ErrorDetails = new ErrorDetails(webException.InnerException.Message);
				}
				base.WriteError(errorRecord);
				assembly = null;
			}
			catch (InvalidOperationException invalidOperationException1)
			{
				InvalidOperationException invalidOperationException = invalidOperationException1;
				ErrorRecord errorRecord1 = new ErrorRecord(invalidOperationException, "InvalidOperationException", ErrorCategory.InvalidOperation, this._uri);
				base.WriteError(errorRecord1);
				assembly = null;
			}
			return assembly;
		Label0:
			CodeNamespace codeNamespace = new CodeNamespace();
			if (!string.IsNullOrEmpty(NameSpace))
			{
				codeNamespace.Name = NameSpace;
			}
			if (!string.IsNullOrEmpty(ClassName))
			{
				CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration(ClassName);
				codeTypeDeclaration.IsClass = true;
				codeTypeDeclaration.Attributes = MemberAttributes.Public;
				codeNamespace.Types.Add(codeTypeDeclaration);
			}
			WebReference webReference = new WebReference(discoveryClientProtocol.Documents, codeNamespace);
			WebReferenceCollection webReferenceCollection = new WebReferenceCollection();
			webReferenceCollection.Add(webReference);
			CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
			codeCompileUnit.Namespaces.Add(codeNamespace);
			WebReferenceOptions webReferenceOption = new WebReferenceOptions();
			webReferenceOption.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateOldAsync;
			webReferenceOption.Verbose = true;
			CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider();
			StringCollection stringCollections = ServiceDescriptionImporter.GenerateWebReferences(webReferenceCollection, cSharpCodeProvider, codeCompileUnit, webReferenceOption);
			StringBuilder stringBuilder = new StringBuilder();
			StringWriter stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture);
			try
			{
				cSharpCodeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, stringWriter, null);
			}
			catch (NotImplementedException notImplementedException1)
			{
				NotImplementedException notImplementedException = notImplementedException1;
				ErrorRecord errorRecord2 = new ErrorRecord(notImplementedException, "NotImplementedException", ErrorCategory.ObjectNotFound, this._uri);
				base.WriteError(errorRecord2);
			}
			this.sourceHash = stringBuilder.ToString().GetHashCode();
			if (!NewWebServiceProxy.srccodeCache.ContainsKey(this.sourceHash))
			{
				CompilerParameters compilerParameter = new CompilerParameters();
				CompilerResults compilerResult = null;
				foreach (string str in stringCollections)
				{
					base.WriteWarning(str);
				}
				compilerParameter.ReferencedAssemblies.Add("System.dll");
				compilerParameter.ReferencedAssemblies.Add("System.Data.dll");
				compilerParameter.ReferencedAssemblies.Add("System.Xml.dll");
				compilerParameter.ReferencedAssemblies.Add("System.Web.Services.dll");
				compilerParameter.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
				this.GetReferencedAssemblies(typeof(Cmdlet).Assembly, compilerParameter);
				compilerParameter.GenerateInMemory = true;
				compilerParameter.TreatWarningsAsErrors = false;
				compilerParameter.WarningLevel = 4;
				compilerParameter.GenerateExecutable = false;
				try
				{
					string[] strArrays = new string[1];
					strArrays[0] = stringBuilder.ToString();
					compilerResult = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameter, strArrays);
				}
				catch (NotImplementedException notImplementedException3)
				{
					NotImplementedException notImplementedException2 = notImplementedException3;
					ErrorRecord errorRecord3 = new ErrorRecord(notImplementedException2, "NotImplementedException", ErrorCategory.ObjectNotFound, this._uri);
					base.WriteError(errorRecord3);
				}
				return compilerResult.CompiledAssembly;
			}
			else
			{
				NewWebServiceProxy.srccodeCache.TryGetValue(this.sourceHash, out obj);
				base.WriteObject(obj, true);
				return null;
			}
		}
		/// <summary>
		/// Gets the XML schemas for generating data contracts.
		/// </summary>
		/// <param name="options">The metadata resolving options.</param>
		/// <returns>A collection of the XML schemas.</returns>
		public static XmlSchemas GetXmlSchemas(MetadataResolverOptions options)
		{
			if (options.DataContractFiles == null)
				throw new ArgumentNullException("options");

			// Resolve the schemas.
			XmlSchemas schemas = new XmlSchemas();
			for (int fi = 0; fi < options.DataContractFiles.Length; fi++)
			{
				// Skip the non xsd/wsdl files.
				string lowext = Path.GetExtension(options.DataContractFiles[fi]).ToLower();
				if (lowext == ".xsd") // This is an XSD file.
				{
					XmlTextReader xmltextreader = null;

					try
					{
						xmltextreader = new XmlTextReader(options.DataContractFiles[fi]);
						XmlSchema schema = XmlSchema.Read(xmltextreader, null);
						XmlSchemaSet schemaset = new XmlSchemaSet();
						schemaset.Add(schema);
						RemoveDuplicates(ref schemaset);
						schemaset.Compile();
						schemas.Add(schema);
					}
					finally
					{
						if (xmltextreader != null)
						{
							xmltextreader.Close();
						}
					}
				}
				else if (lowext == ".wsdl") // This is a WSDL file.
				{
					XmlSchemaSet schemaset = new XmlSchemaSet();
					XmlSchemaSet embeddedschemaset = new XmlSchemaSet();
					DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
					dcp.AllowAutoRedirect = true;
					dcp.Credentials = CredentialCache.DefaultCredentials;
					dcp.DiscoverAny(options.DataContractFiles[fi]);
					dcp.ResolveAll();
					foreach (object document in dcp.Documents.Values)
					{
						if (document is XmlSchema)
						{
							schemaset.Add((XmlSchema)document);
							schemas.Add((XmlSchema)document);
						}
						if (document is WebServiceDescription)
						{
							schemas.Add(((WebServiceDescription)document).Types.Schemas);
							foreach (XmlSchema schema in ((WebServiceDescription)document).Types.Schemas)
							{
								embeddedschemaset.Add(schema);
								schemas.Add(schema);
							}
						}
					}
					RemoveDuplicates(ref schemaset);
					schemaset.Add(embeddedschemaset);
					schemaset.Compile();
				}
			}
			return schemas;
		}
        private static void ResolveImports(MetadataResolverOptions options, MetadataSet metadataSet)
        {
            // Resolve metadata using a DiscoveryClientProtocol.
            DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
            dcp.Credentials = GetCredentials(options);
            dcp.AllowAutoRedirect = true;
            dcp.DiscoverAny(options.MetadataLocation);
            dcp.ResolveAll();

            foreach (object osd in dcp.Documents.Values)
            {
                if (osd is System.Web.Services.Description.ServiceDescription)
                {
                    MetadataSection mds = MetadataSection.CreateFromServiceDescription((System.Web.Services.Description.ServiceDescription)osd);
                    metadataSet.MetadataSections.Add(mds);
                    continue;
                }
                if (osd is XmlSchema)
                {
                    //XmlSchema schema = osd as XmlSchema;
                    //if (schema != null)
                    //{
                    //    if ("urn:examples.com:techniques:iepd:commercialVehicleCollision:message:2.0" != schema.TargetNamespace)
                    //    {
                    //        schema.Compile(null);
                    //    }
                    //}

                    MetadataSection mds = MetadataSection.CreateFromSchema((XmlSchema)osd);
                    metadataSet.MetadataSections.Add(mds);
                    continue;
                }
            }
        }
        private static void ResolveImports(MetadataResolverOptions options, MetadataSet metadataSet)
        {
            // Resolve metadata using a DiscoveryClientProtocol.
            DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
            dcp.Credentials = GetCredentials(options);
            dcp.AllowAutoRedirect = true;
            dcp.DiscoverAny(options.MetadataLocation);
            dcp.ResolveAll();

            foreach (object osd in dcp.Documents.Values)
            {
                if (osd is System.Web.Services.Description.ServiceDescription)
                {
                    MetadataSection mds = MetadataSection.CreateFromServiceDescription((System.Web.Services.Description.ServiceDescription)osd);
                    metadataSet.MetadataSections.Add(mds);
                    continue;
                }
                if (osd is XmlSchema)
                {
                    MetadataSection mds = MetadataSection.CreateFromSchema((XmlSchema)osd);
                    metadataSet.MetadataSections.Add(mds);
                    continue;
                }
            }
        }
        /// <summary>
        /// Process remote urls
        /// </summary>
        /// <param name="url"></param>
        /// <param name="discoveryClientProtocol"></param>
        private void ProcessUrl(string url, DiscoveryClientProtocol discoveryClientProtocol)
        {
            try
            {
                DiscoveryDocument discoveryDocument = discoveryClientProtocol.DiscoverAny(url);
                discoveryClientProtocol.ResolveAll();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("General Error " + url, ex);
            }

            foreach (DictionaryEntry entry in discoveryClientProtocol.Documents)
                this.AddDocument((string)entry.Key, entry.Value);
        }
 private void DoMex()
 {
     string str;
     string str2;
     string str3;
     string str4;
     string str5;
     string str6;
     string str7;
     string str8;
     string str9 = null;
     string str10 = null;
     string str11 = null;
     string str12 = null;
     string str13 = null;
     string str14 = null;
     string str15 = null;
     EndpointIdentity identity = null;
     EndpointIdentity identity2 = null;
     WsdlImporter importer;
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Contract, out str4);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.ContractNamespace, out str5);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.BindingNamespace, out str7);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Binding, out str6);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexAddress, out str);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexBinding, out str2);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexBindingConfiguration, out str3);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Address, out str8);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.SpnIdentity, out str9);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.UpnIdentity, out str10);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.DnsIdentity, out str11);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexSpnIdentity, out str12);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexUpnIdentity, out str13);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexDnsIdentity, out str14);
     this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Serializer, out str15);
     if (string.IsNullOrEmpty(str))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerMexAddressNotSpecified")));
     }
     if (!string.IsNullOrEmpty(str12))
     {
         if (!string.IsNullOrEmpty(str13) || !string.IsNullOrEmpty(str14))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentityForMex")));
         }
         identity2 = EndpointIdentity.CreateSpnIdentity(str12);
     }
     else if (!string.IsNullOrEmpty(str13))
     {
         if (!string.IsNullOrEmpty(str12) || !string.IsNullOrEmpty(str14))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentityForMex")));
         }
         identity2 = EndpointIdentity.CreateUpnIdentity(str13);
     }
     else if (!string.IsNullOrEmpty(str14))
     {
         if (!string.IsNullOrEmpty(str12) || !string.IsNullOrEmpty(str13))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentityForMex")));
         }
         identity2 = EndpointIdentity.CreateDnsIdentity(str14);
     }
     else
     {
         identity2 = null;
     }
     if (string.IsNullOrEmpty(str8))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerAddressNotSpecified")));
     }
     if (string.IsNullOrEmpty(str4))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerContractNotSpecified")));
     }
     if (string.IsNullOrEmpty(str6))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerBindingNotSpecified")));
     }
     if (string.IsNullOrEmpty(str7))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerBindingNamespacetNotSpecified")));
     }
     if (!string.IsNullOrEmpty(str9))
     {
         if (!string.IsNullOrEmpty(str10) || !string.IsNullOrEmpty(str11))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentity")));
         }
         identity = EndpointIdentity.CreateSpnIdentity(str9);
     }
     else if (!string.IsNullOrEmpty(str10))
     {
         if (!string.IsNullOrEmpty(str9) || !string.IsNullOrEmpty(str11))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentity")));
         }
         identity = EndpointIdentity.CreateUpnIdentity(str10);
     }
     else if (!string.IsNullOrEmpty(str11))
     {
         if (!string.IsNullOrEmpty(str9) || !string.IsNullOrEmpty(str10))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentity")));
         }
         identity = EndpointIdentity.CreateDnsIdentity(str11);
     }
     else
     {
         identity = null;
     }
     MetadataExchangeClient client = null;
     EndpointAddress address = new EndpointAddress(new Uri(str), identity2, new AddressHeader[0]);
     if (!string.IsNullOrEmpty(str2))
     {
         System.ServiceModel.Channels.Binding mexBinding = null;
         try
         {
             mexBinding = ConfigLoader.LookupBinding(str2, str3);
         }
         catch (ConfigurationErrorsException)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MexBindingNotFoundInConfig", new object[] { str2 })));
         }
         if (mexBinding == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MexBindingNotFoundInConfig", new object[] { str2 })));
         }
         client = new MetadataExchangeClient(mexBinding);
     }
     else
     {
         if (!string.IsNullOrEmpty(str3))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerMexBindingSectionNameNotSpecified")));
         }
         client = new MetadataExchangeClient(address);
     }
     if (identity2 != null)
     {
         client.SoapCredentials.Windows.AllowNtlm = false;
     }
     bool flag = false;
     if (!string.IsNullOrEmpty(str15))
     {
         if (("xml" != str15) && ("datacontract" != str15))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorectSerializer")));
         }
         if ("xml" == str15)
         {
             this.useXmlSerializer = true;
         }
         else
         {
             flag = true;
         }
     }
     ServiceEndpoint endpoint = null;
     ServiceEndpointCollection serviceEndpointsRetrieved = null;
     try
     {
         MetadataSet metadata = client.GetMetadata(address);
         if (this.useXmlSerializer)
         {
             importer = this.CreateXmlSerializerImporter(metadata);
         }
         else if (flag)
         {
             importer = this.CreateDataContractSerializerImporter(metadata);
         }
         else
         {
             importer = new WsdlImporter(metadata);
         }
         serviceEndpointsRetrieved = this.ImportWsdlPortType(new XmlQualifiedName(str4, str5), importer);
         ComPlusMexChannelBuilderMexCompleteTrace.Trace(TraceEventType.Verbose, 0x50024, "TraceCodeComIntegrationMexMonikerMetadataExchangeComplete", serviceEndpointsRetrieved);
     }
     catch (Exception exception)
     {
         if (Fx.IsFatal(exception))
         {
             throw;
         }
         if (UriSchemeSupportsDisco(address.Uri))
         {
             try
             {
                 DiscoveryClientProtocol protocol = new DiscoveryClientProtocol {
                     UseDefaultCredentials = true,
                     AllowAutoRedirect = true
                 };
                 protocol.DiscoverAny(address.Uri.AbsoluteUri);
                 protocol.ResolveAll();
                 MetadataSet metadataSet = new MetadataSet();
                 foreach (object obj2 in protocol.Documents.Values)
                 {
                     this.AddDocumentToSet(metadataSet, obj2);
                 }
                 if (this.useXmlSerializer)
                 {
                     importer = this.CreateXmlSerializerImporter(metadataSet);
                 }
                 else if (flag)
                 {
                     importer = this.CreateDataContractSerializerImporter(metadataSet);
                 }
                 else
                 {
                     importer = new WsdlImporter(metadataSet);
                 }
                 serviceEndpointsRetrieved = this.ImportWsdlPortType(new XmlQualifiedName(str4, str5), importer);
                 ComPlusMexChannelBuilderMexCompleteTrace.Trace(TraceEventType.Verbose, 0x50024, "TraceCodeComIntegrationMexMonikerMetadataExchangeComplete", serviceEndpointsRetrieved);
                 goto Label_0634;
             }
             catch (Exception exception2)
             {
                 if (Fx.IsFatal(exception2))
                 {
                     throw;
                 }
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerFailedToDoMexRetrieve", new object[] { exception2.Message })));
             }
         }
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerFailedToDoMexRetrieve", new object[] { exception.Message })));
     }
 Label_0634:
     if (serviceEndpointsRetrieved.Count == 0)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerContractNotFoundInRetreivedMex")));
     }
     foreach (ServiceEndpoint endpoint2 in serviceEndpointsRetrieved)
     {
         System.ServiceModel.Channels.Binding binding = endpoint2.Binding;
         if ((binding.Name == str6) && (binding.Namespace == str7))
         {
             endpoint = endpoint2;
             break;
         }
     }
     if (endpoint == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerNoneOfTheBindingMatchedTheSpecifiedBinding")));
     }
     this.contractDescription = endpoint.Contract;
     this.serviceEndpoint = new ServiceEndpoint(this.contractDescription, endpoint.Binding, new EndpointAddress(new Uri(str8), identity, null));
     ComPlusMexChannelBuilderTrace.Trace(TraceEventType.Verbose, 0x50025, "TraceCodeComIntegrationMexChannelBuilderLoaded", endpoint.Contract, endpoint.Binding, str8);
 }
Exemple #23
0
        //TODO: FB client.GetMetadata is not working working on linux, instead use DiscoveryClientProtocol.
        //this means that mex bindings are currently not supported on linux
        void DownloadWeb(model.IProxy proxy, out List<wsdlDescription.ServiceDescription> descriptions, out List<XmlSchema> schemas)
        {
            DiscoveryClientProtocol client = new DiscoveryClientProtocol();

            if (proxy.ProxyType == model.Proxy.EProxyType.Enabled) {

                client.Proxy = new System.Net.WebProxy(proxy.Host, proxy.Port);
                client.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
            }

            descriptions = new List<wsdlDescription.ServiceDescription>();
            schemas = new List<XmlSchema>();

            //download document
            client.AllowAutoRedirect = true;
            client.Timeout = _timeoutInSeconds * 1000;

            client.Documents.Clear();
            client.DiscoverAny(_wsdlEndpoint);
            client.ResolveAll();

            //generate stub
            foreach (var v in client.Documents.Values) {
                if (v is wsdlDescription.ServiceDescription) {
                    descriptions.Add((wsdlDescription.ServiceDescription)v);
                }
                else if (v is XmlSchema) {
                    schemas.Add((XmlSchema)v);
                }
            }
        }
		protected override byte[] GenerateCode(string fileName, string FileContents)
		{
			InitializeTool();
			try
			{
				if (mOutLog != null) 
				{
					mOutLog.Clear();
				}
				string DefaultNameSpace = this.GetDefaultNameSpace(fileName);

				// Load FileContents into XML Doc
				XmlDocument inXDoc = new XmlDocument();

				inXDoc.PreserveWhitespace = false;
				inXDoc.LoadXml(FileContents);
                       
				// Get the path to the WSDL
				XmlNode wsdln = inXDoc.DocumentElement.SelectSingleNode("//WSDLFile/text()");
				if (wsdln == null || wsdln.Value == String.Empty)
				{
					//Console.WriteLine("WSDL not found in Document <configuration><WSDLFile>http://value.wsdl</WSDLFile></configuration>\n");
					if (mOutLog != null) 
					{
						mOutLog.OutputString("WSDL not found in Document <configuration><WSDLFile>http://value.wsdl</WSDLFile></configuration>\n");
					}
					else 
					{
						Console.WriteLine("WSDL not found in Document <configuration><WSDLFile>http://value.wsdl</WSDLFile></configuration>\n");
					}
					return null;
				}

				string WSDLPath = wsdln.Value;
				if (mOutLog != null) 
				{
					mOutLog.OutputString("Generating Proxy Class File\n");
					mOutLog.OutputString("NameSpace: " + DefaultNameSpace + "\n");
					mOutLog.OutputString("WSDL Path: " + WSDLPath + "\n");
				}
				else 
				{
					Console.WriteLine("Generating Proxy Class File\n");
					Console.WriteLine("NameSpace: " + DefaultNameSpace + "\n");
					Console.WriteLine("WSDL Path: " + WSDLPath + "\n");
				}

				// Load WSDL
                XmlTextReader xtr = new XmlTextReader(WSDLPath);
                ServiceDescription serviceDescription = ServiceDescription.Read(xtr);
				CodeCompileUnit codeUnit = new CodeCompileUnit();

				CodeNamespace codeNamespace = new CodeNamespace(DefaultNameSpace);
				codeUnit.Namespaces.Add(codeNamespace);

				codeNamespace.Comments.Add(new CodeCommentStatement("Generator version 1.1"));
				codeNamespace.Comments.Add(new CodeCommentStatement(""));
				codeNamespace.Comments.Add(new CodeCommentStatement("Copyright: ?2000-2008 eBay Inc."));
				codeNamespace.Comments.Add(new CodeCommentStatement(""));
				codeNamespace.Comments.Add(new CodeCommentStatement("Date: " + DateTime.Now.ToString()));
				codeNamespace.Comments.Add(new CodeCommentStatement(""));

				//
				// Set up the service importer that eventually generate the DOM
				// for client proxy.
				//
				ServiceDescriptionImporter serviceImporter = new ServiceDescriptionImporter();
			
				// Resolve any Imports
				
                DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
				dcp.DiscoverAny(WSDLPath);
				dcp.ResolveAll();

				foreach (object osd in dcp.Documents.Values)
				{
					if (osd is ServiceDescription) serviceImporter.AddServiceDescription((ServiceDescription)osd, String.Empty, String.Empty);;
					if (osd is XmlSchema) serviceImporter.Schemas.Add((XmlSchema)osd);
				}

				// Configure the Importer
				serviceImporter.ProtocolName = "Soap";
				serviceImporter.Style = ServiceDescriptionImportStyle.Client;

                //serviceImporter.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.EnableDataBinding
                //                                      | serviceImporter.CodeGenerationOptions;
            
				ServiceDescriptionImportWarnings warnings = serviceImporter.Import(codeNamespace, codeUnit);

				if (mOutLog != null) 
				{
					if ((warnings & ServiceDescriptionImportWarnings.NoMethodsGenerated) != 0)
						mOutLog.OutputString("Warning: no methods were generated.\n");
					if ((warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) != 0)
						mOutLog.OutputString("Warning: one or more optional WSDL extension elements were ignored.\n");
					if ((warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) != 0)
						mOutLog.OutputString("Warning: one or more optional WSDL extension elements were ignored.\n");
					if ((warnings & ServiceDescriptionImportWarnings.RequiredExtensionsIgnored) != 0)
						mOutLog.OutputString("Warning: one or more required WSDL extension elements were ignored.\n");
					if ((warnings & ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored) != 0)
						mOutLog.OutputString("Warning: one or more bindings were skipped.\n");
					if ((warnings & ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored) != 0)
						mOutLog.OutputString("one or more operations were skipped.\n");
					if ((warnings & ServiceDescriptionImportWarnings.NoCodeGenerated) != 0)
					{
						mOutLog.OutputString("Warning: no classes were generated.\n");
						return null;
					}
					if (warnings != 0)
						mOutLog.OutputString("Warnings were encountered. Review generated source comments for more details.\n");
				}
				else 
				{
					if ((warnings & ServiceDescriptionImportWarnings.NoMethodsGenerated) != 0)
						Console.WriteLine("Warning: no methods were generated.\n");
					if ((warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) != 0)
						Console.WriteLine("Warning: one or more optional WSDL extension elements were ignored.\n");
					if ((warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) != 0)
						Console.WriteLine("Warning: one or more optional WSDL extension elements were ignored.\n");
					if ((warnings & ServiceDescriptionImportWarnings.RequiredExtensionsIgnored) != 0)
						Console.WriteLine("Warning: one or more required WSDL extension elements were ignored.\n");
					if ((warnings & ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored) != 0)
						Console.WriteLine("Warning: one or more bindings were skipped.\n");
					if ((warnings & ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored) != 0)
						Console.WriteLine("one or more operations were skipped.\n");
					if ((warnings & ServiceDescriptionImportWarnings.NoCodeGenerated) != 0)
					{
						Console.WriteLine("Warning: no classes were generated.\n");
						return null;
					}
					if (warnings != 0)
						Console.WriteLine("Warnings were encountered. Review generated source comments for more details.\n");
				}

                // change the base class
                CodeTypeDeclaration ctDecl = codeNamespace.Types[0];
                codeNamespace.Types.Remove(ctDecl);
                ctDecl.BaseTypes[0] = new CodeTypeReference(DefaultNameSpace + ".SoapHttpClientProtocolEx");
                codeNamespace.Types.Add(ctDecl);

                codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
                CodeTypeDeclarationCollection codeTypeColl = new CodeTypeDeclarationCollection();
                ArrayList colList = new ArrayList();
                ArrayList allMembers = new ArrayList();

                //added by william, workaround to fix the code
                FixCode(codeNamespace);

                foreach (CodeTypeDeclaration codeType in codeNamespace.Types)
                {

                    allMembers.Clear();
                    foreach (CodeTypeMember codeMember in codeType.Members)
                    {
                        allMembers.Add(codeMember.Name);
                    }

                    CodeTypeMemberCollection codeMemberColl = new CodeTypeMemberCollection();

                    //
                    // Collect the public fields of the type.
                    //

                    foreach (CodeTypeMember codeMember in codeType.Members)
                    {
                        CodeMemberMethod codeMethod = codeMember as CodeMemberMethod;

                        if (codeMethod != null)
                        {
                            if ((codeMethod.Attributes & MemberAttributes.Public) == MemberAttributes.Public)
                            {
                                foreach (CodeAttributeDeclaration cadt in codeMethod.CustomAttributes)
                                {
                                    if (cadt.Name.EndsWith("SoapDocumentMethodAttribute"))
                                    {
                                        codeMethod.CustomAttributes.Add(new CodeAttributeDeclaration(DefaultNameSpace + ".SoapExtensionExAttribute"));
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            CodeMemberField codeField = codeMember as CodeMemberField;
                            if (codeField != null)
                            {   
                                if ((codeField.Attributes & MemberAttributes.Public) == MemberAttributes.Public)
                                {
                                    codeField.Comments.Clear();

                                    CodeTypeReference codeFieldRef = codeField.Type.ArrayElementType as CodeTypeReference;

                                    //skip 'System.Byte'
                                    if (codeFieldRef != null && !"System.Byte".Equals(codeFieldRef.BaseType))
                                    {
                                        string name = codeFieldRef.BaseType;
                                        //Debug.WriteLine("Array BaseType name : " + name);

                                        string[] splstr = name.Split('.');

                                        if (splstr.Length > 1)
                                        {
                                            string ns = String.Join(".", splstr, 0, splstr.Length - 1);
                                            codeNamespace.Imports.Add(new CodeNamespaceImport(ns));
                                            name = (string)splstr.GetValue(splstr.Length - 1);
                                        }

                                        if (!colList.Contains(name))
                                        {
                                            codeTypeColl.Add(this.CreateCollectionType(name));
                                            colList.Add(name);
                                        }
                                        codeField.Type = new CodeTypeReference(name + "Collection");

                                    }

                                    int val = allMembers.IndexOf(codeField.Name + "Specified");
                                    codeMemberColl.Add(this.CreateProperty(codeField, val != -1));
                                }
                            }
                        }
                    }

                    // add the newly created public properties
                    codeType.Members.AddRange(codeMemberColl);
                }

                codeNamespace.Types.AddRange(codeTypeColl);
                codeNamespace.Types.Add(CreateSoapHttpClientProtocolEx());
                codeNamespace.Types.Add(CreateSoapExtensionExAttribute());
                codeNamespace.Types.Add(CreateSoapExtensionEx());

				if (this.mProjItem != null) 
				{
					MemoryStream mem = new MemoryStream();
					StreamWriter outputWriter = new StreamWriter(mem);
					CodeProvider.GenerateCodeFromCompileUnit(codeUnit, outputWriter, new CodeGeneratorOptions());
                    outputWriter.Flush();
					mOutLog.OutputString("Code Generation Completed Successfully\n");
					return mem.ToArray();
				}
				else 
				{
                    CodeDomProvider generator = null;
					string fileExt = null;
					if (mLang.Equals(VB))
					{
						generator = new Microsoft.VisualBasic.VBCodeProvider();
						fileExt = VB;
					}
						//j# is not available.
						//else if (mLang.Equals(JS))
						//{	
						//	generator = new Microsoft.JScript.JScriptCodeProvider().CreateGenerator();
						//}
					else 
					{
						generator = new Microsoft.CSharp.CSharpCodeProvider();
						fileExt = CS;
					}

					if (mOutputOneFileOption == true) 
					{
						MemoryStream mem = new MemoryStream();
						StreamWriter outputWriter = new StreamWriter(mem);
						CodeGeneratorOptions options = new CodeGeneratorOptions();
						options.BlankLinesBetweenMembers = false;
						generator.GenerateCodeFromCompileUnit(codeUnit, outputWriter, options);;
						outputWriter.Flush();

						byte [] output = mem.ToArray();
						BinaryWriter writer = new BinaryWriter(File.Open(mOutputPath + fileName, FileMode.Create));
						writer.Write(output);	
						writer.Close();
					}
					else
					{
						CodeTypeDeclarationCollection coll = new CodeTypeDeclarationCollection();
						coll.AddRange(codeNamespace.Types);

						foreach (CodeTypeDeclaration codeType in coll) 
						{
							codeNamespace.Types.Clear();				
							CodeTypeDeclarationCollection types = new CodeTypeDeclarationCollection();
							codeNamespace.Types.Add(codeType);
							MemoryStream mem = new MemoryStream();
							StreamWriter outputWriter = new StreamWriter(mem);

							CodeGeneratorOptions options = new CodeGeneratorOptions();
							options.BlankLinesBetweenMembers = false;
							generator.GenerateCodeFromCompileUnit(codeUnit, outputWriter, options);;
							outputWriter.Flush();

							byte [] output = mem.ToArray();
							string clsName = codeType.Name + "." + fileExt;
							BinaryWriter writer = new BinaryWriter(File.Open(mOutputPath + clsName, FileMode.Create));
							writer.Write(output);	
							writer.Close();
						}
					}
					Console.WriteLine("Code Generation Completed Successfully\n");
					return null;
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message + "\n");
				return null;
			}
		}
        private void DownloadMetadata()
        {
            EndpointAddress epr = new EndpointAddress(this.wsdlUri);

            DiscoveryClientProtocol disco = new DiscoveryClientProtocol();
            disco.AllowAutoRedirect = true;
            disco.UseDefaultCredentials = true;
            disco.DiscoverAny(this.wsdlUri);
            disco.ResolveAll();

            Collection<MetadataSection> results = new Collection<MetadataSection>();
            foreach (object document in disco.Documents.Values)
            {
                AddDocumentToResults(document, results);
            }
            this.metadataCollection = results;
        }
Exemple #26
0
 private void ProcessRemoteUrls(DiscoveryClientProtocol client, StringCollection urls, XmlSchemas schemas, ServiceDescriptionCollection descriptions)
 {
     StringEnumerator enumerator = urls.GetEnumerator();
     while (enumerator.MoveNext())
     {
         string current = enumerator.Current;
         try
         {
             DiscoveryDocument document = client.DiscoverAny(current);
             client.ResolveAll();
             continue;
         }
         catch (Exception exception)
         {
             throw new InvalidOperationException("General Error " + current, exception);
         }
     }
     IDictionaryEnumerator enumerator2 = client.Documents.GetEnumerator();
     while (enumerator2.MoveNext())
     {
         DictionaryEntry entry = (DictionaryEntry)enumerator2.Current;
         this.AddDocument((string)entry.Key, entry.Value, schemas, descriptions);
     }
 }
Exemple #27
0
		MetadataSet ResolveWithDisco (string url)
		{
			DiscoveryClientProtocol prot = null;
			Console.WriteLine ("\nAttempting to download metadata from '{0}' using DISCO..", url);
			try { 
				prot = new DiscoveryClientProtocol ();
				prot.DiscoverAny (url);
				prot.ResolveAll ();
			} catch (Exception e) {
				Console.WriteLine ("Disco failed for the url '{0}' with exception :\n {1}", url, e.Message);
				return null;
			}

			if (prot.References.Count > 0)
			{
				Console.WriteLine ("Disco found documents at the following URLs:");
				foreach (DiscoveryReference refe in prot.References.Values)
				{
					if (refe is ContractReference) Console.Write ("- WSDL document at  ");
					else if (refe is DiscoveryDocumentReference) Console.Write ("- DISCO document at ");
					else Console.Write ("- Xml Schema at    ");
					Console.WriteLine (refe.Url);
				}
			} else {
				Console.WriteLine ("Disco didn't find any document at the specified URL");
				return null;
			}

			MetadataSet metadata = new MetadataSet ();
			foreach (object o in prot.Documents.Values) {
				if (o is WSServiceDescrition) {
					metadata.MetadataSections.Add (
						new MetadataSection (MetadataSection.ServiceDescriptionDialect, "", (WSServiceDescrition) o));
				}
				if (o is XmlSchema) {
					metadata.MetadataSections.Add (
						new MetadataSection (MetadataSection.XmlSchemaDialect, "", (XmlSchema) o));
				}
			}

			return metadata;
		}
        /// <summary>
        /// Checks the for imports.
        /// </summary>
        /// <param name="baseWSDLUrl">Base WSDL URL.</param>
        private void CheckForImports(string baseWSDLUrl)
        {
            DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
            //DEBUG code
            try
            {
                dcp.DiscoverAny(baseWSDLUrl);
                dcp.ResolveAll();
            }
            catch(UriFormatException ex)
            {
                throw new ApplicationException("Not a valid wsdl location: " + baseWSDLUrl, ex);
            }

            foreach (object osd in dcp.Documents.Values)
            {
                if (osd is ServiceDescription) sdi.AddServiceDescription((ServiceDescription)osd, null, null);
                if (osd is XmlSchema)
                {
                    // store in global schemas variable
                    if (schemas == null) schemas = new XmlSchemas();
                    schemas.Add((XmlSchema)osd);

                    sdi.Schemas.Add((XmlSchema)osd);
                }
            }
        }
 /// <summary>                       
 /// 根据web   service文档架构向代理类添加ServiceDescription和XmlSchema                             
 /// </summary>                                  
 /// <param   name="baseWSDLUrl">web服务地址</param>                           
 /// <param   name="importer">代理类</param>                              
 private void checkForImports(string baseWsdlUrl, ServiceDescriptionImporter importer)
 {
     DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
     dcp.DiscoverAny(baseWsdlUrl);
     dcp.ResolveAll();
     foreach (object osd in dcp.Documents.Values)
     {
         if (osd is ServiceDescription) importer.AddServiceDescription((ServiceDescription)osd, null, null); ;
         if (osd is XmlSchema) importer.Schemas.Add((XmlSchema)osd);
     }
 }
Exemple #30
0
        private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName)
        {
            DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();

            //if paramset is defaultcredential, set the flag in wcclient
            if (_usedefaultcredential.IsPresent)
                dcp.UseDefaultCredentials = true;

            //if paramset is credential, assign the credentials
            if (ParameterSetName.Equals("Credential", StringComparison.OrdinalIgnoreCase))
                dcp.Credentials = _credential.GetNetworkCredential();

            try
            {
                dcp.AllowAutoRedirect = true;
                dcp.DiscoverAny(_uri.ToString());
                dcp.ResolveAll();
            }
            catch (WebException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "WebException", ErrorCategory.ObjectNotFound, _uri);
                if (ex.InnerException != null)
                    er.ErrorDetails = new ErrorDetails(ex.InnerException.Message);
                WriteError(er);
                return null;
            }
            catch (InvalidOperationException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _uri);
                WriteError(er);
                return null;
            }

            // create the namespace
            CodeNamespace codeNS = new CodeNamespace();
            if (!string.IsNullOrEmpty(NameSpace))
                codeNS.Name = NameSpace;

            //create the class and add it to the namespace
            if (!string.IsNullOrEmpty(ClassName))
            {
                CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName);
                codeClass.IsClass = true;
                codeClass.Attributes = MemberAttributes.Public;
                codeNS.Types.Add(codeClass);
            }

            //create a web reference to the uri docs
            WebReference wref = new WebReference(dcp.Documents, codeNS);
            WebReferenceCollection wrefs = new WebReferenceCollection();
            wrefs.Add(wref);

            //create a codecompileunit and add the namespace to it
            CodeCompileUnit codecompileunit = new CodeCompileUnit();
            codecompileunit.Namespaces.Add(codeNS);

            WebReferenceOptions wrefOptions = new WebReferenceOptions();
            wrefOptions.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateOldAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
            wrefOptions.Verbose = true;

            //create a csharpprovider and compile it
            CSharpCodeProvider csharpprovider = new CSharpCodeProvider();
            StringCollection Warnings = ServiceDescriptionImporter.GenerateWebReferences(wrefs, csharpprovider, codecompileunit, wrefOptions);

            StringBuilder codegenerator = new StringBuilder();
            StringWriter writer = new StringWriter(codegenerator, CultureInfo.InvariantCulture);
            try
            {
                csharpprovider.GenerateCodeFromCompileUnit(codecompileunit, writer, null);
            }
            catch (NotImplementedException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri);
                WriteError(er);
            }
            //generate the hashcode of the CodeCompileUnit            
            _sourceHash = codegenerator.ToString().GetHashCode();

            //if the sourcehash matches the hashcode in the cache,the proxy hasnt changed and so
            // return the instance of th eproxy in the cache
            if (s_srccodeCache.ContainsKey(_sourceHash))
            {
                object obj;
                s_srccodeCache.TryGetValue(_sourceHash, out obj);
                WriteObject(obj, true);
                return null;
            }
            CompilerParameters options = new CompilerParameters();
            CompilerResults results = null;

            foreach (string warning in Warnings)
            {
                this.WriteWarning(warning);
            }

            // add the references to the required assemblies
            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add("System.Data.dll");
            options.ReferencedAssemblies.Add("System.Xml.dll");
            options.ReferencedAssemblies.Add("System.Web.Services.dll");
            options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            GetReferencedAssemblies(typeof(Cmdlet).Assembly, options);
            options.GenerateInMemory = true;
            options.TreatWarningsAsErrors = false;
            options.WarningLevel = 4;
            options.GenerateExecutable = false;
            try
            {
                results = csharpprovider.CompileAssemblyFromSource(options, codegenerator.ToString());
            }
            catch (NotImplementedException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri);
                WriteError(er);
            }

            return results.CompiledAssembly;
        }