Esempio n. 1
1
		public Binding ()
		{
			extensions = new ServiceDescriptionFormatExtensionCollection (this);
			operations = new OperationBindingCollection (this);
			serviceDescription = null;
			type = XmlQualifiedName.Empty;
		}
        void AddDocumentToSet(MetadataSet metadataSet, object document)
        {
            WsdlNS.ServiceDescription wsdl = document as WsdlNS.ServiceDescription;
            XmlSchema  schema = document as XmlSchema;
            XmlElement xmlDoc = document as XmlElement;

            if (wsdl != null)
            {
                metadataSet.MetadataSections.Add(MetadataSection.CreateFromServiceDescription(wsdl));
            }
            else if (schema != null)
            {
                metadataSet.MetadataSections.Add(MetadataSection.CreateFromSchema(schema));
            }
            else if (xmlDoc != null && MetadataSection.IsPolicyElement(xmlDoc))
            {
                metadataSet.MetadataSections.Add(MetadataSection.CreateFromPolicy(xmlDoc, null));
            }
            else
            {
                MetadataSection mexDoc = new MetadataSection();
                mexDoc.Metadata = document;
                metadataSet.MetadataSections.Add(mexDoc);
            }
        }
		public override void FixtureSetUp()
		{
			base.FixtureSetUp();
			// Set up the project.
			MSBuildBasedProject project = WebReferenceTestHelper.CreateTestProject("C#");
			project.FileName = FileName.Create("c:\\projects\\test\\foo.csproj");
			
			// Web references item.
			WebReferencesProjectItem webReferencesItem = new WebReferencesProjectItem(project);
			webReferencesItem.Include = "Web References\\";
			ProjectService.AddProjectItem(project, webReferencesItem);
			
			// Web reference url.
			WebReferenceUrl webReferenceUrl = new WebReferenceUrl(project);
			webReferenceUrl.Include = "http://localhost/test.asmx";
			webReferenceUrl.UpdateFromURL = "http://localhost/test.asmx";
			webReferenceUrl.RelPath = "Web References\\localhost";
			ProjectService.AddProjectItem(project, webReferenceUrl);
			
			FileProjectItem discoFileItem = new FileProjectItem(project, ItemType.None);
			discoFileItem.Include = "Web References\\localhost\\test.disco";
			ProjectService.AddProjectItem(project, discoFileItem);

			FileProjectItem wsdlFileItem = new FileProjectItem(project, ItemType.None);
			wsdlFileItem.Include = "Web References\\localhost\\test.wsdl";
			ProjectService.AddProjectItem(project, wsdlFileItem);
			
			// Proxy
			FileProjectItem proxyItem = new FileProjectItem(project, ItemType.Compile);
			proxyItem.Include = "Web References\\localhost\\Reference.cs";
			proxyItem.DependentUpon = "Reference.map";
			ProjectService.AddProjectItem(project, proxyItem);
			
			// Reference map.
			FileProjectItem mapItem = new FileProjectItem(project, ItemType.None);
			mapItem.Include = "Web References\\localhost\\Reference.map";
			ProjectService.AddProjectItem(project, mapItem);
			
			// System.Web.Services reference.
			ReferenceProjectItem webServicesReferenceItem = new ReferenceProjectItem(project, "System.Web.Services");
			ProjectService.AddProjectItem(project, webServicesReferenceItem);
			
			// Set up the web reference.
			DiscoveryClientProtocol	protocol = new DiscoveryClientProtocol();
			DiscoveryDocumentReference discoveryRef = new DiscoveryDocumentReference();
			discoveryRef.Url = "http://localhost/new.asmx";
			protocol.References.Add(discoveryRef);
			
			ContractReference contractRef = new ContractReference();
			contractRef.Url = "http://localhost/new.asmx?wsdl";
			contractRef.ClientProtocol = new DiscoveryClientProtocol();
			ServiceDescription desc = new ServiceDescription();
			contractRef.ClientProtocol.Documents.Add(contractRef.Url, desc);
			protocol.References.Add(contractRef);
			
			WebReferenceTestHelper.InitializeProjectBindings();
			
			var webReference = new Gui.WebReference(project, "http://localhost/new.asmx", "localhost", "ProxyNamespace", protocol);
			changes = webReference.GetChanges(project);
		}
