public static void Main()
    {
// <Snippet1>
// <Snippet2>
        ServiceDescription myServiceDescription = new ServiceDescription();

        myServiceDescription =
            ServiceDescription.Read("ServiceDescription_Extensions_Input_cs.wsdl");
        Console.WriteLine(
            myServiceDescription.Bindings[1].Extensions[0].ToString());
        SoapBinding mySoapBinding = new SoapBinding();

        mySoapBinding.Required = true;
        SoapBinding mySoapBinding1 = new SoapBinding();

        mySoapBinding1.Required = false;
        myServiceDescription.Extensions.Add(mySoapBinding);
        myServiceDescription.Extensions.Add(mySoapBinding1);
        foreach (ServiceDescriptionFormatExtension
                 myServiceDescriptionFormatExtension
                 in myServiceDescription.Extensions)
        {
            Console.WriteLine("Required: " +
                              myServiceDescriptionFormatExtension.Required);
        }
        myServiceDescription.Write(
            "ServiceDescription_Extensions_Output_cs.wsdl");
        myServiceDescription.RetrievalUrl = "http://www.contoso.com/";
        Console.WriteLine("Retrieval URL is: " +
                          myServiceDescription.RetrievalUrl);
// </Snippet2>
// </Snippet1>
    }
Exemplo n.º 2
0
        /// <summary>
        /// Gets XML Web Services documents from a Spring resource.
        /// </summary>
        private DiscoveryClientDocumentCollection GetWsDocuments(IResource resource)
        {
            try
            {
                if (ServiceUri is UrlResource ||
                    ServiceUri is FileSystemResource)
                {
                    DiscoveryClientProtocol dcProtocol = new DiscoveryClientProtocol();
                    dcProtocol.AllowAutoRedirect = true;
                    dcProtocol.Credentials       = CreateCredentials();
                    dcProtocol.Proxy             = ConfigureProxy();
                    dcProtocol.DiscoverAny(resource.Uri.AbsoluteUri);
                    dcProtocol.ResolveAll();

                    return(dcProtocol.Documents);
                }
                else
                {
                    DiscoveryClientDocumentCollection dcdc = new DiscoveryClientDocumentCollection();
                    dcdc[resource.Description] = ServiceDescription.Read(resource.InputStream);
                    return(dcdc);
                }
            }
            catch (Exception ex)
            {
                throw new ArgumentException(String.Format("Couldn't retrieve the description of the web service located at '{0}'.", resource.Description), ex);
            }
        }
        public void Namespaces()
        {
            FileStream    fs  = new FileStream("Test/System.Web.Services.Description/test.wsdl", FileMode.Open);
            XmlTextReader xtr = new XmlTextReader(fs);

            ServiceDescription sd = ServiceDescription.Read(xtr);

            fs.Close();

            Assert.IsNotNull(sd.Namespaces);
            Assert.AreEqual(8, sd.Namespaces.Count, "#n0");

            ArrayList list = new ArrayList(sd.Namespaces.ToArray());

            list.Sort(new qname_comparer());

            Assert.AreEqual(new XmlQualifiedName("", "http://schemas.xmlsoap.org/wsdl/"), list [0]);
            Assert.AreEqual(new XmlQualifiedName("http", "http://schemas.xmlsoap.org/wsdl/http/"), list [1]);
            Assert.AreEqual(new XmlQualifiedName("mime", "http://schemas.xmlsoap.org/wsdl/mime/"), list [2]);
            Assert.AreEqual(new XmlQualifiedName("s", "http://www.w3.org/2001/XMLSchema"), list [3]);
            Assert.AreEqual(new XmlQualifiedName("s0", "http://tempuri.org/"), list [4]);
            Assert.AreEqual(new XmlQualifiedName("soap", "http://schemas.xmlsoap.org/wsdl/soap/"), list [5]);
            Assert.AreEqual(new XmlQualifiedName("soapenc", "http://schemas.xmlsoap.org/soap/encoding/"), list [6]);
            Assert.AreEqual(new XmlQualifiedName("tm", "http://microsoft.com/wsdl/mime/textMatching/"), list [7]);
        }
        /// <summary<
        /// 构造函数
        /// </summary<
        /// <param name="url"<</param<
        public WebServiceAgent(string url)
        {
            XmlTextReader reader = new XmlTextReader(url + "?wsdl");

            //创建和格式化 WSDL 文档
            ServiceDescription sd = ServiceDescription.Read(reader);

            //创建客户端代理代理类
            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();

            sdi.AddServiceDescription(sd, null, null);

            //使用 CodeDom 编译客户端代理类
            CodeNamespace   cn  = new CodeNamespace(CODE_NAMESPACE);
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);
            Microsoft.CSharp.CSharpCodeProvider icc = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            CompilerResults    cr = icc.CompileAssemblyFromDom(cp, ccu);

            agentType = cr.CompiledAssembly.GetTypes()[0];
            agent     = Activator.CreateInstance(agentType);
        }
