public override void ImportClass()
        {
            // grab this here so it gets marked "handled" for both client and server
            SoapAddressBinding soapAddress = ImportContext.Port == null ? null : (SoapAddressBinding)ImportContext.Port.Extensions.Find(typeof(SoapAddressBinding));

            if (ImportContext.Style == ServiceDescriptionImportStyle.Client)
            {
                ImportContext.CodeTypeDeclaration.BaseTypes.Add(typeof(SoapHttpClientProtocol).FullName);
                CodeConstructor ctor = WebCodeGenerator.AddConstructor(ImportContext.CodeTypeDeclaration, new string[0], new string[0], null, CodeFlags.IsPublic);
                ctor.Comments.Add(new CodeCommentStatement("<remarks/>", true));
                if (ImportContext is Soap12ProtocolImporter)
                {
                    // add version code
                    CodeTypeReferenceExpression     versionEnumTypeReference  = new CodeTypeReferenceExpression(typeof(SoapProtocolVersion));
                    CodeFieldReferenceExpression    versionEnumFieldReference = new CodeFieldReferenceExpression(versionEnumTypeReference, Enum.Format(typeof(SoapProtocolVersion), SoapProtocolVersion.Soap12, "G"));
                    CodePropertyReferenceExpression versionPropertyReference  = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "SoapVersion");
                    CodeAssignStatement             assignVersionStatement    = new CodeAssignStatement(versionPropertyReference, versionEnumFieldReference);
                    ctor.Statements.Add(assignVersionStatement);
                }
                ServiceDescription serviceDescription = ImportContext.Binding.ServiceDescription;
                string             url     = (soapAddress != null) ? soapAddress.Location : null;
                string             urlKey  = serviceDescription.AppSettingUrlKey;
                string             baseUrl = serviceDescription.AppSettingBaseUrl;
                ProtocolImporterUtil.GenerateConstructorStatements(ctor, url, urlKey, baseUrl);
            }
            else
            {
                ImportContext.CodeTypeDeclaration.BaseTypes.Add(typeof(WebService).FullName);
            }
        }
Пример #2
0
        protected virtual SoapAddressBinding CreateSoapAddressBinding(string serviceUrl)
        {
            SoapAddressBinding soapAddress = new SoapAddressBinding();

            soapAddress.Location = serviceUrl;
            return(soapAddress);
        }
Пример #3
0
        bool ImportBasicHttpEndpoint(WsdlEndpointConversionContext context)
        {
            var http = context.Endpoint.Binding as BasicHttpBinding;

            if (http == null)
            {
                return(false);
            }

            WS.SoapAddressBinding address = null;
            foreach (var extension in context.WsdlPort.Extensions)
            {
                var check = extension as WS.SoapAddressBinding;
                if (check != null)
                {
                    address = check;
                    break;
                }
            }

            if (address == null)
            {
                return(false);
            }

            context.Endpoint.Address       = new EndpointAddress(address.Location);
            context.Endpoint.ListenUri     = new Uri(address.Location);
            context.Endpoint.ListenUriMode = ListenUriMode.Explicit;
            return(true);
        }
            internal static bool ConvertSoapAddressBinding(ref object src, EnvelopeVersion version)
            {
                WsdlNS.SoapAddressBinding binding = src as WsdlNS.SoapAddressBinding;

                if (src != null)
                {
                    if (binding == null)
                    {
                        return(false); // no match
                    }
                    else if (GetBindingVersion <WsdlNS.Soap12AddressBinding>(src) == version)
                    {
                        return(true); // matched but same version; no change
                    }
                }

                if (version == EnvelopeVersion.None)
                {
                    src = null;
                    return(true);
                }

                WsdlNS.SoapAddressBinding dest = version == EnvelopeVersion.Soap12 ? new WsdlNS.Soap12AddressBinding() : new WsdlNS.SoapAddressBinding();
                if (binding != null)
                {
                    dest.Required = binding.Required;
                    dest.Location = binding.Location;
                }

                src = dest;
                return(true);
            }