Esempio n. 4
0
        private void AddDocumentToResults(object document, Collection <MetadataSection> results)
        {
            WsdlNS.ServiceDescription wsdl = document as WsdlNS.ServiceDescription;
            XmlSchema  schema = document as XmlSchema;
            XmlElement xmlDoc = document as XmlElement;

            if (wsdl != null)
            {
                results.Add(MetadataSection.CreateFromServiceDescription(wsdl));
            }
            else if (schema != null)
            {
                results.Add(MetadataSection.CreateFromSchema(schema));
            }
            else if (xmlDoc != null && xmlDoc.LocalName == "Policy")
            {
                results.Add(MetadataSection.CreateFromPolicy(xmlDoc, null));
            }
            else
            {
                MetadataSection mexDoc = new MetadataSection();
                mexDoc.Metadata = document;
                results.Add(mexDoc);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Open specified Wsdl file and parse content into ServiceDescription hierarchy. Method attempts
        /// to Import external schema references.
        /// </summary>
        /// <param name="fileName">A valid Wsdl file name.</param>
        /// <exception cref="FileNotFoundException">If specified file is cannot be opened.</exception>
        public void ParseWsdl(string fileName, List<string> schemaRefs)
        {
            isParsing = true;
            Logger.WriteLine("Reading WSDL file: " + fileName, LogLevel.Normal);

            // Use a validating xml reader to validate the schema. If it checks out
            // we only have to worry about building code fragements and data contracts.
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.ValidationFlags = XmlSchemaValidationFlags.AllowXmlAttributes |
                XmlSchemaValidationFlags.ProcessIdentityConstraints |
                XmlSchemaValidationFlags.ProcessInlineSchema |
                XmlSchemaValidationFlags.ProcessSchemaLocation |
                XmlSchemaValidationFlags.ReportValidationWarnings;

            // Create the reader
            settings.ValidationEventHandler += new ValidationEventHandler(Settings_ValidationEventHandler);

            XmlReader reader = XmlReader.Create(fileName, settings);

            if (!ServiceDescription.CanRead(reader)) throw new InvalidOperationException("The WSDL file is not compatible.");

            // Parse the Wsdl
            m_svcDesc = ServiceDescription.Read(reader, true);
            reader.Close();

            List<string> importFiles = new List<string>();
            importFiles.Add(fileName);

            ParseWsdl(m_svcDesc, schemaRefs, settings, importFiles);
        }
 private static Binding GetSoapBinding(ServiceDescription description, string bindingName)
 {
     var soapBindings = description.GetSoapBindings()
         .Where(binding => binding.Name == bindingName)
         .OrderByDescending(binding => binding.Type.Name);
     return soapBindings.FirstOrDefault();
 }
        private void AddDocumentToSet(MetadataSet metadataSet, object document)
        {
            System.Web.Services.Description.ServiceDescription serviceDescription = document as System.Web.Services.Description.ServiceDescription;
            System.Xml.Schema.XmlSchema schema = document as System.Xml.Schema.XmlSchema;
            XmlElement policy = document as XmlElement;

            if (serviceDescription != null)
            {
                metadataSet.MetadataSections.Add(MetadataSection.CreateFromServiceDescription(serviceDescription));
            }
            else if (schema != null)
            {
                metadataSet.MetadataSections.Add(MetadataSection.CreateFromSchema(schema));
            }
            else if ((policy != null) && MetadataSection.IsPolicyElement(policy))
            {
                metadataSet.MetadataSections.Add(MetadataSection.CreateFromPolicy(policy, null));
            }
            else
            {
                MetadataSection item = new MetadataSection {
                    Metadata = document
                };
                metadataSet.MetadataSections.Add(item);
            }
        }
        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);
        }
		public void SetUpFixture()
		{
			project = WebReferenceTestHelper.CreateTestProject("C#");
			project.FileName = "C:\\projects\\test\\foo.csproj";
			
			ReferenceProjectItem referenceItem = new ReferenceProjectItem(project, "System.Web.Services");
			ProjectService.AddProjectItem(project, referenceItem);
			
			protocol = new DiscoveryClientProtocol();
			DiscoveryDocumentReference discoveryRef = new DiscoveryDocumentReference();
			discoveryRef.Url = updateFromUrl;
			protocol.References.Add(discoveryRef);
			
			ContractReference contractRef = new ContractReference();
			contractRef.Url = "http://localhost/test.asmx?wsdl";
			contractRef.ClientProtocol = new DiscoveryClientProtocol();
			ServiceDescription desc = new ServiceDescription();
			contractRef.ClientProtocol.Documents.Add(contractRef.Url, desc);
			protocol.References.Add(contractRef);
			
			WebReferenceTestHelper.InitializeLanguageBindings();
			
			webReference = new SD.WebReference(project, updateFromUrl, name, proxyNamespace, protocol);
			webServicesReferenceProjectItem = (ReferenceProjectItem)WebReferenceTestHelper.GetProjectItem(webReference.Items, ItemType.Reference);
		}
        public void ExportEndpointTest()
        {
            WsdlExporter we = new WsdlExporter();

            ServiceEndpoint se = new ServiceEndpoint(ContractDescription.GetContract(typeof(IEchoService)));

            se.Binding = new BasicHttpBinding();
            se.Address = new EndpointAddress("http://localhost:8080");
            //TEST Invalid name: 5se.Name = "Service#1";
            //se.Name = "Service0";
            //se.ListenUri = new Uri ("http://localhost:8080/svc");

            we.ExportEndpoint(se);

            MetadataSet ms = we.GetGeneratedMetadata();

            Assert.AreEqual(6, ms.MetadataSections.Count);
            CheckContract_IEchoService(ms, "#eet01");

            WSServiceDescription sd = GetServiceDescription(ms, "http://tempuri.org/", "ExportEndpointTest");

            CheckServicePort(GetService(sd, "service", "ExportEndpointTest"),
                             "BasicHttpBinding_IEchoService", new XmlQualifiedName("BasicHttpBinding_IEchoService", "http://tempuri.org/"),
                             "http://localhost:8080/", "#eet02");

            CheckBasicHttpBinding(sd, "BasicHttpBinding_IEchoService", new XmlQualifiedName("IEchoService", "http://myns/echo"),
                                  "Echo", "http://myns/echo/IEchoService/Echo", true, true, "#eet03");
        }
Esempio n. 11
0
        /// <summary>
        /// Generate a DPWSClientProxy source file from a wsdl service description.
        /// </summary>
        /// <param name="serviceDesc">A valid wsdl service description.</param>
        public void GenerateClientProxy(ServiceDescription serviceDesc, TargetPlatform platform)
        {
            // Well here's a nasty used in an attempt to make up a name
            string clientProxyClassName = serviceDesc.Name;
            string clientProxyNs = CodeGenUtils.GenerateDotNetNamespace(serviceDesc.TargetNamespace);
            string filename = serviceDesc.Name + "ClientProxy.cs";

            ClientProxies clientProxies = new ClientProxies(clientProxyNs);

            foreach (PortType portType in serviceDesc.PortTypes)
            {
                ClientProxy clientProxy = new ClientProxy(portType.Name, platform);
                foreach (Operation operation in portType.Operations)
                {
                    // Create action names
                    // Apply special naming rules if this is a notification (event) operation
                    string inAction = serviceDesc.TargetNamespace + "/" + operation.Name + "Request";
                    string outAction = serviceDesc.TargetNamespace + "/" + operation.Name + ((operation.Messages.Flow == OperationFlow.Notification) ? "" : "Response");
                    clientProxy.AddOperation(operation, inAction, outAction);
                }

                foreach (Message message in serviceDesc.Messages)
                {
                    clientProxy.Messages.Add(message);
                }

                if (clientProxy.ServiceOperations.Count > 0)
                    clientProxies.Add(clientProxy);
            }

            ClientProxyGenerator clientProxyGen = new ClientProxyGenerator();
            clientProxyGen.GenerateCode(filename, clientProxies);
        }
Esempio n. 12
0
        /// <summary>
        /// Generate a DPWSHostedService source file from a Wsdl service description.
        /// </summary>
        /// <param name="serviceDesc">A valid wsdl service description.</param>
        public void GenerateHostedService(ServiceDescription serviceDesc, TargetPlatform platform)
        {
            // Well here's a nasty used in an attempt to make up a name
            string hostedServiceClassName = serviceDesc.Name;
            string hostedServiceNs = CodeGenUtils.GenerateDotNetNamespace(serviceDesc.TargetNamespace);
            string filename = serviceDesc.Name + "HostedService.cs";

            HostedServices hostedServices = new HostedServices(hostedServiceNs);

            foreach (PortType portType in serviceDesc.PortTypes)
            {
                HostedService hostedService = new HostedService(portType.Name, hostedServiceNs, platform);
                foreach (Operation operation in portType.Operations)
                {
                    // Create action names
                    // Apply special naming rules if this is a notification (event) operation
                    string inAction = serviceDesc.TargetNamespace + "/" + operation.Name + "Request";
                    string outAction = serviceDesc.TargetNamespace + "/" + operation.Name + ((operation.Messages.Flow == OperationFlow.Notification) ? "" : "Response");
                    hostedService.AddOperation(operation, inAction, outAction);
                }

                foreach (Message message in serviceDesc.Messages)
                {
                    hostedService.Messages.Add(message);
                }
            }

            HostedServiceGenerator hostedServiceGen = new HostedServiceGenerator();
            hostedServiceGen.GenerateCode(filename, hostedServices);
        }