Exemplo n.º 5
0
        public ServiceDescription Convert(XmlDocument wsdl2Xml)
        {
            CannonizePrefix(wsdl2Xml);
            var ser    = new XmlSerializer(typeof(DescriptionType));
            var reader = new StringReader(wsdl2Xml.OuterXml);
            var wsdl2  = (DescriptionType)ser.Deserialize(reader);

            var wsdl1 = new ServiceDescription();

            ConvertDescription(wsdl2, wsdl1);
            ConvertImports(wsdl2, wsdl1);
            ConvertTypes(wsdl2, wsdl1);
            ConvertInterface(wsdl2, wsdl1);
            ConvertBinding(wsdl2, wsdl1);
            ConvertService(wsdl2, wsdl1);

            //not sure why needs to do it... but otherwise code generation fails
            var m = new MemoryStream();

            wsdl1.Write(m);
            string s = Encoding.UTF8.GetString(m.GetBuffer());

            wsdl1 = ServiceDescription.Read(new StringReader(s));

            return(wsdl1);
        }
Exemplo n.º 6
0
        private object ReadLocalDocument(bool isSchema, string path)
        {
            object       obj1    = null;
            StreamReader reader1 = null;

            try
            {
                reader1 = new StreamReader(path);
                if (isSchema)
                {
                    return(XmlSchema.Read(new XmlTextReader(reader1), null));
                }
                obj1 = ServiceDescription.Read(reader1.BaseStream);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (reader1 != null)
                {
                    reader1.Close();
                }
            }
            return(obj1);
        }
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            CodeCompileUnit unit      = new CodeCompileUnit();
            CodeNamespace   proxyCode = new CodeNamespace();

            unit.Namespaces.Add(proxyCode);

            var description    = ServiceDescription.Read(OpenReader());
            var discCollection = new DiscoveryClientDocumentCollection()
            {
                {
                    VirtualPath, description
                }
            };

            var webref = new WebReferenceCollection()
            {
                new WebReference(discCollection, proxyCode)
            };

            var options = new WebReferenceOptions();

            options.Style = ServiceDescriptionImportStyle.Client;
            ServiceDescriptionImporter.GenerateWebReferences(webref, assemblyBuilder.CodeDomProvider, unit, options);

            assemblyBuilder.AddCodeCompileUnit(unit);
        }
Exemplo n.º 8
0
    public static void Main()
    {
        Binding myBinding;
// <Snippet1>
// <Snippet2>
// <Snippet3>
// <Snippet4>
        ServiceDescription myServiceDescription = ServiceDescription.Read("MathService_input.wsdl");

        Console.WriteLine("Total Number of bindings defined are:" + myServiceDescription.Bindings.Count);
        myBinding = myServiceDescription.Bindings[0];

        // Remove the first binding in the collection.
        myServiceDescription.Bindings.Remove(myBinding);
        Console.WriteLine("Successfully removed binding " + myBinding.Name);
        Console.WriteLine("Total Number of bindings defined now are:" + myServiceDescription.Bindings.Count);
        myServiceDescription.Write("MathService_temp.wsdl");
// </Snippet1>
        // Add binding to the ServiceDescription instance.
        myServiceDescription.Bindings.Add(myBinding);
// </Snippet2>
        if (myServiceDescription.Bindings.Contains(myBinding))
        {
            Console.WriteLine("Successfully added binding " + myBinding.Name);
        }
// </Snippet3>
        Console.WriteLine("Binding was added at index " + myServiceDescription.Bindings.IndexOf(myBinding));
        Console.WriteLine("Total Number of bindings defined now are:" + myServiceDescription.Bindings.Count);
        myServiceDescription.Write("MathService_temp1.wsdl");
// </Snippet4>
        myServiceDescription = null;
        myBinding            = null;
    }