Пример #5
0
        public override void ImportClass()
        {
            SoapAddressBinding binding = (base.ImportContext.Port == null) ? null : ((SoapAddressBinding)base.ImportContext.Port.Extensions.Find(typeof(SoapAddressBinding)));

            if (base.ImportContext.Style == ServiceDescriptionImportStyle.Client)
            {
                base.ImportContext.CodeTypeDeclaration.BaseTypes.Add(typeof(SoapHttpClientProtocol).FullName);
                CodeConstructor ctor = WebCodeGenerator.AddConstructor(base.ImportContext.CodeTypeDeclaration, new string[0], new string[0], null, CodeFlags.IsPublic);
                ctor.Comments.Add(new CodeCommentStatement(Res.GetString("CodeRemarks"), true));
                bool flag = true;
                if (base.ImportContext is Soap12ProtocolImporter)
                {
                    flag = false;
                    CodeTypeReferenceExpression     targetObject = new CodeTypeReferenceExpression(typeof(SoapProtocolVersion));
                    CodeFieldReferenceExpression    right        = new CodeFieldReferenceExpression(targetObject, Enum.Format(typeof(SoapProtocolVersion), SoapProtocolVersion.Soap12, "G"));
                    CodePropertyReferenceExpression left         = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "SoapVersion");
                    CodeAssignStatement             statement    = new CodeAssignStatement(left, right);
                    ctor.Statements.Add(statement);
                }
                ServiceDescription serviceDescription = base.ImportContext.Binding.ServiceDescription;
                string             url = (binding != null) ? binding.Location : null;
                string             appSettingUrlKey  = serviceDescription.AppSettingUrlKey;
                string             appSettingBaseUrl = serviceDescription.AppSettingBaseUrl;
                ProtocolImporterUtil.GenerateConstructorStatements(ctor, url, appSettingUrlKey, appSettingBaseUrl, flag && !base.ImportContext.IsEncodedBinding);
            }
            else if (base.ImportContext.Style == ServiceDescriptionImportStyle.Server)
            {
                base.ImportContext.CodeTypeDeclaration.BaseTypes.Add(typeof(WebService).FullName);
            }
        }
		protected override void BeginClass ()
		{
			SoapBinding sb = new SoapBinding ();
			sb.Transport = SoapBinding.HttpTransport;
			sb.Style = ((SoapTypeStubInfo)TypeInfo).SoapBindingStyle;
			Binding.Extensions.Add (sb);

			SoapAddressBinding abind = new SoapAddressBinding ();
			abind.Location = ServiceUrl;
			Port.Extensions.Add (abind);
		}
        override void ReflectDescription()
        {
            SoapBinding sb = CreateSoapBinding();

            sb.Transport = SoapBinding.HttpTransport;
            sb.Style     = ((SoapTypeStubInfo)ReflectionContext.TypeInfo).SoapBindingStyle;
            ReflectionContext.Binding.Extensions.Add(sb);

            SoapAddressBinding abind = CreateSoapAddressBinding();

            abind.Location = ReflectionContext.ServiceUrl;
            ReflectionContext.Port.Extensions.Add(abind);
        }
Пример #8
0
        protected virtual SoapAddressBinding CreateSoapAddressBinding(string serviceUrl)
        {
            SoapAddressBinding soapAddress = new SoapAddressBinding();

            soapAddress.Location = serviceUrl;
            if (this.UriFixups != null)
            {
                this.UriFixups.Add(delegate(Uri current)
                {
                    soapAddress.Location = DiscoveryServerType.CombineUris(current, soapAddress.Location);
                });
            }
            return(soapAddress);
        }
        void IWsdlExportExtension.ExportEndpoint(WsdlExporter exporter,
                                                 WsdlEndpointConversionContext context)
        {
            var soap_binding = new WS.SoapBinding();

            soap_binding.Transport = WS.SoapBinding.HttpTransport;
            soap_binding.Style     = WS.SoapBindingStyle.Document;
            context.WsdlBinding.Extensions.Add(soap_binding);

            var soap_address = new WS.SoapAddressBinding();

            soap_address.Location = context.Endpoint.Address.Uri.AbsoluteUri;

            context.WsdlPort.Extensions.Add(soap_address);
        }
        static WsdlNS.SoapAddressBinding CreateSoapAddressBinding(EnvelopeVersion version, WsdlNS.Port wsdlPort)
        {
            WsdlNS.SoapAddressBinding soapAddressBinding = null;

            if (version == EnvelopeVersion.Soap12)
            {
                soapAddressBinding = new WsdlNS.Soap12AddressBinding();
            }
            else if (version == EnvelopeVersion.Soap11)
            {
                soapAddressBinding = new WsdlNS.SoapAddressBinding();
            }
            Fx.Assert(soapAddressBinding != null, "EnvelopeVersion is not recognized. Please update the SoapHelper class");

            wsdlPort.Extensions.Add(soapAddressBinding);
            return(soapAddressBinding);
        }
        // -----------------------------------------------------------------------------------------------------------------------
        // Developers Note: We go through a little song an dance here to Get or Create an exsisting SoapBinding from the WSDL
        // Extensions for a number of reasons:
        //      1. Multiple Extensions may contribute to the settings in the soap binding and so to make this work without
        //          relying on ordering, we need the GetOrCreate method.
        //      2. There are diffrent classes for diffrent SOAP versions and the extensions that determines the version is
        //          also un-ordered so when we finally figure out the version we may need to recreate the BindingExtension and
        //          clone it.

        internal static WsdlNS.SoapAddressBinding GetOrCreateSoapAddressBinding(WsdlNS.Binding wsdlBinding, WsdlNS.Port wsdlPort, WsdlExporter exporter)
        {
            if (GetSoapVersionState(wsdlBinding, exporter) == EnvelopeVersion.None)
            {
                return(null);
            }

            WsdlNS.SoapAddressBinding existingSoapAddressBinding = GetSoapAddressBinding(wsdlPort);
            EnvelopeVersion           version = GetSoapVersion(wsdlBinding);

            if (existingSoapAddressBinding != null)
            {
                return(existingSoapAddressBinding);
            }

            WsdlNS.SoapAddressBinding soapAddressBinding = CreateSoapAddressBinding(version, wsdlPort);
            return(soapAddressBinding);
        }
        void CheckDuplicateSoapAddressBinding(ConformanceCheckContext ctx, ServiceDescription value)
        {
            ArrayList locations = new ArrayList();

            foreach (PortType p in value.PortTypes)
            {
                SoapAddressBinding b = (SoapAddressBinding)p.Extensions.Find(typeof(SoapAddressBinding));
                if (b == null || b.Location == null || b.Location.Length == 0)
                {
                    continue;
                }
                if (locations.Contains(b.Location))
                {
                    ctx.ReportRuleViolation(value, BasicProfileRules.R2711);
                    // One report for one ServiceDescription should be enough.
                    return;
                }
                locations.Add(b.Location);
            }
        }