Esempio n. 13
0
        private void AddMinimum(
            WSD.ServiceDescription wsdl,
            string contractName,
            OperationDescriptionCollection operations,
            ServiceEndpoint endpoint)
        {
            // Absolut minimum in order to provide a WSDL
            var portType =
                new WSD.PortType
            {
                Name = contractName
            };

            wsdl.PortTypes.Add(portType);
            var address =
                new WSD.Soap12AddressBinding
            {
                Location = endpoint.Address.ToString()
            };
            var port =
                new WSD.Port
            {
                Name = contractName
            };

            port.Extensions.Add(address);
            var service =
                new WSD.Service
            {
                Name = wsdl.Name
            };

            service.Ports.Add(port);
            wsdl.Services.Add(service);
        }
        void CheckMessage(WSServiceDescription sd, string msg_name, string part_name, string part_type, bool is_type, string label)
        {
            WSMessage m = sd.Messages [msg_name];

            Assert.IsNotNull(m, label + " : Message named " + msg_name + " not found.");

            Assert.AreEqual(msg_name, m.Name, label + " #cm1");
            Assert.AreEqual(0, m.Extensions.Count, label + " #cm2");

            Assert.IsNull(m.ExtensibleAttributes, label + " #cm3a");
            Assert.AreEqual(1, m.Parts.Count, label + " #cm3");

            Assert.AreEqual(part_name, m.Parts [0].Name, label + " #cm9");

            if (is_type)
            {
                Assert.AreEqual("", m.Parts [0].Element.ToString(), label + " #cm4");
                Assert.AreEqual(part_type, m.Parts [0].Type.ToString(), label + " #cm4a");
            }
            else
            {
                Assert.AreEqual("", m.Parts [0].Type.ToString(), label + " #cm5");
                Assert.AreEqual(part_type, m.Parts [0].Element.ToString(), label + " #cm5a");
            }

            Assert.IsNull(m.Parts [0].ExtensibleAttributes, label + " #cm6");
            Assert.AreEqual(0, m.Parts [0].Extensions.Count, label + " #cm7");
        }
Esempio n. 15
0
        private void RemoveOperationsFromBindings(System.Web.Services.Description.ServiceDescription wsdl, out List <string> policiesToRemove)
        {
            policiesToRemove = new List <string>();
            foreach (System.Web.Services.Description.Binding binding in wsdl.Bindings)
            {
                for (int i = binding.Operations.Count - 1; i >= 0; i--)
                {
                    if (m_operationsToRemove.Contains(binding.Operations[i].Name))
                    {
                        string inputPolicy = GetPolicyReferences(binding.Operations[i].Input);
                        if (inputPolicy != null)
                        {
                            policiesToRemove.Add(inputPolicy);
                        }

                        string outputPolicy = GetPolicyReferences(binding.Operations[i].Output);
                        if (outputPolicy != null)
                        {
                            policiesToRemove.Add(outputPolicy);
                        }

                        binding.Operations.RemoveAt(i);
                    }
                }
            }
        }
		public override void FixtureSetUp()
		{
			base.FixtureSetUp();
			project = WebReferenceTestHelper.CreateTestProject("C#");
			WebReferencesProjectItem item = new WebReferencesProjectItem(project);
			item.Include = "Web References\\";
			ProjectService.AddProjectItem(project, item);

			protocol = new DiscoveryClientProtocol();
			DiscoveryDocumentReference discoveryRef = new DiscoveryDocumentReference();
			discoveryRef.Url = updateFromUrl;
			protocol.References.Add(discoveryRef);

			ContractReference contractRef = new ContractReference();
			contractRef.Url = "http://localhost/test.asmx?wsdl";
			contractRef.ClientProtocol = new DiscoveryClientProtocol();
			ServiceDescription desc = new ServiceDescription();
			contractRef.ClientProtocol.Documents.Add(contractRef.Url, desc);
			protocol.References.Add(contractRef);

			WebReferenceTestHelper.InitializeProjectBindings();

			webReference = new Gui.WebReference(project, updateFromUrl, name, proxyNamespace, protocol);
			webReferencesProjectItem = WebReferenceTestHelper.GetProjectItem(webReference.Items, "Web References\\", ItemType.WebReferences);
		}
		internal int Add (ServiceDescription serviceDescription, string appSettingUrlKey, string appSettingBaseUrl)
		{
			if (importer != null)
				importer.OnServiceDescriptionAdded (serviceDescription, appSettingUrlKey, appSettingBaseUrl);
			Insert (Count, serviceDescription);
			return (Count - 1);
		}
		public static bool CheckConformance (WsiClaims claims, ServiceDescription service, BasicProfileViolationCollection violations)
		{
			ServiceDescriptionCollection col = new ServiceDescriptionCollection ();
			col.Add (service);
			ConformanceCheckContext ctx = new ConformanceCheckContext (col, violations);
			return Check (claims, ctx, col);
		}
		public int Add (ServiceDescription serviceDescription) 
		{
			if (importer != null)
				importer.OnServiceDescriptionAdded (serviceDescription, null, null);
			Insert (Count, serviceDescription);
			return (Count - 1);
		}
Esempio n. 20
0
		public void SetUpFixture()
		{
			project = WebReferenceTestHelper.CreateTestProject("C#");
			project.FileName = FileName.Create("C:\\projects\\test\\foo.csproj");

			protocol = new DiscoveryClientProtocol();
			DiscoveryDocumentReference discoveryRef = new DiscoveryDocumentReference();
			discoveryRef.Url = updateFromUrl;
			protocol.References.Add(discoveryRef);
			
			ContractReference contractRef = new ContractReference();
			contractRef.Url = "http://localhost/test.asmx?wsdl";
			contractRef.ClientProtocol = new DiscoveryClientProtocol();
			ServiceDescription desc = new ServiceDescription();
			contractRef.ClientProtocol.Documents.Add(contractRef.Url, desc);
			protocol.References.Add(contractRef);
			
			WebReferenceTestHelper.InitializeProjectBindings();
			
			webReference = new SD.WebReference(project, updateFromUrl, name, proxyNamespace, protocol);
			
			webReferenceUrl = webReference.WebReferenceUrl;
			discoFileProjectItem = WebReferenceTestHelper.GetFileProjectItem(webReference.Items, "Web References\\localhost\\test.disco", ItemType.None);
			referenceMapFileProjectItem = WebReferenceTestHelper.GetFileProjectItem(webReference.Items, "Web References\\localhost\\Reference.map", ItemType.None);
			wsdlFileProjectItem = WebReferenceTestHelper.GetFileProjectItem(webReference.Items, "Web References\\localhost\\test.wsdl", ItemType.None); 
			proxyFileProjectItem = WebReferenceTestHelper.GetFileProjectItem(webReference.Items, "Web References\\localhost\\Reference.cs", ItemType.Compile);
			webReferencesProjectItem = (WebReferencesProjectItem)WebReferenceTestHelper.GetProjectItem(webReference.Items, "Web References\\", ItemType.WebReferences);
			webServicesReferenceProjectItem = (ReferenceProjectItem)WebReferenceTestHelper.GetProjectItem(webReference.Items, ItemType.Reference);
		}