Exemplo n.º 9
0
    consultarServicoWeb()
    {
        try
        {
            this.Cursor = Cursors.WaitCursor;

            XmlTextReader reader = new XmlTextReader(cboURL.Text);

            ServiceDescription service = ServiceDescription.Read(reader, false);

            WSDLParser parser = new WSDLParser(service);

            this.tvwService.Nodes.Add(parser.ServiceNode);
            this.cboURL.Items.Add(cboURL.Text);
            //http://soap.amazon.com/schemas2/AmazonWebServices.wsdl
            //http://glkev.webs.innerhost.com/glkev_ws/weatherfetcher.asmx?wsdl
        }
        catch (Exception e)
        {
            MessageBox.Show("Call to the Structural Validation Service " + " invalid WSDL Document  ");
        }
        finally
        {
            this.Cursor = Cursors.Default;
        }
    }
        /// <summary>
        /// Retrieve a list of available web methods for specified url
        /// Method modified from its original source:
        /// http://mikehadlow.blogspot.se/2006/06/simple-wsdl-object.html
        /// </summary>
        private List <string> GetWebServiceMethods(Uri url)
        {
            UriBuilder uriBuilder = new UriBuilder(url);

            uriBuilder.Query = "WSDL";

            List <string> methodNames = new List <string>();

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uriBuilder.Uri);

            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Method      = "GET";
            webRequest.Accept      = "text/xml";

            ServiceDescription serviceDescription;

            using (WebResponse response = webRequest.GetResponse())
                using (Stream stream = response.GetResponseStream())
                {
                    serviceDescription = ServiceDescription.Read(stream);
                }

            foreach (PortType portType in serviceDescription.PortTypes)
            {
                foreach (Operation operation in portType.Operations)
                {
                    //' Get the method name and add to list
                    methodNames.Add(operation.Name);
                }
            }

            return(methodNames);
        }
Exemplo n.º 11
0
        public void GetWebReferences()
        {
            DiscoveryClientDocumentCollection wsdlCollection = new DiscoveryClientDocumentCollection();
            ServiceDescription description = ServiceDescription.Read(new StringReader(_wsdlContent));

            wsdlCollection.Add(Url, description);

            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

            // Create a namespace and a unit for compilation.
            CodeCompileUnit unit  = new CodeCompileUnit();
            CodeNamespace   space = new CodeNamespace("DynamicWS.Soap");

            unit.Namespaces.Add(space);

            // Create a web referernce using the WSDL collection.
            WebReference reference = new WebReference(wsdlCollection, space)
            {
                ProtocolName = "Soap12"
            };

            // Create a web reference collection.
            WebReferenceCollection references = new WebReferenceCollection
            {
                reference
            };

            WebReferenceOptions options = new WebReferenceOptions
            {
                Style = ServiceDescriptionImportStyle.Client,
                CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync
            };

            StringCollection results = ServiceDescriptionImporter.GenerateWebReferences(references, provider, unit, options);
        }
    public static void Main( )
    {
// <Snippet1>
        ServiceDescription myServiceDescription = new ServiceDescription();

        myServiceDescription =
            ServiceDescription.Read("ServiceDescription_Imports_Input_CS.wsdl");
        ImportCollection myImportCollection = myServiceDescription.Imports;

        // Create an Import.
        Import myImport = new Import();

        myImport.Namespace = myServiceDescription.TargetNamespace;

        // Set the location for the Import.
        myImport.Location = "http://www.contoso.com/";
        myImportCollection.Add(myImport);
        myServiceDescription.Write("ServiceDescription_Imports_Output_CS.wsdl");
        myImportCollection.Clear();
        myServiceDescription =
            ServiceDescription.Read("ServiceDescription_Imports_Output_CS.wsdl");
        myImportCollection = myServiceDescription.Imports;
        Console.WriteLine(
            "The Import elements added to the ImportCollection are: ");
        for (int i = 0; i < myImportCollection.Count; i++)
        {
            Console.WriteLine((i + 1) + ". " + myImportCollection[i].Location);
        }
// </Snippet1>
    }
        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();
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// 动态调用web服务
        /// </summary>
        /// <param name="url">WSDL服务地址</param>
        /// <param name="classname">服务接口类名</param>
        /// <param name="methodname">方法名</param>
        /// <param name="args">参数值</param>
        /// <returns></returns>
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";

            if ((classname == null) || (classname == ""))
            {
                classname = WebServiceHelper.GetWsClassName(url);
            }
            try
            {
                //获取WSDL
                WebClient          wc     = new WebClient();
                Stream             stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription sd     = ServiceDescription.Read(stream);
                //注意classname一定要赋值获取
                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 icc = 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 = 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(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);
                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, new Exception(ex.StackTrace));
            }
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: hsproxygen [web service uri] [output dir]");
            }
            else
            {
                string wsdlUri   = args[0];
                string outputDir = args[1];

                Stream        wsdlStream = RetrieveWsdlXml(wsdlUri);
                XmlTextReader reader     = new XmlTextReader(wsdlStream);
                if (ServiceDescription.CanRead(reader))
                {
                    ServiceDescription desc = ServiceDescription.Read(reader);

                    if (wsdlUri.IndexOf("?WSDL") > 0)
                    {
                        desc.RetrievalUrl = wsdlUri.Substring(0, wsdlUri.IndexOf("?WSDL"));
                    }

                    ProxyModel proxyModel = new ProxyModel(desc);
                    Generator.CreateSpecificModule(proxyModel, outputDir);
                }

                wsdlStream.Close();
            }
        }