Пример #13
0
        void IWsdlExportExtension.ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext endpointContext)
        {
            bool createdNew;
            MessageEncodingBindingElement encodingBindingElement = FindMessageEncodingBindingElement(endpointContext, out createdNew);
            bool useWebSocketTransport = WebSocketHelper.UseWebSocketTransport(this.WebSocketSettings.TransportUsage, endpointContext.ContractConversionContext.Contract.IsDuplex());

            EndpointAddress address = endpointContext.Endpoint.Address;

            if (useWebSocketTransport)
            {
                address = new EndpointAddress(WebSocketHelper.GetWebSocketUri(endpointContext.Endpoint.Address.Uri), endpointContext.Endpoint.Address);
                WsdlNS.SoapAddressBinding binding = SoapHelper.GetSoapAddressBinding(endpointContext.WsdlPort);
                if (binding != null)
                {
                    binding.Location = address.Uri.AbsoluteUri;
                }
            }

            TransportBindingElement.ExportWsdlEndpoint(exporter, endpointContext,
                                                       this.GetWsdlTransportUri(useWebSocketTransport), address, encodingBindingElement.MessageVersion.Addressing);
        }
        //this imports the address of the endpoint.
        void ImportAddress(WsdlEndpointConversionContext context)
        {
            EndpointAddress address = null;

            if (context.WsdlPort != null)
            {
                XmlElement addressing10Element =
                    context.WsdlPort.Extensions.Find("EndpointReference", AddressingVersionConstants.WSAddressing10NameSpace);

                XmlElement addressing200408Element =
                    context.WsdlPort.Extensions.Find("EndpointReference", AddressingVersionConstants.WSAddressingAugust2004NameSpace);

                WsdlNS.SoapAddressBinding soapAddressBinding =
                    (WsdlNS.SoapAddressBinding)context.WsdlPort.Extensions.Find(typeof(WsdlNS.SoapAddressBinding));

                if (addressing10Element != null)
                {
                    address = EndpointAddress.ReadFrom(AddressingVersion.WSAddressing10,
                                                       new XmlNodeReader(addressing10Element));
                }
                if (addressing200408Element != null)
                {
                    address = EndpointAddress.ReadFrom(AddressingVersion.WSAddressingAugust2004,
                                                       new XmlNodeReader(addressing200408Element));
                }
                else if (soapAddressBinding != null)
                {
                    // checking for soapAddressBinding checks for both Soap 1.1 and Soap 1.2
                    address = new EndpointAddress(soapAddressBinding.Location);
                }
            }

            if (address != null)
            {
                context.Endpoint.Address = address;
            }
        }
Пример #15
0
        protected override CodeTypeDeclaration BeginClass()
        {
            soapBinding = (SoapBinding)Binding.Extensions.Find(typeof(SoapBinding));

            CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName);

#if NET_2_0
            codeClass.IsPartial = true;
#endif

            string location = null;

            if (Port != null)
            {
                SoapAddressBinding sab = (SoapAddressBinding)Port.Extensions.Find(typeof(SoapAddressBinding));
                if (sab != null)
                {
                    location = sab.Location;
                }
            }

            string namspace = (Port != null ? Port.Binding.Namespace : Binding.ServiceDescription.TargetNamespace);
            string name     = (Port != null ? Port.Name : Binding.Name);

            if (Style == ServiceDescriptionImportStyle.Client)
            {
                CodeTypeReference ctr = new CodeTypeReference("System.Web.Services.Protocols.SoapHttpClientProtocol");
                codeClass.BaseTypes.Add(ctr);
            }
            else
            {
                CodeTypeReference ctr = new CodeTypeReference("System.Web.Services.WebService");
                codeClass.BaseTypes.Add(ctr);
                CodeAttributeDeclaration attws = new CodeAttributeDeclaration("System.Web.Services.WebServiceAttribute");
                attws.Arguments.Add(GetArg("Namespace", namspace));
                AddCustomAttribute(codeClass, attws, true);
            }

            CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.Web.Services.WebServiceBinding");
            att.Arguments.Add(GetArg("Name", name));
            att.Arguments.Add(GetArg("Namespace", namspace));
            AddCustomAttribute(codeClass, att, true);

            if (Style == ServiceDescriptionImportStyle.Client)
            {
                CodeConstructor cc = new CodeConstructor();
                cc.Attributes = MemberAttributes.Public;
                GenerateServiceUrl(location, cc.Statements);

#if NET_2_0
                if (ProtocolName.ToUpper() == "SOAP12")
                {
                    CodeExpression thisSoapVer = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "SoapVersion");
                    CodeFieldReferenceExpression soap12Enum =
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(SoapProtocolVersion)), "Soap12");
                    cc.Statements.Add(new CodeAssignStatement(thisSoapVer, soap12Enum));
                }