Esempio n. 21
0
		public Import ()
		{
			extensions = new ServiceDescriptionFormatExtensionCollection (this);
			location = String.Empty;
			ns = String.Empty;
			serviceDescription = null;
		}
        public void ExportEndpointTest2()
        {
            WsdlExporter we = new WsdlExporter();

            ServiceEndpoint se = new ServiceEndpoint(ContractDescription.GetContract(typeof(IEchoService2)));

            se.Binding = new BasicHttpBinding();
            se.Address = new EndpointAddress("http://localhost:8080");
            we.ExportEndpoint(se);

            MetadataSet ms = we.GetGeneratedMetadata();

            Assert.AreEqual(5, ms.MetadataSections.Count);

            WSServiceDescription sd = ms.MetadataSections [0].Metadata as WSServiceDescription;

            CheckContract_IEchoService2(ms, "#eet20");
            CheckServicePort(GetService(GetServiceDescription(ms, "http://tempuri.org/", "#eet21"), "service", "ExportEndpointTest"),
                             "BasicHttpBinding_ThisIsEchoService", new XmlQualifiedName("BasicHttpBinding_ThisIsEchoService", "http://tempuri.org/"),
                             "http://localhost:8080/", "#eet22");

            CheckBasicHttpBinding(sd, "BasicHttpBinding_ThisIsEchoService",
                                  new XmlQualifiedName("ThisIsEchoService", "http://tempuri.org/"),
                                  "Echo", "http://tempuri.org/ThisIsEchoService/Echo", true, true, "#eet03");

            //FIXME: CheckXmlSchema
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Enter address for the service wsdl");
            string str = Console.ReadLine();

            Console.WriteLine("Address of service is {0}", str);

            // Create a webrequest to the particular address as specified
            WebRequest request = WebRequest.Create(str);

            request.UseDefaultCredentials = true;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // Get the stream associated with the response. 
            Stream       receiveStream = response.GetResponseStream();
            StreamReader reader        = new StreamReader(receiveStream);

            System.Web.Services.Description.ServiceDescription wsdl = new System.Web.Services.Description.ServiceDescription();
            wsdl = ServiceDescription.Read(reader);

            foreach (PortType pt in wsdl.PortTypes)
            {
                Console.WriteLine("ServiceContract : {0}", pt.Name);
                Console.ReadLine();
            }
        }
    public SoapEditorProxy(Connections.ConnectionData connData, ServiceDescription description, XmlSchemaSet schemas)
    {
      _connData = connData;
      _descrip = description;
      _schemas = schemas;
      _helper = new XmlCompletionDataProvider(schemas, "http://schemas.xmlsoap.org/soap/envelope/"
        , "soapenv", () => "xmlns:soap=\"" + description.TargetNamespace + "\""
        , e => (e.Name == "Envelope" && e.QualifiedName.Namespace == "http://schemas.xmlsoap.org/soap/envelope/")
          || TypeMatchesAction(e.QualifiedName, this.Action));

      _baseUrl = new Uri(_connData.Url).GetLeftPart(UriPartial.Path);
      switch (_connData.Authentication)
      {
        case Connections.Authentication.Windows:
          _cred = CredentialCache.DefaultNetworkCredentials;
          break;
        case Connections.Authentication.Explicit:
          _cred = new NetworkCredential(_connData.UserName, _connData.Password);
          break;
      }

      _actionUrls = _descrip.Services.OfType<Service>()
        .SelectMany(s => s.Ports.OfType<Port>().Where(SoapPort))
        .SelectMany(p => _descrip.Bindings[p.Binding.Name].Operations.OfType<OperationBinding>())
        .Select(o => new { Name = o.Name, Address = o.Extensions.OfType<SoapOperationBinding>().First().SoapAction })
        .Distinct()
        .ToDictionary(a => a.Name, a => a.Address);
    }
		public override void FixtureSetUp()
		{
			base.FixtureSetUp();
			project = WebReferenceTestHelper.CreateTestProject("C#");
			project.FileName = FileName.Create("C:\\projects\\test\\foo.csproj");

			protocol = new DiscoveryClientProtocol();
			DiscoveryDocumentReference discoveryRef = new DiscoveryDocumentReference();
			discoveryRef.Url = updateFromUrl;
			protocol.References.Add(discoveryRef);
			
			ContractReference contractRef = new ContractReference();
			contractRef.Url = "http://localhost/test.asmx?wsdl";
			contractRef.ClientProtocol = new DiscoveryClientProtocol();
			ServiceDescription desc = new ServiceDescription();
			contractRef.ClientProtocol.Documents.Add(contractRef.Url, desc);
			protocol.References.Add(contractRef);
			
			WebReferenceTestHelper.InitializeProjectBindings();
			
			webReference = new Gui.WebReference(project, updateFromUrl, name, proxyNamespace, protocol);
			
			foreach (ProjectItem item in webReference.Items) {
				ProjectService.AddProjectItem(project, item);
			}
			webReferencesProjectItem = webReference.WebReferencesProjectItem;
		}
Esempio n. 26
0
        private static WsdlNS.ServiceDescription GetSingleWsdl(List <WsdlNS.ServiceDescription> wsdls)
        {
            // Use WSDL that has the contracts as the base for single WSDL
            WsdlNS.ServiceDescription singleWsdl = wsdls.First(wsdl => wsdl.PortTypes.Count > 0);
            if (singleWsdl == null)
            {
                singleWsdl = new WsdlNS.ServiceDescription();
            }
            else
            {
                singleWsdl.Types.Schemas.Clear();
                singleWsdl.Imports.Clear();
            }

            Dictionary <XmlQualifiedName, XmlQualifiedName> bindingReferenceChanges = new Dictionary <XmlQualifiedName, XmlQualifiedName>();

            foreach (WsdlNS.ServiceDescription wsdl in wsdls)
            {
                if (wsdl != singleWsdl)
                {
                    MergeWsdl(singleWsdl, wsdl, bindingReferenceChanges);
                }
            }

            EnsureSingleNamespace(singleWsdl, bindingReferenceChanges);
            return(singleWsdl);
        }
Esempio n. 27
0
        private static WsdlNS.ServiceDescription GetSingleWsdl(List<WsdlNS.ServiceDescription> wsdls)
        {
            // Use WSDL that has the contracts as the base for single WSDL
            WsdlNS.ServiceDescription singleWsdl = wsdls.First(wsdl => wsdl.PortTypes.Count > 0);
            if (singleWsdl == null)
            {
                singleWsdl = new WsdlNS.ServiceDescription();
            }
            else
            {
                singleWsdl.Types.Schemas.Clear();
                singleWsdl.Imports.Clear();
            }

            Dictionary<XmlQualifiedName, XmlQualifiedName> bindingReferenceChanges = new Dictionary<XmlQualifiedName, XmlQualifiedName>();
            foreach (WsdlNS.ServiceDescription wsdl in wsdls)
            {
                if (wsdl != singleWsdl)
                {
                    MergeWsdl(singleWsdl, wsdl, bindingReferenceChanges);
                }              
            }

            EnsureSingleNamespace(singleWsdl, bindingReferenceChanges);
            return singleWsdl;
        }