Exemplo n.º 16
0
    public static void Main()
    {
        try
        {
            ServiceDescription myServiceDescription1 =
                ServiceDescription.Read("DataTypes_CS.wsdl");
            ServiceDescription myServiceDescription2 =
                ServiceDescription.Read("MathService_CS.wsdl");
// <Snippet1>
// <Snippet2>
            // Create the object of 'ServiceDescriptionCollection' class.
            ServiceDescriptionCollection myCollection =
                new ServiceDescriptionCollection();
            // Add 'ServiceDescription' objects.
            myCollection.Add(myServiceDescription1);
            myCollection.Add(myServiceDescription2);
// </Snippet2>
// </Snippet1>
// <Snippet3>
            // Display element properties in collection using 'Item' property.
            for (int i = 0; i < myCollection.Count; i++)
            {
                Console.WriteLine(myCollection[i].TargetNamespace);
            }
// </Snippet3>
        }
        catch (Exception e)
        {
            Console.WriteLine("The following exception was raised: {0}", e.Message);
        }
    }
Exemplo n.º 17
0
    public static void Main()
    {
        try
        {
// <Snippet1>
            PortTypeCollection myPortTypeCollection;

            ServiceDescription myServiceDescription =
                ServiceDescription.Read("MathService_CS.wsdl");

            myPortTypeCollection = myServiceDescription.PortTypes;
            int noOfPortTypes = myServiceDescription.PortTypes.Count;
            Console.WriteLine("\nTotal number of PortTypes: "
                              + myServiceDescription.PortTypes.Count);

            // Copy the collection into an array.
            PortType[] myPortTypeArray = new PortType[noOfPortTypes];
            myPortTypeCollection.CopyTo(myPortTypeArray, 0);

            // Display names of all PortTypes.
            for (int i = 0; i < noOfPortTypes; i++)
            {
                Console.WriteLine("PortType name: " + myPortTypeArray[i].Name);
            }
            myServiceDescription.Write("MathService_New.wsdl");
// </Snippet1>
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
    }
    public static void Main()
    {
// <Snippet1>
        // Read from an existing wsdl file.
        ServiceDescription myServiceDescription =
            ServiceDescription.Read("MapToProperty_cs.wsdl");
        // Get the existing binding
        Binding          myBinding          = myServiceDescription.Bindings["MyWebServiceSoap"];
        OperationBinding myOperationBinding =
            (OperationBinding)myBinding.Operations[0];
        InputBinding myInputBinding = myOperationBinding.Input;
        // Get the 'SoapHeaderBinding' instance from 'myInputBinding'.
        SoapHeaderBinding mySoapHeaderBinding =
            (SoapHeaderBinding)myInputBinding.Extensions[1];

        if (mySoapHeaderBinding.MapToProperty)
        {
            Console.WriteLine("'SoapHeaderBinding' instance is mapped to a " +
                              "specific property in proxy generated class");
        }
        else
        {
            Console.WriteLine("'SoapHeaderBinding' instance is not mapped to " +
                              "a specific property in proxy generated class");
        }
// </Snippet1>
    }
Exemplo n.º 19
0
    public static void Main()
    {
        ServiceDescription myDescription = ServiceDescription.Read("Operation_5_Input_CS.wsdl");
        // Create a 'PortType' object.
        PortType myPortType = new PortType();

        myPortType.Name = "OperationServiceHttpPost";
        Operation myOperation = CreateOperation
                                    ("AddNumbers", "s0:AddNumbersHttpPostIn", "s0:AddNumbersHttpPostOut");

        myPortType.Operations.Add(myOperation);
// <Snippet5>
        // Get the PortType of the Operation.
        PortType myPort = myOperation.PortType;

        Console.WriteLine(
            "The port type of the operation is: " + myPort.Name);
// </Snippet5>
        // Add the 'PortType's to 'PortTypeCollection' of 'ServiceDescription'.
        myDescription.PortTypes.Add(myPortType);

        // Write the 'ServiceDescription' as a WSDL file.
        myDescription.Write("Operation_5_Output_CS.wsdl");
        Console.WriteLine("WSDL file with name 'Operation_5_Output_CS.wsdl' file created Successfully");
    }
Exemplo n.º 20
0
        public void ImportHttpOnlyWsdl()
        {
            ServiceDescriptionImporter imp =
                new ServiceDescriptionImporter();

            imp.AddServiceDescription(ServiceDescription.Read("Test/System.Web.Services.Description/test3.wsdl"), null, null);
            CodeNamespace   cns = new CodeNamespace();
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(cns);
            imp.Import(cns, ccu);
            // FIXME: this test could require more precise result
            bool verified = false;

            Assert.AreEqual(1, ccu.Namespaces.Count, "#1");
            Assert.AreEqual(1, ccu.Namespaces [0].Types.Count, "#2");
            foreach (CodeTypeDeclaration cd in ccu.Namespaces[0].Types)
            {
                Console.WriteLine("***" + cd.Name);
                if (cd.Name != "MyService")
                {
                    continue;
                }
                Assert.AreEqual("System.Web.Services.Protocols.HttpGetClientProtocol", cd.BaseTypes [0].BaseType);
                verified = true;
            }
            Assert.IsTrue(verified, "verified");
        }
    static void Main()
    {
        try
        {
// <Snippet1>
            ContractReference myContractReference = new ContractReference();
            FileStream        myFileStream        = new FileStream("TestOutput_cs.wsdl",
                                                                   FileMode.OpenOrCreate, FileAccess.Write);

            // Get the ServiceDescription for the test .wsdl file.
            ServiceDescription myServiceDescription =
                ServiceDescription.Read("TestInput_cs.wsdl");

            // Write the ServiceDescription into the file stream.
            myContractReference.WriteDocument(myServiceDescription, myFileStream);
            Console.WriteLine("ServiceDescription is written "
                              + "into the file stream successfully.");
            Console.WriteLine("The number of bytes written into the file stream: "
                              + myFileStream.Length);
            myFileStream.Close();
// </Snippet1>
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception raised:" + e.Message);
        }
    }
Exemplo n.º 22
0
    public static void Main()
    {
        try
        {
            ServiceDescription myServiceDescription1 =
                ServiceDescription.Read("DataTypes_CS.wsdl");
            ServiceDescription myServiceDescription2 =
                ServiceDescription.Read("MathService_CS.wsdl");

            // Create the object of 'ServiceDescriptionCollection' class.
            ServiceDescriptionCollection myCollection =
                new ServiceDescriptionCollection();
            // Add 'ServiceDescription' objects.
            myCollection.Add(myServiceDescription1);
            myCollection.Add(myServiceDescription2);
// <Snippet1>
            // Construct an XML qualified name.
            XmlQualifiedName myXmlQualifiedName =
                new XmlQualifiedName("MathServiceSoap", "http://tempuri2.org/");
            // Get the PortType from the collection.
            PortType myPort = myCollection.GetPortType(myXmlQualifiedName);
// </Snippet1>
            Console.WriteLine("Specified PortType is a member of ServiceDescription "
                              + "instances within the collection.");
        }
        catch (Exception e)
        {
            Console.WriteLine("The following exception was raised: {0}", e.Message);
        }
    }
Exemplo n.º 23
0
        private WfServiceOperationDefinition GetWfServiceOperationDefinition(string functionName, string servicAddressKey)
        {
            WfServiceAddressDefinition serviceAddressDef = WfGlobalParameters.Default.ServiceAddressDefs[servicAddressKey];
            string addressUri = GetWsdlUrl(serviceAddressDef.Address);

            WebClient wc = new WebClient();

            using (Stream stream = wc.OpenRead(addressUri))
            {
                ServiceDescription sd            = ServiceDescription.Read(stream);
                Binding            targetBinding = GetBinding(sd, serviceAddressDef.RequestMethod);

                if (targetBinding == null && serviceAddressDef.RequestMethod == WfServiceRequestMethod.Post)
                {
                    targetBinding = GetPostableBinding(sd);
                }

                if (targetBinding == null)
                {
                    throw new NotImplementedException("服务不支持此种操作类型" + serviceAddressDef.RequestMethod.ToString());
                }

                Operation operation = GetOperation(sd, targetBinding, functionName);

                WfServiceOperationParameterCollection reqParameters = GetOperationParams(sd, operation);

                WfServiceOperationDefinition operationDef =
                    new WfServiceOperationDefinition(serviceAddressDef.Key, functionName, reqParameters, string.Empty);

                return(operationDef);
            }
        }
Exemplo n.º 24
0
        private bool BuildWSDL(WebProperties WebProps, IntegrationLog Log)
        {
            try
            {
                Uri uri = new Uri(WebProps.Properties["WSDL"].ToString());
                //byte[] byteArray = Encoding.ASCII.GetBytes(WebProps.Properties["WSDL"].ToString());
                //MemoryStream stream = new MemoryStream(byteArray);
                WebRequest       webRequest = WebRequest.Create(uri);
                System.IO.Stream stream     = webRequest.GetResponse().GetResponseStream();

                ServiceDescription sd     = ServiceDescription.Read(stream);
                string             sdName = sd.Services[0].Name;

                // Initialize a service description servImport
                ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
                servImport.AddServiceDescription(sd, String.Empty, String.Empty);
                servImport.ProtocolName          = "Soap";
                servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

                CodeNamespace   nameSpace       = new CodeNamespace();
                CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                codeCompileUnit.Namespaces.Add(nameSpace);

                ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

                if (warnings == 0)
                {
                    using (var stringWriter = new StringWriter(CultureInfo.CurrentCulture))
                    {
                        var prov = new CSharpCodeProvider();
                        prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

                        var assemblyReferences = new string[2] {
                            "System.Web.Services.dll", "System.Xml.dll"
                        };
                        var param = new CompilerParameters(assemblyReferences)
                        {
                            GenerateExecutable    = false,
                            GenerateInMemory      = true,
                            TreatWarningsAsErrors = false,
                            WarningLevel          = 4,
                        };

                        var results = new CompilerResults(new TempFileCollection());
                        results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
                        var assembly = results.CompiledAssembly;
                        service = assembly.GetType(sdName);

                        methodInfo = service.GetMethods();
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                Log.LogMessage(ex.Message, IntegrationLogType.Error);
            }
            return(false);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Obter a descrição completa do serviço, ou seja, o WSDL do webservice de um arquivo local
        /// </summary>
        /// <param name="arquivoWSDL">Local e nome do arquivo WDDL</param>
        /// <param name="Certificado">Certificado digital</param>
        private void DescricaoServico(int cUF, bool taHomologacao, string arquivoWSDL)
        {
            //Forçar utilizar o protocolo SSL 3.0 que está de acordo com o manual de integração do SEFAZ
            //Wandrey 31/03/2010
            switch (cUF)
            {
            case 52:     //Estado de Goiás
                if (taHomologacao)
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                }
                else
                {
                    goto default;
                }
                break;

            case 3550308:     //Municipio de São Paulo-SP
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                break;

            default:
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                break;
            }

            //Definir a descrição completa do servido (WSDL)
            this.serviceDescription = ServiceDescription.Read(arquivoWSDL);
        }
Exemplo n.º 26
0
    public static void Main()
    {
        // Read the 'StockQuote.wsdl' file as input.
        ServiceDescription myServiceDescription = ServiceDescription.Read("StockQuote.wsdl");

        // Get the operation fault collection and remove the operation fault with the name 'ErrorString'.
        PortTypeCollection       myPortTypeCollection       = myServiceDescription.PortTypes;
        PortType                 myPortType                 = myPortTypeCollection[0];
        OperationCollection      myOperationCollection      = myPortType.Operations;
        Operation                myOperation                = myOperationCollection[0];
        OperationFaultCollection myOperationFaultCollection = myOperation.Faults;

        if (myOperationFaultCollection.Contains(myOperationFaultCollection["ErrorString"]))
        {
            myOperationFaultCollection.Remove(myOperationFaultCollection["ErrorString"]);
        }

        // Get the fault binding collection and remove the fault binding with the name 'ErrorString'.
// <Snippet1>
        BindingCollection          myBindingCollection          = myServiceDescription.Bindings;
        Binding                    myBinding                    = myBindingCollection[0];
        OperationBindingCollection myOperationBindingCollection = myBinding.Operations;
        OperationBinding           myOperationBinding           = myOperationBindingCollection[0];
        FaultBindingCollection     myFaultBindingCollection     = myOperationBinding.Faults;

        if (myFaultBindingCollection.Contains(myFaultBindingCollection["ErrorString"]))
        {
            myFaultBindingCollection.Remove(myFaultBindingCollection["ErrorString"]);
        }
// </Snippet1>

        myServiceDescription.Write(Console.Out);
    }
        public void ReadAndRetrievalUrl()
        {
            Assert.AreEqual(String.Empty, new ServiceDescription().RetrievalUrl, "#1");
            ServiceDescription sd = ServiceDescription.Read("Test/System.Web.Services.Description/test2.wsdl");

            Assert.AreEqual(String.Empty, sd.RetrievalUrl, "#2");
        }
Exemplo n.º 28
0
    public static void Main()
    {
        Console.WriteLine("Import Sample");
// <Snippet1>
        ServiceDescription myServiceDescription =
            ServiceDescription.Read("StockQuote_cs.wsdl");

        myServiceDescription.Imports.Add(
            CreateImport("http://localhost/stockquote/schemas",
                         "http://localhost/stockquote/stockquote_cs.xsd"));
// </Snippet1>
        // Save the ServiceDescripition to an external file.
        myServiceDescription.Write("StockQuote_cs.wsdl");
        Console.WriteLine(
            "Successfully added import to WSDL document 'StockQuote_cs.wsdl'");

        // Print the import collection to the console.
        PrintImportCollection("StockQuote_cs.wsdl");
// <Snippet2>
        myServiceDescription =
            ServiceDescription.Read("StockQuoteService_cs.wsdl");
        myServiceDescription.Imports.Insert(
            0, CreateImport("http://localhost/stockquote/definitions",
                            "http://localhost/stockquote/stockquote_cs.wsdl"));
// </Snippet2>
        // Save the ServiceDescripition to an external file.
        myServiceDescription.Write("StockQuoteService_cs.wsdl");
        Console.WriteLine("");
        Console.WriteLine("Successfully added import to WSDL " +
                          "document 'StockQuoteService_cs.wsdl'");

        //Print the import collection to the console.
        PrintImportCollection("StockQuoteService_cs.wsdl");
    }
Exemplo n.º 29
0
        static void Main()
        {
            ServiceDescription myServiceDescription =
                ServiceDescription.Read("MimeContentSample_cs.wsdl");

            // Get the Binding.
            Binding myBinding = myServiceDescription.Bindings["b1"];

            // Get the first OperationBinding.
            OperationBinding myOperationBinding = myBinding.Operations[0];
            OutputBinding    myOutputBinding    = myOperationBinding.Output;
            ServiceDescriptionFormatExtensionCollection
                myServiceDescriptionFormatExtensionCollection =
                myOutputBinding.Extensions;

            // Find all MimeContentBinding objects in extensions.
            MimeContentBinding[] myMimeContentBindings = (MimeContentBinding[])
                                                         myServiceDescriptionFormatExtensionCollection.FindAll(
                typeof(MimeContentBinding));

            // Enumerate the array and display MimeContentBinding properties.
            foreach (MimeContentBinding myMimeContentBinding in
                     myMimeContentBindings)
            {
                Console.WriteLine("Type: " + myMimeContentBinding.Type);
                Console.WriteLine("Part: " + myMimeContentBinding.Part);
            }
            Console.WriteLine("Namespace: " + MimeContentBinding.Namespace);
        }
        public void ReadAndRetrievalUrl()
        {
            Assert.AreEqual(String.Empty, new ServiceDescription().RetrievalUrl, "#1");
            ServiceDescription sd = ServiceDescription.Read(TestResourceHelper.GetFullPathOfResource("Test/System.Web.Services.Description/test2.wsdl"));

            Assert.AreEqual(String.Empty, sd.RetrievalUrl, "#2");
        }