#endif
                codeClass.Members.Add(cc);
            }

            memberIds       = new CodeIdentifiers();
            headerVariables = new Hashtable();
            return(codeClass);
        }
Пример #16
0
		Port ExportService (WSServiceDescription sd, WSBinding ws_binding, EndpointAddress address, bool msg_version_none)
		{
			if (address == null)
				return null;

			Service ws_svc = GetService (sd, "service");
			sd.Name = "service";

				Port ws_port = new Port ();
				ws_port.Name = ws_binding.Name;
				ws_port.Binding = new QName (ws_binding.Name, sd.TargetNamespace);

				if (!msg_version_none) {
					SoapAddressBinding soap_addr = new SoapAddressBinding ();
					soap_addr.Location = address.Uri.AbsoluteUri;

					ws_port.Extensions.Add (soap_addr);
				}

			ws_svc.Ports.Add (ws_port);

			return ws_port;
		}
Пример #17
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();
        }
 protected virtual SoapAddressBinding CreateSoapAddressBinding(string serviceUrl) {
     SoapAddressBinding soapAddress = new SoapAddressBinding();
     soapAddress.Location = serviceUrl;
     if (this.UriFixups != null)
     {
         this.UriFixups.Add(delegate(Uri current)
         {
             soapAddress.Location = DiscoveryServerType.CombineUris(current, soapAddress.Location);
         });
     }
     return soapAddress;
 }
 private void Write119_SoapAddressBinding(string n, string ns, SoapAddressBinding o, bool isNullable, bool needType)
 {
     if (o == null)
     {
         if (isNullable)
         {
             base.WriteNullTagLiteral(n, ns);
         }
     }
     else
     {
         if (!needType && !(o.GetType() == typeof(SoapAddressBinding)))
         {
             throw base.CreateUnknownTypeException(o);
         }
         base.WriteStartElement(n, ns, o, false, null);
         if (needType)
         {
             base.WriteXsiType("SoapAddressBinding", "http://schemas.xmlsoap.org/wsdl/soap/");
         }
         if (o.Required)
         {
             base.WriteAttribute("required", "http://schemas.xmlsoap.org/wsdl/", XmlConvert.ToString(o.Required));
         }
         base.WriteAttribute("location", "", o.Location);
         base.WriteEndElement(o);
     }
 }
        private static void ConstructServiceElement(InterfaceContract serviceInterfaceContract, bool isRoundTrip, System.Web.Services.Description.ServiceDescription desc, string serviceName, string portTypeName, List<ServiceEndpoint> endpoints)
        {
            // Generate <service> element optionally - sometimes necessary for interop reasons
            if (serviceInterfaceContract.NeedsServiceElement)
            {
                Service defaultService = null;
                if (isRoundTrip || desc.Services.Count == 0)
                {
                    // Create a new service element.
                    defaultService = new Service();
                    defaultService.Name = serviceName;
                    foreach (ServiceEndpoint endpoint in endpoints)
                    {
                        if (endpoint.Binding.MessageVersion.Envelope == EnvelopeVersion.Soap11)
                        {
                            Port defaultPort = new Port();
                            defaultPort.Name = serviceInterfaceContract.ServiceName + "Port";
                            defaultPort.Binding = new XmlQualifiedName(endpoint.Name.Replace(Constants.InternalContractName, portTypeName), desc.TargetNamespace);
                            SoapAddressBinding defaultSoapAddressBinding = new SoapAddressBinding();
                            defaultSoapAddressBinding.Location = GetDefaultEndpoint(endpoint.Binding, serviceInterfaceContract.ServiceName);
                            defaultPort.Extensions.Add(defaultSoapAddressBinding);
                            defaultService.Ports.Add(defaultPort);
                        }
                        else if (endpoint.Binding.MessageVersion.Envelope == EnvelopeVersion.Soap12)
                        {
                            Port soap12Port = new Port();
                            soap12Port.Name = serviceInterfaceContract.ServiceName + "SOAP12Port";
                            soap12Port.Binding = new XmlQualifiedName(endpoint.Name.Replace(Constants.InternalContractName, portTypeName), desc.TargetNamespace);
                            Soap12AddressBinding soap12AddressBinding = new Soap12AddressBinding();
                            soap12AddressBinding.Location = GetDefaultEndpoint(endpoint.Binding, serviceInterfaceContract.ServiceName);
                            soap12Port.Extensions.Add(soap12AddressBinding);
                            defaultService.Ports.Add(soap12Port);
                        }
                    }

                    desc.Services.Add(defaultService);
                }
                else
                {
                    defaultService = desc.Services[0];
                    defaultService.Name = serviceName;
                }
            }
        }