Esempio n. 28
0
        private async Task LoadAsWsdlAsync(XmlNS.XmlReader reader, string uri, string basePath, CancellationToken cancellationToken)
        {
            WsdlNS.ServiceDescription wsdl = await AsyncHelper.RunAsync(() => WsdlNS.ServiceDescription.Read(reader), cancellationToken).ConfigureAwait(false);

            wsdl.RetrievalUrl = uri;

            if (_resolveExternalDocs)
            {
                foreach (WsdlNS.Import import in wsdl.Imports)
                {
                    if (!string.IsNullOrWhiteSpace(import.Location))
                    {
                        var resolvedLocation = await LoadAsSchemaImportLocationAsync(import.Location, uri, basePath, import.Namespace, ".wsdl", cancellationToken).ConfigureAwait(false);

                        import.Location = resolvedLocation;
                    }
                }

                foreach (XmlNS.Schema.XmlSchema schema in wsdl.Types.Schemas)
                {
                    schema.SourceUri = uri;
                    await LoadAsXmlSchemaIncludesAsync(schema, wsdl.RetrievalUrl, basePath, cancellationToken).ConfigureAwait(false);
                }
            }

            _metadataSections.Add(MetadataSection.CreateFromServiceDescription(wsdl));
        }
Esempio n. 29
0
        /// <summary> 根据参数执行WebService </summary>
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            try
            {
                string _namespace = "WebService";
                if (string.IsNullOrEmpty(classname))
                {
                    classname = GetClassName(url);
                }
                //获取服务描述语言(WSDL)
                Net.WebClient wc     = new Net.WebClient();
                Stream        stream = wc.OpenRead(url + "?WSDL");                                                                   //【1】
                Web.Services.Description.ServiceDescription         sd  = Web.Services.Description.ServiceDescription.Read(stream);  //【2】
                Web.Services.Description.ServiceDescriptionImporter sdi = new Web.Services.Description.ServiceDescriptionImporter(); //【3】
                sdi.AddServiceDescription(sd, "", "");
                CodeDom.CodeNamespace cn = new CodeDom.CodeNamespace(_namespace);                                                    //【4】
                //生成客户端代理类代码
                CodeDom.CodeCompileUnit ccu = new CodeDom.CodeCompileUnit();                                                         //【5】
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                //CSharpCodeProvider csc = new CSharpCodeProvider();//【6】
                CodeDom.Compiler.CodeDomProvider csc = CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
                //ICodeCompiler icc = csc.CreateCompiler();//【7】

                //设定编译器的参数
                CodeDom.Compiler.CompilerParameters cplist = new CodeDom.Compiler.CompilerParameters();//【8】
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");
                //编译代理类
                CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);//【9】
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new StringBuilder();
                    foreach (CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t  = assembly.GetType(_namespace + "." + classname, true, true);
                object bj = Activator.CreateInstance(t);                   //【10】
                System.Reflection.MethodInfo mi = t.GetMethod(methodname); //【11】
                return(mi.Invoke(bj, args));
            }
            catch (System.Exception ex)
            {
                Common.LogHelper.Instance.WriteError(ex.Message + "|" + ex.StackTrace);
                //MessageManager.ShowErrorMsg(ex.Message.ToString(), "test");
                return(null);
            }
        }
Esempio n. 30
0
        public static void CheckExport(
            WS.ServiceDescription wsdl, QName contractName, string bindingName,
            int countEndpoints, TestLabel label)
        {
            label.EnterScope("ServiceDescription");
            Assert.That(wsdl.TargetNamespace, Is.EqualTo(contractName.Namespace), label.Get());
            Assert.That(wsdl.Name, Is.EqualTo("service"), label.Get());
            label.LeaveScope();

            label.EnterScope("Bindings");
            Assert.That(wsdl.Bindings, Is.Not.Null, label.Get());
            Assert.That(wsdl.Bindings.Count, Is.EqualTo(countEndpoints), label.Get());

            for (int i = 0; i < countEndpoints; i++)
            {
                label.EnterScope(string.Format("#{0}", i + 1));
                var binding      = wsdl.Bindings [i];
                var expectedName = string.Format(
                    "{0}_{1}{2}", bindingName, contractName.Name,
                    i > 0 ? i.ToString() : "");
                Assert.That(binding.Name, Is.EqualTo(expectedName), label.Get());
                Assert.That(binding.Type, Is.EqualTo(contractName), label.Get());
                label.LeaveScope();
            }
            label.LeaveScope();

            label.EnterScope("PortTypes");
            Assert.That(wsdl.PortTypes, Is.Not.Null, label.Get());
            Assert.That(wsdl.PortTypes.Count, Is.EqualTo(1), label.Get());
            var portType = wsdl.PortTypes [0];

            Assert.That(portType.Name, Is.EqualTo(contractName.Name), label.Get());
            label.LeaveScope();

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

            Assert.That(service.Name, Is.EqualTo("service"), label.Get());
            label.LeaveScope();

            label.EnterScope("Ports");
            Assert.That(service.Ports, Is.Not.Null, label.Get());
            Assert.That(service.Ports.Count, Is.EqualTo(countEndpoints), label.Get());
            for (int i = 0; i < countEndpoints; i++)
            {
                label.EnterScope(string.Format("#{0}", i + 1));
                var port         = service.Ports [i];
                var expectedName = string.Format(
                    "{0}_{1}{2}", bindingName, contractName.Name,
                    i > 0 ? i.ToString() : "");
                var qname = new QName(expectedName, contractName.Namespace);
                Assert.That(port.Name, Is.EqualTo(qname.Name), label.Get());
                Assert.That(port.Binding, Is.EqualTo(qname), label.Get());
                label.LeaveScope();
            }
            label.LeaveScope();
        }
        void CheckContract_IEchoService(MetadataSet ms, string label)
        {
            WSServiceDescription wsd = GetServiceDescription(ms, "http://myns/echo", label + "#a0");

            Assert.AreEqual(4, wsd.Messages.Count, "#cw5");

            Assert.IsNotNull(wsd.Messages [0]);
            //WSMessage m = wsd.Messages [0];

            CheckMessage(wsd, "IEchoService_Echo_InputMessage", "http://myns/echo:Echo");
            CheckMessage(wsd, "IEchoService_Echo_OutputMessage", "http://myns/echo:EchoResponse");

            CheckMessage(wsd, "IEchoService_DoubleIt_InputMessage", "http://myns/echo:DoubleIt");
            CheckMessage(wsd, "IEchoService_DoubleIt_OutputMessage", "http://myns/echo:DoubleItResponse");

            //PortTypes
            Assert.AreEqual(1, wsd.PortTypes.Count, "#cw6");
            PortType port = wsd.PortTypes [0];

            Assert.AreEqual("IEchoService", port.Name, "#cw7");

            //Operations
            Assert.AreEqual(2, port.Operations.Count, "#cw8");
            //Operations [0]
            Operation op = port.Operations [0];

            Assert.AreEqual("Echo", op.Name, "#co1");
            Assert.AreEqual(0, op.Extensions.Count, "#co2");
            Assert.IsNull(op.ParameterOrder, "#co3");
            Assert.AreEqual("", op.ParameterOrderString, "#co4");
            Assert.AreEqual(0, op.Faults.Count, "#co5");

            //OperationMessages
            Assert.AreEqual(2, op.Messages.Count, "#co6");
            Assert.AreEqual(OperationFlow.RequestResponse, op.Messages.Flow, "#co7");

            CheckOperationMessage(op.Messages [0], "http://myns/echo:IEchoService_Echo_InputMessage", typeof(OperationInput), "http://myns/echo/IEchoService/Echo");
            CheckOperationMessage(op.Messages [1], "http://myns/echo:IEchoService_Echo_OutputMessage", typeof(OperationOutput), "http://myns/echo/IEchoService/EchoResponse");

            op = port.Operations [1];
            Assert.AreEqual("DoubleIt", op.Name, "#co8");
            Assert.AreEqual(0, op.Extensions.Count, "#co9");
            Assert.IsNull(op.ParameterOrder, "#co10");
            Assert.AreEqual("", op.ParameterOrderString, "#co11");
            Assert.AreEqual(0, op.Faults.Count, "#co12");

            //OperationMessages
            Assert.AreEqual(2, op.Messages.Count, "#co13");
            Assert.AreEqual(OperationFlow.RequestResponse, op.Messages.Flow, "#co14");

            CheckOperationMessage(op.Messages [0], "http://myns/echo:IEchoService_DoubleIt_InputMessage", typeof(OperationInput), "http://myns/echo/IEchoService/DoubleIt");
            CheckOperationMessage(op.Messages [1], "http://myns/echo:IEchoService_DoubleIt_OutputMessage", typeof(OperationOutput), "http://myns/echo/IEchoService/DoubleItResponse");

            /* FIXME: Assert.AreEqual (1, wsd.Types.Schemas.Count, "#co20");
             * XmlSchema xs = wsd.Types.Schemas [0];
             *
             * Assert.AreEqual (4, xs.Includes.Count);
             * //FIXME: Check the imports.. */
        }
Esempio n. 32
0
		public Message ()
		{
#if !NET_2_0
			name = String.Empty;
#endif
			parts = new MessagePartCollection (this);
			serviceDescription = null;
		}
Esempio n. 33
0
        private string GetHeaderMessageName(MessageDescription messageDescription)
        {
            Message message         = this.ExportedMessages.WsdlMessages[new MessageDescriptionDictionaryKey(this.contractContext.Contract, messageDescription)];
            string  messageNameBase = string.Format(CultureInfo.InvariantCulture, "{0}_Headers", new object[] { message.Name });

            System.Web.Services.Description.ServiceDescription serviceDescription = this.contractContext.WsdlPortType.ServiceDescription;
            return(this.GetUniqueMessageName(serviceDescription, messageNameBase));
        }
Esempio n. 34
0
		public PortType ()
		{
			operations = new OperationCollection (this);
			serviceDescription = null;
#if NET_2_0
			extensions = new ServiceDescriptionFormatExtensionCollection (this);
#endif
		}
Esempio n. 35
0
		public Service ()
		{
			extensions = new ServiceDescriptionFormatExtensionCollection (this);
#if !NET_2_0
			name = String.Empty;
#endif
			ports = new PortCollection (this);
			serviceDescription = null;
		}
Esempio n. 36
0
        /// <summary>
        /// 实例化WebServices
        /// </summary>
        /// <param name="url">WebServices地址</param>
        /// <param name="methodname">调用的方法</param>
        /// <param name="args">把webservices里需要的参数按顺序放到这个object[]里</param>
        public static object InvokeWebService(string url, string methodname, object[] args)
        {
            string @namespace = "WSTools.Client";

            try
            {
                //获取WSDL
                WebClient wc     = new WebClient();
                Stream    stream = wc.OpenRead(url);
                WebServiceCore.ServiceDescription sd = WebServiceCore.ServiceDescription.Read(stream);
                string classname = sd.Services[0].Name;
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider csc = new CSharpCodeProvider();

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);
                var parameters = mi.GetParameters();

                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                return(args[2] = ex.Message + ex.InnerException != null ? ex.InnerException.Message : "");
            }
        }
Esempio n. 37
0
 public Schema Build(ServiceDescription description, string bindingName, Assembly assembly)
 {
     var binding = GetSoapBinding(description, bindingName);
     var serviceType = GetServiceType(binding, assembly);
     return new Schema {
         TypeName = serviceType.Name,
         Entities = BuildEntities(serviceType, binding)
     };
 }
Esempio n. 38
0
        SMMessage CreateWsdlMessage(WSServiceDescription wsdl)
        {
            MemoryStream ms = new MemoryStream();
            XmlWriter    xw = XmlWriter.Create(ms);

            WSServiceDescription.Serializer.Serialize(xw, wsdl);
            ms.Seek(0, SeekOrigin.Begin);
            return(SMMessage.CreateMessage(MessageVersion.None, "", XmlReader.Create(ms)));
        }
Esempio n. 39
0
 private void AddNamespaces(
     WSD.ServiceDescription wsdl,
     Dictionary <string, string> namespaces)
 {
     foreach (var ns in namespaces)
     {
         wsdl.Namespaces.Add(ns.Key, ns.Value);
     }
 }
Esempio n. 40
0
 private void AddTypes(
     WSD.ServiceDescription wsdl,
     XmlSchemaSet schemas)
 {
     foreach (XmlSchema schema in schemas.Schemas())
     {
         wsdl.Types.Schemas.Add(schema);
     }
 }
		CodeNamespace GenerateCodeFromWsdl (ServiceDescription sd)
		{
			ServiceDescriptionImporter imp =
				new ServiceDescriptionImporter ();
			imp.AddServiceDescription (sd, null, null);
			CodeNamespace cns = new CodeNamespace ();
			imp.Import (cns, null);
			return cns;
		}