Пример #21
0
        private void ConvertService(DescriptionType wsdl2, ServiceDescription wsdl1)
        {
            var services = wsdl2.Items.Where(s => s is ServiceType);

            foreach (ServiceType s2 in services)
            {
                var s1 = new Service();
                wsdl1.Services.Add(s1);
                s1.Name = s2.name;

                foreach (EndpointType e2 in s2.Items)
                {
                    var p1 = new Port();
                    s1.Ports.Add(p1);

                    p1.Name = e2.name;
                    p1.Binding = e2.binding;

                    var sab = new SoapAddressBinding() { Location = e2.address };
                    var sab12 = new Soap12AddressBinding() { Location = e2.address };
                    p1.Extensions.Add(sab);
                    p1.Extensions.Add(sab12);
                }
            }
        }
        /// <summary>
        /// Generates the WSDL file for a specified <see cref="InterfaceContract"/>.
        /// </summary>
        /// <param name="serviceInterfaceContract">
        /// <see cref="InterfaceContract"/> to use for the WSDL generation.
        /// </param>
        /// <param name="wsdlSaveLocation">Location to save the generated WSDL file.</param>
        /// <param name="xmlComment">XML comment to add to the top of the WSDL file.</param>
        /// <param name="wsdlLocation">Path of an existing WSDL file to overwrite with the generated 
        /// WSDL file.</param>
        /// <returns>The path of the WSDL file generated.</returns>
        /// <remarks>
        /// This methods loads the information, it receive in a <see cref="InterfaceContract"/> to
        /// a <see cref="System.Web.Services.Description.ServiceDescription"/> class, which is later 
        /// used to generate the WSDL file. The loading process takes place in several steps. <br></br>
        /// 1. Load the basic meta data from <see cref="InterfaceContract"/>.<br></br>
        /// 2. Load the schema imports in the <see cref="SchemaImports"/> collection.<br></br>
        /// 3. Load the messages in <see cref="OperationsCollection"/>.<br></br>
        /// 4. Create the WSDL Port Type.<br></br>
        /// 5. Add each operation and it's corresponding in/out messages to the Port Type.<br></br>
        /// 6. Create a WSDL Binding section and add OperationBinding for each operation.<br></br>
        /// 7. Generate the WSDL 'service' tags if required.<br></br>
        /// 8. Finally write the file to the output stream.<br></br>
        /// 
        /// This method generates <see cref="WsdlGenerationException"/> exception, if it fails to create the WSDL file.
        /// If a file is specified to overwrite with the new file, the original file is restored in case of
        /// a failure.
        /// </remarks>
        public static string GenerateWsdl(InterfaceContract serviceInterfaceContract,
            string wsdlSaveLocation, string xmlComment, string wsdlLocation)
        {
            System.Web.Services.Description.ServiceDescription desc = null;

            string serviceAttributeName = "";
            string bindingName = "";
            string serviceName = "";
            string portTypeName = "";

            // Load the existing WSDL if one specified.
            if (wsdlLocation != null)
            {
                #region Round-tripping

                desc = System.Web.Services.Description.ServiceDescription.Read(wsdlLocation);

                // Read the existing name values.
                serviceAttributeName = desc.Name;
                bindingName = desc.Bindings[0].Name;
                portTypeName = desc.PortTypes[0].Name;

                // Check whether we have a service element and save it's name for the 
                // future use.
                if (desc.Services.Count > 0)
                {
                    serviceName = desc.Services[0].Name;
                }
                else
                {
                    serviceName = serviceInterfaceContract.ServiceName + "Port"; ;
                }

                // Check for the place which has the Service name and assign the new value 
                // appropriatly.			
                if (serviceAttributeName != null && serviceAttributeName != "")
                {
                    serviceAttributeName = serviceInterfaceContract.ServiceName;
                }
                else if (serviceName != null && serviceName != "")
                {
                    // If the user has selected to remove the service element, 
                    // use the service name in the attribute by default.
                    if (serviceInterfaceContract.NeedsServiceElement)
                    {
                        serviceName = serviceInterfaceContract.ServiceName;
                    }
                    else
                    {
                        serviceAttributeName = serviceInterfaceContract.ServiceName;
                    }
                }
                else if (bindingName != null && bindingName != "")
                {
                    bindingName = serviceInterfaceContract.ServiceName;
                }

                // Clear the service description. But do not clear the types definitions.
                desc.Extensions.Clear();
                desc.Bindings.Clear();
                desc.Documentation = "";
                desc.Imports.Clear();
                desc.Messages.Clear();
                desc.PortTypes.Clear();
                desc.RetrievalUrl = "";

                if (desc.ServiceDescriptions != null)
                {
                    desc.ServiceDescriptions.Clear();
                }

                if (!serviceInterfaceContract.NeedsServiceElement)
                {
                    desc.Services.Clear();
                }
                #endregion
            }
            else
            {
                #region New WSDL

                desc = new System.Web.Services.Description.ServiceDescription();

                // Create the default names.
                serviceAttributeName = serviceInterfaceContract.ServiceName;
                bindingName = serviceInterfaceContract.ServiceName;
                portTypeName = serviceInterfaceContract.ServiceName + "Interface";
                serviceName = serviceInterfaceContract.ServiceName + "Port";

                #endregion
            }

            #region Load the basic meta data.
            if (serviceAttributeName != null && serviceAttributeName != "")
            {
                desc.Name = serviceAttributeName;
            }
            desc.TargetNamespace = serviceInterfaceContract.ServiceNamespace;
            desc.Documentation = serviceInterfaceContract.ServiceDocumentation;
            #endregion

            #region Load the schema imports.

            XmlSchema typesSchema = null;

            // Are we round-tripping? Then we have to access the existing types 
            // section.
            // Otherwise we just initialize a new XmlSchema for types.
            if (wsdlLocation != null)
            {
                typesSchema = desc.Types.Schemas[desc.TargetNamespace];
                // if we don't have a types section belonging to the same namespace as service description
                // we take the first types section available.                
                if (typesSchema == null)
                {
                    typesSchema = desc.Types.Schemas[0];
                }
                // Remove the includes. We gonna re-add them later in this operation.
                typesSchema.Includes.Clear();
            }
            else
            {
                typesSchema = new XmlSchema();
            }

            // Add imports to the types section resolved above.
            foreach (SchemaImport import in serviceInterfaceContract.Imports)
            {
                XmlSchemaExternal importedSchema = null;
                if (import.SchemaNamespace == null || import.SchemaNamespace == "")
                {
                    importedSchema = new XmlSchemaInclude();
                }
                else
                {
                    importedSchema = new XmlSchemaImport();
                    ((XmlSchemaImport)importedSchema).Namespace = import.SchemaNamespace;
                }
                if (serviceInterfaceContract.UseAlternateLocationForImports)
                {
                    importedSchema.SchemaLocation = import.AlternateLocation;
                }
                else
                {
                    importedSchema.SchemaLocation = import.SchemaLocation;
                }
                typesSchema.Includes.Add(importedSchema);
            }

            // If we are not round-tripping we have to link the types schema we just created to 
            // the service description.
            if (wsdlLocation == null)
            {
                // Finally add the type schema to the ServiceDescription.Types.Schemas collection.
                desc.Types.Schemas.Add(typesSchema);
            }

            #endregion

            #region Load the messages in all the operations

            MessageCollection msgs = desc.Messages;

            foreach (Operation op in serviceInterfaceContract.OperationsCollection)
            {
                foreach (Message msg in op.MessagesCollection)
                {
                    FxMessage tempMsg = new FxMessage();
                    tempMsg.Name = msg.Name;
                    tempMsg.Documentation = msg.Documentation;

                    MessagePart msgPart = new MessagePart();
                    msgPart.Name = Constants.DefaultMessagePartName;
                    msgPart.Element = new XmlQualifiedName(msg.Element.ElementName,
                            msg.Element.ElementNamespace);
                    tempMsg.Parts.Add(msgPart);

                    msgs.Add(tempMsg);
                }

				foreach (Message msg in op.Faults)
				{
					Message messageName = msg;
					if (msgs.OfType<FxMessage>().Any(m => m.Name == messageName.Name)) continue;

					FxMessage tempMsg = new FxMessage();
					tempMsg.Name = msg.Name;
					tempMsg.Documentation = msg.Documentation;

					MessagePart msgPart = new MessagePart();
					msgPart.Name = Constants.FaultMessagePartName;
					msgPart.Element = new XmlQualifiedName(msg.Element.ElementName, msg.Element.ElementNamespace);
					tempMsg.Parts.Add(msgPart);

					msgs.Add(tempMsg);
				}
            }

            #endregion

            #region Create the Port Type

            PortTypeCollection portTypes = desc.PortTypes;
            PortType portType = new PortType();
            portType.Name = portTypeName;
            portType.Documentation = serviceInterfaceContract.ServiceDocumentation;

            // Add each operation and it's corresponding in/out messages to the WSDL Port Type.
            foreach (Operation op in serviceInterfaceContract.OperationsCollection)
            {
                FxOperation tempOperation = new FxOperation();
                tempOperation.Name = op.Name;
                tempOperation.Documentation = op.Documentation;
                int i = 0;

                OperationInput operationInput = new OperationInput();
                operationInput.Message = new XmlQualifiedName(op.MessagesCollection[i].Name, desc.TargetNamespace);

                tempOperation.Messages.Add(operationInput);

                if (op.Mep == Mep.RequestResponse)
                {
                    OperationOutput operationOutput = new OperationOutput();
                    operationOutput.Message = new XmlQualifiedName(op.MessagesCollection[i + 1].Name, desc.TargetNamespace);

                    tempOperation.Messages.Add(operationOutput);
                }

				foreach (Message fault in op.Faults)
				{
					OperationFault operationFault = new OperationFault();
					operationFault.Name = fault.Name;
					operationFault.Message = new XmlQualifiedName(fault.Name, desc.TargetNamespace);
					tempOperation.Faults.Add(operationFault);
				}
				
                portType.Operations.Add(tempOperation);
                i++;
            }

            portTypes.Add(portType);

            #endregion

            // Here we have a list of WCF endpoints.
            // Currently we populate this list with only two endpoints that has default
            // BasicHttpBinding and default NetTcpBinding.
            List<ServiceEndpoint> endpoints = new List<ServiceEndpoint>();

            BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
            endpoints.Add(ServiceEndpointFactory<IDummyContract>.CreateServiceEndpoint(basicHttpBinding));

            // BDS (10/22/2007): Commented out the TCP binding generation as we are not going to support this feature
            // in this version.
            //NetTcpBinding netTcpBinding = new NetTcpBinding();
            //endpoints.Add(ServiceEndpointFactory<IDummyContract>.CreateServiceEndpoint(netTcpBinding));

            // Now, for each endpoint we have to create a binding in our service description.
            foreach (ServiceEndpoint endpoint in endpoints)
            {
                // Create a WSDL BindingCollection.
                BindingCollection bindings = desc.Bindings;
                System.Web.Services.Description.Binding binding = new System.Web.Services.Description.Binding();
                binding.Name = endpoint.Name.Replace(Constants.InternalContractName, portTypeName);
                binding.Type = new XmlQualifiedName(portType.Name, desc.TargetNamespace);

                // Create Operation binding for each operation and add it the the BindingCollection.
                foreach (Operation op in serviceInterfaceContract.OperationsCollection)
                {
                    // SOAP 1.1 Operation bindings.
                    OperationBinding operationBinding1 = new OperationBinding();
                    operationBinding1.Name = op.Name;

                    InputBinding inputBinding1 = new InputBinding();
                    object bodyBindingExtension = GetSoapBodyBinding(endpoint.Binding);
                    if (bodyBindingExtension != null)
                    {
                        inputBinding1.Extensions.Add(bodyBindingExtension);
                    }
                    operationBinding1.Input = inputBinding1;

					// Faults.
                	foreach (Message fault in op.Faults)
                	{
                		FaultBinding faultBinding = new FaultBinding();
                		faultBinding.Name = fault.Name;

						SoapFaultBinding faultBindingExtension = GetFaultBodyBinding(endpoint.Binding);
						if (faultBindingExtension != null)
						{
							faultBindingExtension.Name = fault.Name;
							faultBinding.Extensions.Add(faultBindingExtension);
						}

                		operationBinding1.Faults.Add(faultBinding);
                	}

                    // Input message.
                    // Look up the message headers for each Message and add them to the current binding.
                    foreach (MessageHeader inHeader in op.MessagesCollection[0].HeadersCollection)
                    {
                        object headerBindingExtension = GetSoapHeaderBinding(endpoint.Binding, inHeader.Message, desc.TargetNamespace);
                        if (headerBindingExtension != null)
                        {
                            inputBinding1.Extensions.Add(headerBindingExtension);
                        }
                    }

                    if (op.Mep == Mep.RequestResponse)
                    {
                        // Output message.
                        OutputBinding outputBinding1 = new OutputBinding();
                        object responseBodyBindingExtension = GetSoapBodyBinding(endpoint.Binding);
                        if (responseBodyBindingExtension != null)
                        {
                            outputBinding1.Extensions.Add(responseBodyBindingExtension);
                        }
                        operationBinding1.Output = outputBinding1;

                        // Look up the message headers for each Message and add them to the current binding. 
                        foreach (MessageHeader outHeader in op.MessagesCollection[1].HeadersCollection)
                        {
                            object headerBindingExtension = GetSoapHeaderBinding(endpoint.Binding, outHeader.Message, desc.TargetNamespace);
                            if (headerBindingExtension != null)
                            {
                                outputBinding1.Extensions.Add(headerBindingExtension);
                            }
                        }
                    }

                    string action = desc.TargetNamespace + ":" + op.Input.Name;
                    object operationBindingExtension = GetSoapOperationBinding(endpoint.Binding, action);
                    if (operationBindingExtension != null)
                    {
                        operationBinding1.Extensions.Add(operationBindingExtension);
                    }

                    binding.Operations.Add(operationBinding1);
                    // End of SOAP 1.1 operation bindings.                    
                }

                object soapBindingExtension = GetSoapBinding(endpoint.Binding);
                if (soapBindingExtension != null)
                {
                    binding.Extensions.Add(soapBindingExtension);
                }
                bindings.Add(binding);
            }

            // Generate <service> element optionally - sometimes necessary for interop reasons
            if (serviceInterfaceContract.NeedsServiceElement)
            {
                Service defaultService = null;
                if (wsdlLocation == null || desc.Services.Count == 0)
                {
                    // Create a new service element.
                    defaultService = new Service();
                    defaultService.Name = serviceName;
                    foreach (ServiceEndpoint endpoint in endpoints)
                    {
                        if (endpoint.Binding.MessageVersion.Envelope == EnvelopeVersion.Soap11)
                        {
                            Port defaultPort = new Port();
                            defaultPort.Name = serviceInterfaceContract.ServiceName + "Port";
                            defaultPort.Binding = new XmlQualifiedName(endpoint.Name.Replace(Constants.InternalContractName, portTypeName), desc.TargetNamespace);
                            SoapAddressBinding defaultSoapAddressBinding = new SoapAddressBinding();
                            defaultSoapAddressBinding.Location = GetDefaultEndpoint(endpoint.Binding, serviceInterfaceContract.ServiceName);
                            defaultPort.Extensions.Add(defaultSoapAddressBinding);
                            defaultService.Ports.Add(defaultPort);
                        }
                        else if (endpoint.Binding.MessageVersion.Envelope == EnvelopeVersion.Soap12)
                        {
                            Port soap12Port = new Port();
                            soap12Port.Name = serviceInterfaceContract.ServiceName + "SOAP12Port";
                            soap12Port.Binding = new XmlQualifiedName(endpoint.Name.Replace(Constants.InternalContractName, portTypeName), desc.TargetNamespace);
                            Soap12AddressBinding soap12AddressBinding = new Soap12AddressBinding();
                            soap12AddressBinding.Location = GetDefaultEndpoint(endpoint.Binding, serviceInterfaceContract.ServiceName);
                            soap12Port.Extensions.Add(soap12AddressBinding);
                            defaultService.Ports.Add(soap12Port);
                        }                        
                    }
                    
                    desc.Services.Add(defaultService);                    
                }
                else
                {
                    defaultService = desc.Services[0];
                    defaultService.Name = serviceName;
                }
            }

            // Generate the WSDL file.
            string fileName = string.Empty;
            string bkFileName = string.Empty;

            // Overwrite the existing file if one specified.
            if (wsdlLocation == null)
            {
                fileName = wsdlSaveLocation + @"\" + serviceInterfaceContract.ServiceName + ".wsdl";
            }
            else
            {
                fileName = wsdlLocation;
            }

            // Backup existing file before proceeding.
            if (File.Exists(fileName))
            {
                int index = 1;
                // Create the backup file name. 
                // See whether the generated backup file name is already taken by an existing file and 
                // generate a new file name. 
                while (File.Exists(fileName + "." + index.ToString()))
                {
                    index++;
                }
                bkFileName = fileName + "." + index.ToString();

                // Backup the file.
                try
                {
                    File.Copy(fileName, bkFileName);
                }
                catch (Exception ex)
                {
                    throw new WsdlGenerationException("An error occured while trying to generate a WSDL. Failed to backup the existing WSDL file.", ex);
                }
            }

            StreamWriter writer1 = new StreamWriter(fileName);
            try
            {
                XmlTextWriter writer11 = new XmlTextWriter(writer1);

                writer11.Formatting = Formatting.Indented;
                writer11.Indentation = 2;
                writer11.WriteComment(xmlComment);
                // BDS: Added a new comment line with the date time of WSDL file.
                CultureInfo ci = new CultureInfo("en-US");
                writer11.WriteComment(DateTime.Now.ToString("dddd", ci) + ", " + DateTime.Now.ToString("dd-MM-yyyy - hh:mm tt", ci));

                XmlSerializer serializer1 = System.Web.Services.Description.ServiceDescription.Serializer;
                XmlSerializerNamespaces nsSer = new XmlSerializerNamespaces();
                nsSer.Add("soap", "http://schemas.xmlsoap.org/wsdl/soap/");
                nsSer.Add("soap12", "http://schemas.xmlsoap.org/wsdl/soap12/");
                nsSer.Add("xsd", "http://www.w3.org/2001/XMLSchema");
                nsSer.Add("tns", desc.TargetNamespace);

                // Add the imported namespaces to the WSDL <description> element.
                for (int importIndex = 0; importIndex < serviceInterfaceContract.Imports.Count;
                    importIndex++)
                {
                    if (serviceInterfaceContract.Imports[importIndex].SchemaNamespace != null &&
                        serviceInterfaceContract.Imports[importIndex].SchemaNamespace != "")
                    {
                        nsSer.Add("import" + importIndex.ToString(),
                                  serviceInterfaceContract.Imports[importIndex].SchemaNamespace);
                    }
                }
                // 

                // Finally write the file to the output stram.
                serializer1.Serialize(writer11, desc, nsSer);

                // Close the stream and delete the backupfile.
                writer1.Close();
                if (bkFileName != string.Empty)
                {
                    File.Delete(bkFileName);
                }

                WsdlWorkshop workshop = new WsdlWorkshop(endpoints, fileName, portTypeName);
                workshop.BuildWsdl();
                return fileName;
            }
            catch (Exception ex)
            {
                writer1.Close();
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += ex.InnerException.Message;
                }

                // Restore the original file.
                if (bkFileName != string.Empty)
                {
                    try
                    {
                        File.Copy(bkFileName, fileName, true);
                        File.Delete(bkFileName);
                    }
                    catch
                    {
                        throw new WsdlGenerationException(
                            message + "\nFailed to restore the original file.");
                    }
                }
                else if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                throw new WsdlGenerationException(
                    message, ex);
            }
        }