Esempio n. 42
0
        private object InvokeWebservice(string url, string space, string classname, string methodname, object[] args)
        {
            try
            {
                System.Net.WebClient wc     = new System.Net.WebClient();
                System.IO.Stream     stream = wc.OpenRead(url + "?WSDL");
                System.Web.Services.Description.ServiceDescription         sd  = System.Web.Services.Description.ServiceDescription.Read(stream);
                System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                System.CodeDom.CodeNamespace   cn  = new System.CodeDom.CodeNamespace(space);
                System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);

                Microsoft.CSharp.CSharpCodeProvider   csc = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler();

                System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(space + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                //用来解决webservice上面有重载函数的问题
                Type[] types = new Type[args.Length];
                for (int i = 0; i < args.Length; i++)
                {
                    types[i] = args[i].GetType();
                }
                System.Reflection.MethodInfo mi = t.GetMethod(methodname, types);
                if (null == mi)
                {
                    return(null);
                }
                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
Esempio n. 43
0
        protected string GetFaultMessageName(string faultName)
        {
            string name            = this.contractContext.WsdlPortType.Name;
            string str2            = this.contractContext.GetOperation(this.operation).Name;
            string messageNameBase = string.Format(CultureInfo.InvariantCulture, "{0}_{1}_{2}_FaultMessage", new object[] { name, str2, faultName });

            System.Web.Services.Description.ServiceDescription serviceDescription = this.contractContext.WsdlPortType.ServiceDescription;
            return(this.GetUniqueMessageName(serviceDescription, messageNameBase));
        }
Esempio n. 44
0
        public static object WebserviceInvoke(string p_strUrl, string p_strNameSpace, string p_strClassName, string p_strMethodName, object[] p_objArgs)
        {
            object oReturnValue = null;

            try
            {
                if (p_strNameSpace == "")
                {
                    p_strNameSpace = "EnterpriseServerBase.WebService.DynamicWebCalling";
                }
                if (p_strClassName == "")
                {
                    p_strClassName = WebServiceHelper.GetWsClassName(p_strUrl);
                }
                System.Net.WebClient wc     = new System.Net.WebClient();
                System.IO.Stream     stream = wc.OpenRead(p_strUrl + "?wsdl");
                System.Web.Services.Description.ServiceDescription         sd  = System.Web.Services.Description.ServiceDescription.Read(stream);
                System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                System.CodeDom.CodeNamespace   cn  = new System.CodeDom.CodeNamespace(p_strNameSpace);
                System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);

                Microsoft.CSharp.CSharpCodeProvider        csc    = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(p_strNameSpace + "." + p_strClassName, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(p_strMethodName);
                oReturnValue = mi.Invoke(obj, p_objArgs);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
            return(oReturnValue);
        }
        WSBinding GetBinding(WSServiceDescription sd, string name, string label)
        {
            WSBinding ret = sd.Bindings [name];

            if (ret == null)
            {
                Assert.Fail(String.Format("[{0}] Binding named '{1}' not found.", label, name));
            }
            return(ret);
        }
		public void TestAddServiceDescriptionWithoutTargetNS ()
		{
			const string serviceDescriptionNamespace = "testServiceDescription";
			
			ServiceDescription sd = new ServiceDescription ();	
			sdc.Add (sd);

			Assertion.AssertEquals (1, sdc.Count);
			Assertion.AssertNull (sdc[serviceDescriptionNamespace]);
		}
        private static void InitializeDescription(InterfaceContract serviceInterfaceContract, ref System.Web.Services.Description.ServiceDescription desc, ref string serviceAttributeName, ref string bindingName, ref string serviceName, ref string portTypeName)
        {
            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";
        }
Esempio n. 48
0
		public Binding ()
		{
			extensions = new ServiceDescriptionFormatExtensionCollection (this);
#if !NET_2_0
			name = String.Empty;
#endif
			operations = new OperationBindingCollection (this);
			serviceDescription = null;
			type = XmlQualifiedName.Empty;
		}
Esempio n. 49
0
 private static void RemoveWsdlMessages(System.Web.Services.Description.ServiceDescription wsdl, List <string> messageNamesToRemove)
 {
     for (int i = wsdl.Messages.Count - 1; i >= 0; i--)
     {
         if (messageNamesToRemove.Contains(wsdl.Messages[i].Name))
         {
             wsdl.Messages.RemoveAt(i);
         }
     }
 }
        Service GetService(WSServiceDescription sd, string name, string label)
        {
            Service ret = sd.Services [name];

            if (ret == null)
            {
                Assert.Fail(String.Format("[{0}] Service named '{1}' not found.", label, name));
            }
            return(ret);
        }
 public static MetadataSection CreateFromServiceDescription(System.Web.Services.Description.ServiceDescription serviceDescription)
 {
     if (serviceDescription == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceDescription");
     }
     return(new MetadataSection {
         Dialect = ServiceDescriptionDialect, Identifier = serviceDescription.TargetNamespace, Metadata = serviceDescription
     });
 }
Esempio n. 52
0
        public SMMessage Get(SMMessage req)
        {
            EnsureMetadata();

            HttpRequestMessageProperty prop = (HttpRequestMessageProperty)req.Properties [HttpRequestMessageProperty.Name];

            NameValueCollection query_string = CreateQueryString(prop.QueryString);

            if (query_string == null || query_string.AllKeys.Length != 1)
            {
                if (HelpUrl != null && Uri.Compare(req.Headers.To, HelpUrl, UriComponents.HttpRequestUrl ^ UriComponents.Query, UriFormat.UriEscaped, StringComparison.Ordinal) == 0)
                {
                    return(CreateHelpPage(req));
                }
                WSServiceDescription w = GetWsdl("wsdl");
                if (w != null)
                {
                    return(CreateWsdlMessage(w));
                }
            }

            if (query_string [null] == "wsdl")
            {
                WSServiceDescription wsdl = GetWsdl("wsdl");
                if (wsdl != null)
                {
                    return(CreateWsdlMessage(wsdl));
                }
            }
            else if (query_string ["wsdl"] != null)
            {
                WSServiceDescription wsdl = GetWsdl(query_string ["wsdl"]);
                if (wsdl != null)
                {
                    return(CreateWsdlMessage(wsdl));
                }
            }
            else if (query_string ["xsd"] != null)
            {
                XmlSchema schema = GetXmlSchema(query_string ["xsd"]);
                if (schema != null)
                {
                    //FIXME: Is this the correct way?
                    MemoryStream ms = new MemoryStream();

                    schema.Write(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    SMMessage ret = SMMessage.CreateMessage(MessageVersion.None, "", XmlReader.Create(ms));

                    return(ret);
                }
            }

            return(CreateHelpPage(req));
        }
Esempio n. 53
0
		public Message ()
		{
#if !NET_2_0
			name = String.Empty;
#endif
#if NET_2_0
			extensions = new ServiceDescriptionFormatExtensionCollection (this);
#endif
			parts = new MessagePartCollection (this);
			serviceDescription = null;
		}
Esempio n. 54
0
        private static void EnsureSingleNamespace(WsdlNS.ServiceDescription wsdl, Dictionary <XmlQualifiedName, XmlQualifiedName> bindingReferenceChanges)
        {
            string targetNamespace = wsdl.TargetNamespace;

            foreach (WsdlNS.Binding binding in wsdl.Bindings)
            {
                if (binding.Type.Namespace != targetNamespace)
                {
                    binding.Type = new XmlQualifiedName(binding.Type.Name, targetNamespace);
                }
            }

            foreach (WsdlNS.PortType portType in wsdl.PortTypes)
            {
                foreach (WsdlNS.Operation operation in portType.Operations)
                {
                    WsdlNS.OperationInput messageInput = operation.Messages.Input;
                    if (messageInput != null && messageInput.Message.Namespace != targetNamespace)
                    {
                        messageInput.Message = new XmlQualifiedName(messageInput.Message.Name, targetNamespace);
                    }

                    WsdlNS.OperationOutput messageOutput = operation.Messages.Output;
                    if (messageOutput != null && messageOutput.Message.Namespace != targetNamespace)
                    {
                        messageOutput.Message = new XmlQualifiedName(messageOutput.Message.Name, targetNamespace);
                    }

                    foreach (WsdlNS.OperationFault fault in operation.Faults)
                    {
                        if (fault.Message.Namespace != targetNamespace)
                        {
                            fault.Message = new XmlQualifiedName(fault.Message.Name, targetNamespace);
                        }
                    }
                }
            }

            foreach (WsdlNS.Service service in wsdl.Services)
            {
                foreach (WsdlNS.Port port in service.Ports)
                {
                    XmlQualifiedName newPortBinding;
                    if (bindingReferenceChanges.TryGetValue(port.Binding, out newPortBinding))
                    {
                        port.Binding = newPortBinding;
                    }
                    else if (port.Binding.Namespace != targetNamespace)
                    {
                        port.Binding = new XmlQualifiedName(port.Binding.Name, targetNamespace);
                    }
                }
            }
        }
		public void TestAddServiceDescriptionWithTargetNS ()
		{
			const string serviceDescriptionNamespace = "http://some.urn";
			
			ServiceDescription sd = new ServiceDescription ();
			sd.TargetNamespace = serviceDescriptionNamespace;
			
			sdc.Add (sd);

			Assertion.AssertEquals (1, sdc.Count);
			Assertion.AssertEquals (sd, sdc[serviceDescriptionNamespace]);
		}
        public void GetServiceDescription_Returns_TheServiceDescription()
        {
            // Arrange.
            const string Url = "http://www.example.com/TestService.svc";
            const string Username = "******";
            const string Password = "******";

            Mock.Arrange(() => Arg.IsAny<DiscoveryClientProtocol>().DiscoverAny(Url)).DoNothing();
            Mock.Arrange(() => Arg.IsAny<DiscoveryClientProtocol>().ResolveAll()).DoNothing();

            var contract1 = new ServiceDescription();
            var contractReference1 = Mock.Create<ContractReference>(Behavior.Loose);
            Mock.Arrange(() => contractReference1.Contract).Returns(contract1);
            Mock.Arrange(() => contractReference1.Url).Returns("contract1");

            var contract2 = new ServiceDescription();
            var contractReference2 = Mock.Create<ContractReference>(Behavior.Loose);
            Mock.Arrange(() => contractReference2.Contract).Returns(contract2);
            Mock.Arrange(() => contractReference2.Url).Returns("contract2");
            
            var schema1 = new XmlSchema();
            var schemaReference1 = Mock.Create<SchemaReference>(Behavior.Loose);
            Mock.Arrange(() => schemaReference1.Schema).Returns(schema1);
            Mock.Arrange(() => schemaReference1.Url).Returns("schema1");
            
            var schema2 = new XmlSchema();
            var schemaReference2 = Mock.Create<SchemaReference>(Behavior.Loose);
            Mock.Arrange(() => schemaReference2.Schema).Returns(schema2);
            Mock.Arrange(() => schemaReference2.Url).Returns("schema2");

            var references = new DiscoveryClientReferenceCollection { contractReference1, contractReference2, schemaReference1, schemaReference2 };
            Mock.Arrange(() => Arg.IsAny<DiscoveryClientProtocol>().References).Returns(references);

            var retriever = new WebServiceDescriptionRetriever();

            // Act.
            var serviceDescription = retriever.GetServiceDescription(Url, Username, Password);

            // Assert.
            Mock.Assert(() => Arg.IsAny<DiscoveryClientProtocol>().DiscoverAny(Url), Occurs.Once());
            Mock.Assert(() => Arg.IsAny<DiscoveryClientProtocol>().ResolveAll(), Occurs.Once());

            Assert.IsNotNull(serviceDescription);
            Assert.AreEqual(2, serviceDescription.ServiceDescriptions.Count);
            Assert.IsTrue(serviceDescription.ServiceDescriptions.Contains(contract1));
            Assert.IsTrue(serviceDescription.ServiceDescriptions.Contains(contract2));
            
            Assert.AreEqual(2, serviceDescription.XmlSchemas.Count);
            Assert.IsTrue(serviceDescription.XmlSchemas.Contains(schema1));
            Assert.IsTrue(serviceDescription.XmlSchemas.Contains(schema2));
        }
Esempio n. 57
0
        /// <summary>
        /// Merge WSDL and XSD in filename and write it to destination
        /// </summary>
        /// <param name="first"></param>
        /// <param name="second"></param>
        public static ServiceDescription Merge(ServiceDescription firstWsdl, ServiceDescription secondWsdl)
        {
            foreach (XmlSchema xmlSchema in secondWsdl.Types.Schemas)
            {
                foreach (var include in xmlSchema.Includes.OfType<XmlSchemaImport>())
                {
                    var ns = include.Namespace;
                    var uri = include.SchemaLocation;

                    var firstSchema = firstWsdl.Types.Schemas.OfType<XmlSchema>().First();
                    if (!firstSchema.Includes.OfType<XmlSchemaImport>().Any(x => x.Namespace == ns && x.SchemaLocation == uri))
                    {
                        firstSchema.Includes.Add(include);
                    }
                }
            }

            foreach (Message message in secondWsdl.Messages)
            {
                if (firstWsdl.Messages.OfType<Message>().All(m => m.Name != message.Name))
                {
                    firstWsdl.Messages.Add(message);
                }
            }

            foreach (PortType portType in secondWsdl.PortTypes)
            {
                if (firstWsdl.PortTypes.OfType<PortType>().All(m => m.Name != portType.Name))
                {
                    firstWsdl.PortTypes.Add(portType);
                }
            }

            foreach (Binding binding in secondWsdl.Bindings)
            {
                if (firstWsdl.Bindings.OfType<Binding>().All(m => m.Name != binding.Name))
                {
                    firstWsdl.Bindings.Add(binding);
                }
            }

            foreach (Service service in secondWsdl.Services)
            {
                if (firstWsdl.Services.OfType<Service>().All(m => m.Name != service.Name))
                {
                    firstWsdl.Services.Add(service);
                }
            }

            return firstWsdl;
        }
Esempio n. 58
0
		public void Ctor ()
		{
			ServiceDescription sd = new ServiceDescription ();
			Assert.IsNotNull (sd.Bindings);
			Assert.IsNotNull (sd.Extensions);
			Assert.IsNotNull (sd.Imports);
			Assert.IsNotNull (sd.Messages);
			Assert.IsNotNull (sd.PortTypes);
			Assert.IsNotNull (sd.Services);
			Assert.IsNotNull (sd.Types);

			Assert.IsNull (sd.ServiceDescriptions);
			Assert.IsNull (sd.TargetNamespace);
		}
Esempio n. 59
0
 public static string GetServiceName(ServiceDescription description)
 {
     if (description.Name != null) {
         return description.Name;
     } else if (!String.IsNullOrEmpty(description.RetrievalUrl)) {
         Uri uri = new Uri(description.RetrievalUrl);
         if (uri.Segments.Length > 0) {
             return uri.Segments[uri.Segments.Length - 1];
         } else {
             return uri.Host;
         }
     }
     return String.Empty;
 }
		/// <summary>Read the service description for a specified uri.</summary>
		/// <param name="uri">A string containing the unique reference identifier for the service.</param>
		/// <returns>A ServiceDescription for the specified uri.</returns>
		public static ServiceDescription ReadServiceDescription(string uri) 
		{
			ServiceDescription desc = new ServiceDescription();
			try 
			{
				HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
				WebResponse response  = request.GetResponse();
			
				desc = ServiceDescription.Read(response.GetResponseStream());
				response.Close();
				desc.RetrievalUrl = uri;
			} 
			catch (Exception) {} 
			
			return desc;
		}