public void AddExtensionWarningComments(CodeCommentStatementCollection comments, ServiceDescriptionFormatExtensionCollection extensions)
 {
     foreach (object obj2 in extensions)
     {
         if (!extensions.IsHandled(obj2))
         {
             string localName = null;
             string namespaceURI = null;
             if (obj2 is XmlElement)
             {
                 XmlElement element = (XmlElement) obj2;
                 localName = element.LocalName;
                 namespaceURI = element.NamespaceURI;
             }
             else if (obj2 is ServiceDescriptionFormatExtension)
             {
                 XmlFormatExtensionAttribute[] customAttributes = (XmlFormatExtensionAttribute[]) obj2.GetType().GetCustomAttributes(typeof(XmlFormatExtensionAttribute), false);
                 if (customAttributes.Length > 0)
                 {
                     localName = customAttributes[0].ElementName;
                     namespaceURI = customAttributes[0].Namespace;
                 }
             }
             if (localName != null)
             {
                 if (extensions.IsRequired(obj2))
                 {
                     this.warnings |= ServiceDescriptionImportWarnings.RequiredExtensionsIgnored;
                     AddWarningComment(comments, System.Web.Services.Res.GetString("WebServiceDescriptionIgnoredRequired", new object[] { localName, namespaceURI }));
                 }
                 else
                 {
                     this.warnings |= ServiceDescriptionImportWarnings.OptionalExtensionsIgnored;
                     AddWarningComment(comments, System.Web.Services.Res.GetString("WebServiceDescriptionIgnoredOptional", new object[] { localName, namespaceURI }));
                 }
             }
         }
     }
 }
Пример #2
0
        private void GenerateCode(ServiceDescriptionCollection sources, XmlSchemas schemas, string uriToWSDL, ICodeGenerator codeGen, string fileExtension)
        {
            this.proxyCode = " <ERROR> ";
            StringWriter w = null;

            this.compileUnit = new CodeCompileUnit();
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            importer.Schemas.Add(schemas);
            foreach (ServiceDescription description in sources)
            {
                importer.AddServiceDescription(description, "", "");
            }
            importer.Style = ServiceDescriptionImportStyle.Client;
            Protocol protocol = this.WsdlProperties.Protocol;

            importer.ProtocolName = this.WsdlProperties.Protocol.ToString();
            CodeNamespace namespace2 = new CodeNamespace(this.proxyNamespace);

            this.compileUnit.Namespaces.Add(namespace2);
            ServiceDescriptionImportWarnings warnings = importer.Import(namespace2, this.compileUnit);

            try
            {
                try
                {
                    w = new StringWriter();
                }
                catch
                {
                    throw;
                }
                MemoryStream stream = null;
                if (schemas.Count > 0)
                {
                    this.compileUnit.ReferencedAssemblies.Add("System.Data.dll");
                    foreach (XmlSchema schema in schemas)
                    {
                        string targetNamespace = null;
                        try
                        {
                            targetNamespace = schema.TargetNamespace;
                            if (XmlSchemas.IsDataSet(schema))
                            {
                                if (stream == null)
                                {
                                    stream = new MemoryStream();
                                }
                                stream.Position = 0L;
                                stream.SetLength(0L);
                                schema.Write(stream);
                                stream.Position = 0L;
                                DataSet dataSet = new DataSet();
                                dataSet.ReadXmlSchema(stream);
                                TypedDataSetGenerator.Generate(dataSet, namespace2, codeGen);
                            }
                            continue;
                        }
                        catch
                        {
                            throw;
                        }
                    }
                }
                try
                {
                    GenerateVersionComment(this.compileUnit.Namespaces[0]);
                    this.ChangeBaseType(this.compileUnit);
                    codeGen.GenerateCodeFromCompileUnit(this.compileUnit, w, null);
                }
                catch (Exception exception)
                {
                    if (w != null)
                    {
                        w.Write("Exception in generating code");
                        w.Write(exception.Message);
                    }
                    throw new InvalidOperationException("Error generating ", exception);
                }
            }
            finally
            {
                this.proxyCode = w.ToString();
                if (w != null)
                {
                    w.Close();
                }
            }
        }
Пример #3
0
        public async Task <ReturnValue <object> > GetWebService(CancellationToken cancelToken)
        {
            var serviceDescription = await GetServiceDescription();

            if (serviceDescription.Success == false)
            {
                return(new ReturnValue <object>(serviceDescription.Success, serviceDescription.Message, serviceDescription.Exception, null));
            }

            return(await Task.Run(() =>
            {
                try
                {
                    // Initialize a service description importer.
                    // Use SOAP 1.2.
                    ServiceDescriptionImporter importer = new ServiceDescriptionImporter {
                        ProtocolName = "Soap12"
                    };

                    importer.AddServiceDescription(serviceDescription.Value, null, null);

                    // Generate a proxy client.
                    importer.Style = ServiceDescriptionImportStyle.Client;

                    // Generate properties to represent primitive values.
                    importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

                    // Initialize a Code-DOM tree into which we will import the service.
                    CodeNamespace nmspace = new CodeNamespace();
                    CodeCompileUnit unit1 = new CodeCompileUnit();
                    unit1.Namespaces.Add(nmspace);

                    // Import the service into the Code-DOM tree. This creates proxy code
                    // that uses the service.
                    ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);

                    if (warning == 0)
                    {
                        // Generate and print the proxy code in C#.
                        CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");

                        // Compile the assembly with the appropriate references
                        string[] assemblyReferences = new string[] { "System.Web.Services.dll", "System.Xml.dll" };
                        CompilerParameters parms = new CompilerParameters(assemblyReferences);
                        CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);

                        string errors = "";
                        foreach (CompilerError oops in results.Errors)
                        {
                            errors += oops.ErrorText;
                        }
                        if (errors != "")
                        {
                            State = EConnectionState.Broken;
                            return new ReturnValue <object>(false, "The following errors occurred importing the web service: " + errors, null, null);
                        }

                        //Invoke the web service method
                        object o = results.CompiledAssembly.CreateInstance(DefaultDatabase);
                        State = EConnectionState.Open;
                        return new ReturnValue <object>(true, "", null, o);
                    }

                    State = EConnectionState.Broken;
                    return new ReturnValue <object>(false, "The following warning occurred importing the web service: " + warning.ToString(), null, null);
                }
                catch (Exception ex)
                {
                    State = EConnectionState.Broken;
                    return new ReturnValue <object>(false, "The following error occurred importing the web service: " + ex.Message, ex, null);
                }
            }));
        }
Пример #4
0
            "https://maps.googleapis.com/maps/api/timezone/json?wsdl"; // application/json - INVALID_REQUEST
        //"http://date.jsontest.com?wsdl"; // application/json
        //"http://services.groupkt.com/country/get/all?wsdl"; // text/html

        public void Webservicecall()
        {
            WebRequest         webRequest  = WebRequest.Create(ENDPOINT);
            WebResponse        webResponse = webRequest.GetResponse();
            ServiceDescription description = null;

            List <PageConfig> pageConfigs = new List <PageConfig>();

            if (webResponse.ContentType.Contains("application/json") || webResponse.ContentType.Contains("text/json"))
            {
                using (Stream stream = webResponse.GetResponseStream())
                {
                    StreamReader streamReader   = new StreamReader(stream);
                    var          streamContents = streamReader.ReadToEnd();
                    //streamContents = "{\"time\":\"09:28:40 PM\", \"date\":\"09-21-2017\", \"SubObj\":{\"milliseconds_since_epoch\":1506029320396, \"Name\":\"Paul Moura\"}}";

                    JObject o     = (JObject)JsonConvert.DeserializeObject(streamContents);
                    var     props = o.Properties();

                    var       xmlDoc    = JsonConvert.DeserializeXmlNode(streamContents, "root");
                    XmlReader xmlReader = new XmlNodeReader(xmlDoc);
                    description = ServiceDescription.Read(xmlReader);
                }
            }
            else if (webResponse.ContentType.Contains("text/html") || webResponse.ContentType.Contains("text/plain"))
            {
                using (Stream stream = webResponse.GetResponseStream())
                {
                    StreamReader streamReader   = new StreamReader(stream);
                    var          streamContents = streamReader.ReadToEnd();
                    JObject      o         = (JObject)JsonConvert.DeserializeObject(streamContents);
                    var          props     = o.Properties();
                    var          xmlDoc    = JsonConvert.DeserializeXmlNode(streamContents);
                    XmlReader    xmlReader = new XmlNodeReader(xmlDoc);
                    description = ServiceDescription.Read(xmlReader);
                }
            }
            else
            {
                using (Stream stream = webResponse.GetResponseStream())
                {
                    StreamReader streamReader   = new StreamReader(stream);
                    var          streamContents = streamReader.ReadToEnd();
                }
                using (Stream stream = webResponse.GetResponseStream())
                {
                    description = ServiceDescription.Read(stream);
                }
            }

            ServiceDescriptionImporter importer = new ServiceDescriptionImporter {
                ProtocolName = "Soap12"
            };

            //' Use SOAP 1.2.
            importer.AddServiceDescription(description, null, null);
            importer.Style = ServiceDescriptionImportStyle.Client;

            //'--Generate properties to represent primitive values.
            importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
            //'Initialize a Code-DOM tree into which we will import the service.

            CodeNamespace   nmspace = new CodeNamespace();
            CodeCompileUnit unit1   = new CodeCompileUnit();

            unit1.Namespaces.Add(nmspace);
            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
            CodeDomProvider provider1 = CodeDomProvider.CreateProvider("C#");

            //'--Compile the assembly proxy with the // appropriate references
            string[] assemblyReferences = { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };

            CompilerParameters parms = new CompilerParameters(assemblyReferences)
            {
                GenerateInMemory = true
            };
            CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);

            if (results.Errors.Count > 0)
            {
            }

            List <string> typesStr  = new List <string>();
            Type          foundType = null;

            Type[] types = results.CompiledAssembly.GetTypes();
            foreach (Type type1 in types)
            {
                typesStr.Add(type1.FullName);
                typesStr.AddRange(type1.GetFields().Select(x => x.Name));
                typesStr.AddRange(type1.GetMethods().Select(x => x.Name));
                if (type1.BaseType == typeof(SoapHttpClientProtocol))
                {
                    foundType = type1;
                }
            }

            Object wsvcClass = results.CompiledAssembly.CreateInstance(foundType.ToString());

            foreach (var info in wsvcClass.GetType().GetMethods())
            {
                foreach (var parameter in info.GetParameters())
                {
                    Debug.WriteLine(parameter.ParameterType);
                }

                Debug.WriteLine(info.ReturnType);

                foreach (FieldInfo field in info.ReturnType.GetFields())
                {
                    Debug.WriteLine(field.FieldType);
                }
            }
        }
Пример #5
0
        /// <summary>
        /// 产生WebService引用DLL
        /// </summary>
        /// <returns></returns>
        public static string CreateWebServiceDll()
        {
            //if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "getWebServices.dll"))
            //    return string.Empty;
            WebClient web = new WebClient();

            web.Proxy = null;
            List <Stream>             lsstream      = new List <Stream>();
            List <ServiceDescription> lsdescription = new List <ServiceDescription>();
            Dictionary <string, ServiceDescription> dicdescription = new Dictionary <string, ServiceDescription>();

            XmlDocument doc = new XmlDocument();

            string XmlName = "DllConfig.xml";
            string dllname = "getWebServices.dll";

            doc.Load(XmlName);

            //string ServerURL = ((XmlElement)doc.SelectSingleNode("AutoCreate").SelectSingleNode("URLAddres")).GetAttribute("URL");
            if ((((XmlElement)doc.SelectSingleNode("AutoCreate").SelectSingleNode("NewIP")).GetAttribute("IP") !=
                 ((XmlElement)doc.SelectSingleNode("AutoCreate").SelectSingleNode("ServerIP")).GetAttribute("IP")) ||
                !File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + dllname))
            {
                ((XmlElement)doc.SelectSingleNode("AutoCreate").SelectSingleNode("ServerIP")).SetAttribute("IP",
                                                                                                           ((XmlElement)doc.SelectSingleNode("AutoCreate").SelectSingleNode("NewIP")).GetAttribute("IP"));

                string ServerURL = string.Format("http://{0}/{1}/",
                                                 ((XmlElement)doc.SelectSingleNode("AutoCreate").SelectSingleNode("ServerIP")).GetAttribute("IP"),
                                                 ((XmlElement)doc.SelectSingleNode("AutoCreate").SelectSingleNode("ServerPath")).GetAttribute("PATH"));

                CodeCompileUnit unit = new CodeCompileUnit();

                foreach (XmlNode xn in doc.SelectSingleNode("AutoCreate").SelectSingleNode("FileList").ChildNodes)
                {
                    string _temp = ((XmlElement)xn).GetAttribute("Name");
                    if (!string.IsNullOrEmpty(_temp))
                    {
                        dicdescription.Add(string.Format("WebServices.{0}", _temp.Split('.')[0]),
                                           ServiceDescription.Read(web.OpenRead(string.Format("{0}{1}?WSDL", ServerURL, _temp))));
                    }
                }

                foreach (string str in dicdescription.Keys)
                {
                    CodeNamespace nmspace = new CodeNamespace();
                    ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
                    importer.ProtocolName          = "Soap";
                    importer.Style                 = ServiceDescriptionImportStyle.Client;
                    importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                    nmspace.Name = str;
                    unit.Namespaces.Add(nmspace);
                    importer.AddServiceDescription(dicdescription[str], null, null);
                    ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
                }

                CodeDomProvider    provider  = CodeDomProvider.CreateProvider("CSharp");
                CompilerParameters parameter = new CompilerParameters();
                parameter.GenerateExecutable = false;
                parameter.OutputAssembly     = dllname;
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.ReferencedAssemblies.Add("System.XML.dll");
                parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                parameter.ReferencedAssemblies.Add("System.Data.dll");

                CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);
                StringBuilder   err    = new StringBuilder(50000);
                if (result.Errors.HasErrors)
                {
                    for (int i = 0; i < result.Errors.Count; i++)
                    {
                        err.AppendLine(result.Errors[i].ErrorText);
                    }
                }
                if (string.IsNullOrEmpty(err.ToString()))
                {
                    doc.Save(XmlName);
                }
                return(err.ToString());
            }
            return(null);
        }
Пример #6
0
        private static object dynamicWebServiceCall(string endpoint, string functionName, string locationName)
        {
            string servicoName = endpoint.Split('.')[0].Split('/')[3];
            ServiceDescriptionImporter descriptionImporter = new ServiceDescriptionImporter();

            descriptionImporter.ProtocolName          = "Soap";
            descriptionImporter.Style                 = ServiceDescriptionImportStyle.Client;
            descriptionImporter.CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync;

            DiscoveryClientProtocol clientProtocol = new DiscoveryClientProtocol();

            clientProtocol.DiscoverAny(endpoint);
            clientProtocol.ResolveAll();
            clientProtocol.Documents.Values.OfType <object>()
            .Select(document =>
            {
                if (document is ServiceDescription)
                {
                    descriptionImporter.AddServiceDescription(document as ServiceDescription, string.Empty, string.Empty);
                }
                else if (document is XmlSchema)
                {
                    descriptionImporter.Schemas.Add(document as XmlSchema);
                }
                return(true);
            })
            .ToList();

            CodeNamespace   codeNamemspace  = new CodeNamespace();
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            codeCompileUnit.Namespaces.Add(codeNamemspace);
            ServiceDescriptionImportWarnings warning = descriptionImporter.Import(codeNamemspace, codeCompileUnit);

            if (warning == 0)
            {
                // Generate and print the proxy code in C#.
                CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
                // Compile the assembly with the appropriate references
                string[]           assemblyReferences = new string[] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };
                CompilerParameters parms = new CompilerParameters(assemblyReferences);
                parms.GenerateInMemory = true;
                CompilerResults results = provider1.CompileAssemblyFromDom(parms, codeCompileUnit);

                foreach (CompilerError oops in results.Errors)
                {
                    Console.WriteLine("======== Compiler error ============");
                    Console.WriteLine(oops.ErrorText);
                }

                //Invoke the web service method
                object     o  = results.CompiledAssembly.CreateInstance(servicoName);
                MethodInfo mi = o.GetType().GetMethod(functionName);
                return(mi.Invoke(o, new String[] { locationName }));
            }
            else
            {
                // Print an error message.
                Console.WriteLine("Warning: " + warning);
                return(null);
            }
        }
Пример #7
0
        /// <summary>
        /// Get Parameters regarding to a specific method from wsdl.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="methodName"></param>
        private void getParameters(String url, String methodName)
        {
            try
            {
                //Get Service Description and required info.
                ServiceDescription         sd       = getServiceDescription(url);
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
                importer.ProtocolName = "Soap12";
                importer.AddServiceDescription(sd, null, null);
                importer.Style = ServiceDescriptionImportStyle.Client;
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync;
                ParameterInfo[] paramArr = null;

                CodeNamespace   nm   = new CodeNamespace();
                CodeCompileUnit unit = new CodeCompileUnit();
                unit.Namespaces.Add(nm);

                ServiceDescriptionImportWarnings warnings = importer.Import(nm, unit);

                if (warnings == 0)
                {
                    //set the CodeDOMProvider to C# to generate the code in C#
                    System.IO.StringWriter sw       = new System.IO.StringWriter();
                    CodeDomProvider        provider = CodeDomProvider.CreateProvider("C#");
                    provider.GenerateCodeFromCompileUnit(unit, sw, new CodeGeneratorOptions());
                    string sdName = sd.Services[0].Name;

                    //setting the CompilerParameters for the temporary assembly
                    string[]           refAssembly = { "System.dll", "System.Data.dll", "System.Web.Services.dll", "System.Xml.dll" };
                    CompilerParameters param       = new CompilerParameters(refAssembly);
                    CompilerResults    results     = provider.CompileAssemblyFromDom(param, unit);
                    object             o           = results.CompiledAssembly.CreateInstance(sd.Services[0].Name);
                    Type         service           = results.CompiledAssembly.GetType(sdName);
                    MethodInfo[] methods           = service.GetMethods();

                    Session["instance"] = o;
                    Session["type"]     = service;

                    foreach (MethodInfo meth in methods)
                    {
                        if (meth.Name.Equals(methodName))
                        {
                            paramArr = meth.GetParameters();
                            break;
                        }
                    }
                }

                //Code to display selected methods.
                tblButtons.Controls.Clear();

                TableRow tRow = new TableRow();

                TableCell tcLabel = new TableCell();
                TableCell tcType  = new TableCell();
                TableCell tcValue = new TableCell();

                tRow.Attributes.Add("style", "margin:15px;");

                Label lblHeader = new Label();
                lblHeader.Text = "Enter Parameters";
                lblHeader.Attributes.Add("style", "margin:10px;");

                pnlButtons.Controls.AddAt(0, lblHeader);

                //Label lblTemp1 = new Label();
                //Label lblTemp2 = new Label();

                //tcLabel.Controls.Add(lblHeader);
                //tcLabel.Controls.Add(lblHeader);
                //tcLabel.Controls.Add(lblHeader);

                //tRow.Controls.Add(tcLabel);
                //tRow.Controls.Add(tcType);
                //tRow.Controls.Add(tcValue);

                //tblButtons.Controls.Add(tRow);

                //to show input for parameters
                foreach (ParameterInfo param in paramArr)
                {
                    tRow = new TableRow();

                    tcLabel = new TableCell();
                    tcType  = new TableCell();
                    tcValue = new TableCell();

                    Label lblDescription = new Label();
                    lblDescription.Text = param.Name + " : ";
                    lblDescription.Attributes.Add("style", "margin:10px;");

                    Label lblType = new Label();
                    lblType.Text     = param.ParameterType.Name;
                    lblType.CssClass = "col-md-3";
                    lblType.Attributes.Add("style", "margin:10px;");

                    TextBox txtValue = new TextBox();
                    txtValue.ID = param.Name;
                    txtValue.Attributes.Add("style", "margin:10px;");
                    txtValue.CssClass = "form-control";

                    //add control to cells
                    tcLabel.Controls.Add(lblDescription);
                    tcType.Controls.Add(lblType);
                    tcValue.Controls.Add(txtValue);

                    //Add Controls to Row
                    tRow.Controls.Add(tcLabel);
                    tRow.Controls.Add(tcType);
                    tRow.Controls.Add(tcValue);

                    //Add row to table.
                    tblButtons.Controls.Add(tRow);
                }

                //To show a drop down to select the number oftimes the service need to be called.
                tRow = new TableRow();

                tcLabel = new TableCell();
                tcType  = new TableCell();
                tcValue = new TableCell();

                Label lblCount = new Label();
                lblCount.Text = "Select Repetations : ";
                lblCount.Attributes.Add("style", "margin:10px;");

                DropDownList ddlCount = new DropDownList();
                ddlCount.ID = "ddlCount";
                ddlCount.Attributes.Add("style", "margin:10px;");
                ddlCount.CssClass = "form-control";

                ddlCount.DataSource    = getRepetations();
                ddlCount.DataTextField = "Count";
                ddlCount.DataBind();

                tcLabel.Controls.Add(lblCount);
                tcValue.Controls.Add(ddlCount);

                tRow.Controls.Add(tcLabel);
                tRow.Controls.Add(tcType);
                tRow.Controls.Add(tcValue);

                tblButtons.Controls.Add(tRow);

                pnlButtons.Visible = true;
            }
            catch (Exception)
            {
                throw;
            }
        }
 void NoMethodsGeneratedWarning() {
     AddWarningComment(codeClass.Comments, Res.GetString(Res.NoMethodsWereFoundInTheWSDLForThisProtocol));
     warnings |= ServiceDescriptionImportWarnings.NoMethodsGenerated;
 }
Пример #9
0
        /// <summary>
        /// 编译程序集
        /// </summary>
        /// <param name="url"></param>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        private static String CompilerAssembly(String url, String serviceName, String assemblyPath)
        {
            // 1. 使用 WebClient 下载 WSDL 信息。
            WebClient web = new WebClient();

            using (Stream stream = web.OpenRead(url + "?WSDL"))
            {
                // 2. 创建和格式化 WSDL 文档。
                ServiceDescription description = ServiceDescription.Read(stream);

                // 3. 创建客户端代理代理类。
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

                importer.ProtocolName          = "Soap";                               // 指定访问协议。
                importer.Style                 = ServiceDescriptionImportStyle.Client; // 生成客户端代理。
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;

                importer.AddServiceDescription(description, null, null); // 添加 WSDL 文档。

                // 4. 使用 CodeDom 编译客户端代理类。
                CodeNamespace   nmspace = new CodeNamespace(serviceName); // 为代理类添加命名空间,缺省为全局空间。
                CodeCompileUnit unit    = new CodeCompileUnit();
                unit.Namespaces.Add(nmspace);

                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
                CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

                // 4.1 根据ESB的需要修正自动生成的代码, 只针对Java进行修正
                if (!url.EndsWith(".asmx"))
                {
                    FixAutoGenCode(nmspace, description);
                }

                CompilerParameters parameter = new CompilerParameters();
                parameter.GenerateExecutable = false;
                parameter.GenerateInMemory   = false;
                parameter.OutputAssembly     = assemblyPath; // 可以指定你所需的任何文件名。
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.ReferencedAssemblies.Add("System.XML.dll");
                parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                parameter.ReferencedAssemblies.Add("System.Data.dll");

                CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);

                // 5. 如果编译出现异常,则直接抛出
                if (result.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new StringBuilder();
                    sb.AppendLine("编译代理程序集出现异常:");

                    foreach (CompilerError ce in result.Errors)
                    {
                        sb.Append(ce.ToString() + System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                // 6. 返回代理类的名词
                Regex regSoap = new Regex("Soap$");
                // 注意:此处要用全名,因为可能存在多个服务共用一个DLL的情况
                String portTypeFullName = serviceName + "." + regSoap.Replace(description.PortTypes[0].Name, "");

                //--记录代理程序集的端口类名,当不需要编译程序集的时候可以直接从AssemblyType.GetInstance(assemblyPath).PortType获取
                AssemblyType.Add(assemblyPath, portTypeFullName);

                return(portTypeFullName);
            }
        }
Пример #10
0
        /// <summary>
        /// 得到WSDL信息,生成本地代理类并编译为DLL
        /// </summary>
        private void CreateServiceAssembly()
        {
            if (this.checkCache())
            {
                this.initTypeName();
                return;
            }
            if (string.IsNullOrEmpty(this._wsdlUrl))
            {
                return;
            }
            try
            {
                //使用WebClient下载WSDL信息
                WebClient                  web         = new WebClient();
                Stream                     stream      = web.OpenRead(this._wsdlUrl);
                ServiceDescription         description = ServiceDescription.Read(stream);  //创建和格式化WSDL文档
                ServiceDescriptionImporter importer    = new ServiceDescriptionImporter(); //创建客户端代理代理类
                importer.ProtocolName          = "Soap";
                importer.Style                 = ServiceDescriptionImportStyle.Client;     //生成客户端代理
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                importer.AddServiceDescription(description, null, null);
                //使用CodeDom编译客户端代理类
                CodeNamespace   nmspace = new CodeNamespace(_assName);  //为代理类添加命名空间
                CodeCompileUnit unit    = new CodeCompileUnit();

                unit.Namespaces.Add(nmspace);
                this.checkForImports(this._wsdlUrl, importer);
                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
                CodeDomProvider    provider  = CodeDomProvider.CreateProvider("CSharp");
                CompilerParameters parameter = new CompilerParameters();
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.ReferencedAssemblies.Add("System.XML.dll");
                parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                parameter.ReferencedAssemblies.Add("System.Data.dll");
                parameter.GenerateExecutable      = false;
                parameter.GenerateInMemory        = false;
                parameter.IncludeDebugInformation = false;
                //1.生成cs
                TextWriter writer = File.CreateText(this._assCsTmp);
                provider.GenerateCodeFromCompileUnit(unit, writer, null);
                writer.Flush();
                writer.Close();
                //2.修改cs中连接的端口
                RefreshPort();
                CompilerResults result = provider.CompileAssemblyFromFile(parameter, this._assCs);
                //如果存在端口隐射的问题,先生成CS,修改cs中的端口 在根据cs生成dll
                provider.Dispose();
                if (result.Errors.HasErrors)
                {
                    string errors = string.Format(@"编译错误:{0}错误!", result.Errors.Count);
                    foreach (CompilerError error in result.Errors)
                    {
                        errors += error.ErrorText;
                    }
                    throw new Exception(errors);
                }
                this.copyTempAssembly(result.PathToAssembly);
                this.initTypeName();
                //删除cs临时文件
                File.Delete(_assCs);
                File.Delete(_assCsTmp);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
Пример #11
0
        /// <summary>
        /// 获取服务端返回的wsdl源代码
        /// </summary>
        /// <param name="swdlAdress"></param>
        /// <param name="?"></param>
        /// <returns></returns>
        public string GetOriginTypeCode(string swdlAdress, out string originTypeName)
        {
            try
            {
                WebClient client = new WebClient();
                string    url    = swdlAdress;
                //读取服务端地址的代码内容
                Stream             stream      = client.OpenRead(url);
                ServiceDescription description = ServiceDescription.Read(stream);
                stream.Close();

                string svcName      = description.Services[0].Name;
                string svcNameSpace = "ChaYeFeng";

                if (description.Services.Count == 0)
                {
                    throw new Exception(string.Format("\"{0}\"没有定义服务", swdlAdress));
                }

                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

                //指定访问协议
                importer.ProtocolName = "Soap";
                //指定生成代码的样式(客户端/服务器)
                importer.Style = ServiceDescriptionImportStyle.Client;
                //设置代码生成的各种选项
                importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.None;
                //添加要导入的wsdl文档
                importer.AddServiceDescription(description, null, null);
                //命名空间
                CodeNamespace nameSpace = new CodeNamespace();
                nameSpace.Name = svcNameSpace;
                //代码的容器
                CodeCompileUnit unit = new CodeCompileUnit();
                unit.Namespaces.Add(nameSpace);
                //以编程的方式调用xml web services提供支持的类
                DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
                //确定url是否为包含有服务说明文档
                dcp.DiscoverAny(url);
                //解析所有发现的文档,xml架构定义和服务说明
                dcp.ResolveAll();
                foreach (object value in dcp.Documents.Values)
                {
                    if (value is ServiceDescription)
                    {
                        importer.AddServiceDescription(value as ServiceDescription, null, null);
                    }
                    if (value is XmlSchema)
                    {
                        importer.Schemas.Add(value as XmlSchema);
                    }
                }

                //导入相应的参数来生成代码
                ServiceDescriptionImportWarnings warning = importer.Import(nameSpace, unit);

                //代码生成器
                CSharpCodeProvider provider = new CSharpCodeProvider();

                //调用编译器的参数
                CompilerParameters parameter = new CompilerParameters
                {
                    //是否生成可执行文件
                    GenerateExecutable = false,
                    //是否在内存中生成输出
                    GenerateInMemory = true
                };
                //添加当前项目引用的程序集
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.ReferencedAssemblies.Add("System.XML.dll");
                parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                parameter.ReferencedAssemblies.Add("System.Data.dll");

                TextWriter stringWriter = new StringWriter();
                //未指定的代码文档对象编译单元生成代码,并使用指定的选项将代码发送到文本编写器
                provider.GenerateCodeFromCompileUnit(unit, stringWriter, null);

                originTypeName = svcName;
                return(stringWriter.ToString());
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Пример #12
0
        /// <summary>
        /// 取得webservice instance
        /// </summary>
        /// <param name="url">url+?wsdl</param>
        /// <param name="assemblyReferences"></param>
        /// <param name="output"></param>
        /// <returns></returns>
        public static bool GetWebServiceInstance(string url, string[] assemblyReferences, out LkReflectModel output, string userName = "", string password = "")
        {
            //http://www.codeproject.com/Articles/18950/Dynamic-Discovery-and-Invocation-of-Web-Services
            //https://dotblogs.com.tw/jimmyyu/archive/2009/04/22/8139.aspx

            output = new LkReflectModel();
            if (assemblyReferences == null)
            {
                assemblyReferences = new string[3] {
                    "System.Web.Services.dll", "System.Xml.dll", "System.Data.dll"
                };
            }
            bool result = false;

            try
            {
                WebRequest webRequest = WebRequest.Create(url);

                //有要權限的話要加下面
                //webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
                if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                {
                    webRequest.Credentials     = new NetworkCredential(userName, password);
                    webRequest.PreAuthenticate = true;
                }
                Stream requestStream = webRequest.GetResponse().GetResponseStream();
                // Get a WSDL file describing a service
                //ServiceDescription类提供一种方法,以创建和格式化用于描述 XML Web services 的有效的 Web 服务描述语言 (WSDL) 文档文件,该文件是完整的,具有适当的命名空间、元素和特性。 无法继承此类。
                //ServiceDescription.Read 方法 (Stream) 通过直接从 Stream实例加载 XML 来初始化ServiceDescription类的实例。
                ServiceDescription sd     = ServiceDescription.Read(requestStream);
                string             sdName = sd.Services[0].Name;

                // Initialize a service description servImport
                //ServiceDescriptionImporter 类 公开一种为 XML Web services 生成客户端代理类的方法。
                //ServiceDescriptionImporter.AddServiceDescription 方法 将指定的ServiceDescription添加到要导入的ServiceDescriptions值的集合中。
                ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
                servImport.AddServiceDescription(sd, String.Empty, String.Empty);
                servImport.ProtocolName          = "Soap";
                servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

                //CodeNamespace表示命名空间声明。
                CodeNamespace nameSpace = new CodeNamespace();
                //CodeCompileUnit会提供一个CodeDOM程式圆形的容器,CodeCompileUnit含有一个集合,可以储存含有CodeDOM原始程式码原形,专案参考的组件集合以及专案组件属性集合的CodeNamespace物件。
                CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                codeCompileUnit.Namespaces.Add(nameSpace);
                // Set Warnings
                ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

                if (warnings == 0)
                {
                    StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                    //CSharpCodeProvider类提供存取C#程式码产生器和程式码编译器的执行个体。
                    Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
                    // 取得C#程式码编译器的执行个体
                    prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

                    // Compile the assembly with the appropriate references
                    // 创建编译器的参数实例
                    CompilerParameters param = new CompilerParameters(assemblyReferences);
                    param.GenerateExecutable    = false;
                    param.GenerateInMemory      = true;
                    param.TreatWarningsAsErrors = false;
                    param.WarningLevel          = 4;

                    // CompilerResults表示从编译器返回的编译结果。使用指定的编译器设定,根据CodeCompileUnit物件之指定阵列所包含的System.CodeDom树状结构,编译一个组件。
                    CompilerResults results = new CompilerResults(new TempFileCollection());
                    // Compile
                    results = prov.CompileAssemblyFromDom(param, codeCompileUnit);

                    if (true == results.Errors.HasErrors)
                    {
                        System.Text.StringBuilder tStr = new System.Text.StringBuilder();
                        foreach (System.CodeDom.Compiler.CompilerError tComError in results.Errors)
                        {
                            tStr.Append(tComError.ToString());
                            tStr.Append(System.Environment.NewLine);
                        }
                        throw new Exception(tStr.ToString());
                    }

                    output.Assembly      = results.CompiledAssembly;
                    output.Class         = output.Assembly.GetType(sdName);
                    output.ClassInstance = Activator.CreateInstance(output.Class);
                    result = true;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return(result);
        }
Пример #13
0
        /* Given a URL, this method extracts the service type and the methods in the service    */
        /* The method and service type objects are returned to enable the caller to call the    */
        /* required service.                                                                    */
        private void GetWebServiceMethods(string url, out MethodInfo[] methodsInfo,
                                          out Type serviceType)
        {
            try
            {
                methodsInfo = null;
                serviceType = null;

                /* Create a new URI Object with the URL provided */
                Uri uri = new Uri(url);

                /* Create a web request to the URI to obtain the WSDL file from the URI */
                WebRequest         webRequest         = WebRequest.Create(uri);
                Stream             wsdlRequestStream  = webRequest.GetResponse().GetResponseStream();
                ServiceDescription serviceDescription = ServiceDescription.Read(wsdlRequestStream);
                Service            service            = serviceDescription.Services[0];

                string serviceDescriptionName = service.Name;

                /* Import service description to create a proxy for the methods present in */
                /* the service. These proxies will later on be used to invoke each of those*/
                /* services.                                                               */
                ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
                servImport.AddServiceDescription(serviceDescription, String.Empty, String.Empty);
                servImport.ProtocolName          = "Soap";
                servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

                /* Create the compile unit and add the required namespaces to it. */
                CodeNamespace   nameSpace       = new CodeNamespace();
                CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                codeCompileUnit.Namespaces.Add(nameSpace);

                /* Obtain the warnings from the compile unit */
                ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

                /* If the warnings obtained are not empty, return */
                if (warnings != 0)
                {
                    return;
                }

                /* Create the string writer object to obtain the the Code DOM for the specified namespace */
                StringWriter       stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                CSharpCodeProvider prov         = new CSharpCodeProvider();
                prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

                /* Set all the required parameters and perform a compilation */
                string[] assemblyReferences = new string[2] {
                    "System.Web.Services.dll", "System.Xml.dll"
                };
                CompilerParameters param = new CompilerParameters(assemblyReferences);
                param.GenerateExecutable    = false;
                param.GenerateInMemory      = true;
                param.TreatWarningsAsErrors = false;
                param.WarningLevel          = 4;

                CompilerResults results  = prov.CompileAssemblyFromDom(param, codeCompileUnit);
                Assembly        assembly = results.CompiledAssembly;

                serviceType = assembly.GetType(serviceDescriptionName);
                methodsInfo = serviceType.GetMethods();
            }
            catch (Exception ec)
            {
                throw new Exception(ec.Message);
            }
        }
Пример #14
0
        /// <summary>
        /// Test the Web Service URL for Validity
        /// </summary>
        /// <param name="webServiceAsmxUrl">web service url</param>
        /// <param name="serviceName">web service name (asmx)</param>
        /// <param name="methodName">web service method</param>
        /// <param name="args">method args</param>
        /// <returns>object</returns>
        public object Testwsurl(string webServiceAsmxUrl, string serviceName, string methodName, object[] args)
        {
            args = new object[] { "Success" };
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(webServiceAsmxUrl);

            webRequest.Timeout   = 300000;
            webRequest.UserAgent = "TerraScan Treasurer";

            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            Encoding     enc            = System.Text.Encoding.GetEncoding(1252);
            StreamReader responseStream = new StreamReader(webResponse.GetResponseStream(), enc);

            string response = responseStream.ReadToEnd();

            responseStream.Close();
            webResponse.Close();

            // MessageBox.Show(Response);
            // return webResponse;

            System.Net.WebClient client = new System.Net.WebClient();

            // --Connect To the web service
            System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");

            // --Now read the WSDL file describing a // service.
            System.Web.Services.Description.ServiceDescription description = ServiceDescription.Read(stream);

            // /// LOAD THE DOM /////////
            // --Initialize a service description importer.
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            importer.ProtocolName = "Soap12"; // Use SOAP 1.2.
            importer.AddServiceDescription(description, null, null);

            // --Generate a proxy client.
            importer.Style = ServiceDescriptionImportStyle.Client;

            // --Generate properties to represent pri // mitive values.
            importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

            // --Initialize a Code-DOM tree into which we will import the service.
            CodeNamespace   nmspace = new CodeNamespace();
            CodeCompileUnit unit1   = new CodeCompileUnit();

            unit1.Namespaces.Add(nmspace);

            // --Import the service into the Code-DOM tree.
            // --This creates proxy code that uses the service.
            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);

            if (warning == 0) // --If zero then we are good to go
            {
                // --Generate the proxy code
                CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");

                // --Compile the assembly proxy with the appropriate references
                string[] assemblyReferences = new string[5] {
                    "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll"
                };
                CompilerParameters parms   = new CompilerParameters(assemblyReferences);
                CompilerResults    results = provider1.CompileAssemblyFromDom(parms, unit1);

                // -Check For Errors
                if (results.Errors.Count > 0)
                {
                    foreach (CompilerError oops in results.Errors)
                    {
                        System.Diagnostics.Debug.WriteLine("========Compiler error============");
                        System.Diagnostics.Debug.WriteLine(oops.ErrorText);
                    }

                    throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window.");
                }

                // --Finally, Invoke the web service method
                object     wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
                MethodInfo mi        = wsvcClass.GetType().GetMethod(methodName);
                return(mi.Invoke(wsvcClass, args));
            }
            else
            {
                return(null);
            }
        }
Пример #15
0
        private void DynamicInvocation()
        {
            try
            {
                messageTextBox.Text += "Generating WSDL \r\n";
                progressBar1.PerformStep();

                Uri uri = new Uri(textBox1.Text);

                messageTextBox.Text += "Generating WSDL \r\n";
                progressBar1.PerformStep();

                WebRequest       webRequest    = WebRequest.Create(uri);
                System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
                // Get a WSDL file describing a service
                ServiceDescription sd     = ServiceDescription.Read(requestStream);
                string             sdName = sd.Services[0].Name;
                // Add in tree view
                treeWsdl.Nodes.Add(sdName);

                messageTextBox.Text += "Generating Proxy \r\n";
                progressBar1.PerformStep();

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

                messageTextBox.Text += "Generating assembly  \r\n";
                progressBar1.PerformStep();

                CodeNamespace   nameSpace       = new CodeNamespace();
                CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                codeCompileUnit.Namespaces.Add(nameSpace);
                // Set Warnings
                ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

                if (warnings == 0)
                {
                    StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                    Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
                    prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

                    messageTextBox.Text += "Compiling assembly \r\n";
                    progressBar1.PerformStep();

                    // Compile the assembly with the appropriate references
                    string[] assemblyReferences = new string[2] {
                        "System.Web.Services.dll", "System.Xml.dll"
                    };
                    CompilerParameters param = new CompilerParameters(assemblyReferences);
                    param.GenerateExecutable    = false;
                    param.GenerateInMemory      = true;
                    param.TreatWarningsAsErrors = false;
                    param.WarningLevel          = 4;

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

                    messageTextBox.Text += "Get Methods of Wsdl \r\n";
                    progressBar1.PerformStep();

                    methodInfo = service.GetMethods();
                    foreach (MethodInfo t in methodInfo)
                    {
                        if (t.Name == "Discover")
                        {
                            break;
                        }


                        treeWsdl.Nodes[0].Nodes.Add(t.Name);
                    }

                    treeWsdl.Nodes[0].Expand();

                    messageTextBox.Text += "Now ready to invoke \r\n ";
                    progressBar1.PerformStep();
                    this.tabControl1.SelectedTab = this.tabPage1;
                }
                else
                {
                    messageTextBox.Text += warnings;
                }
            }
            catch (Exception ex)
            {
                messageTextBox.Text += "\r\n" + ex.Message + "\r\n\r\n" + ex.ToString();;
                progressBar1.Value   = 70;
            }
        }
 /// <include file='doc\ProtocolImporter.uex' path='docs/doc[@for="ProtocolImporter.AddExtensionWarningComments"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public void AddExtensionWarningComments(CodeCommentStatementCollection comments, ServiceDescriptionFormatExtensionCollection extensions) {
     foreach (object item in extensions) {
         if (!extensions.IsHandled(item)) {
             string name = null;
             string ns = null;
             if (item is XmlElement) {
                 XmlElement element = (XmlElement)item;
                 name = element.LocalName;
                 ns = element.NamespaceURI;
             }
             else if (item is ServiceDescriptionFormatExtension) {
                 XmlFormatExtensionAttribute[] attrs = (XmlFormatExtensionAttribute[])item.GetType().GetCustomAttributes(typeof(XmlFormatExtensionAttribute), false);
                 if (attrs.Length > 0) {
                     name = attrs[0].ElementName;
                     ns = attrs[0].Namespace;
                 }
             }
             if (name != null) {
                 if (extensions.IsRequired(item)) {
                     warnings |= ServiceDescriptionImportWarnings.RequiredExtensionsIgnored;
                     AddWarningComment(comments, Res.GetString(Res.WebServiceDescriptionIgnoredRequired, name, ns));
                 }
                 else {
                     warnings |= ServiceDescriptionImportWarnings.OptionalExtensionsIgnored;
                     AddWarningComment(comments, Res.GetString(Res.WebServiceDescriptionIgnoredOptional, name, ns));
                 }
             }
         }
     }
 }
Пример #17
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 = WSHelper.GetWsClassName(url);
            }
            try
            {
                //获取WSDL
                System.Net.WebClient web = new System.Net.WebClient();
                Stream stream            = web.OpenRead(url + "?WSDL");
                //创建和格式化 WSDL 文档
                ServiceDescription description = ServiceDescription.Read(stream);
                //创建客户端代理代理类
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

                importer.ProtocolName          = "Soap";                               // 指定访问协议。
                importer.Style                 = ServiceDescriptionImportStyle.Client; // 生成客户端代理。
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                importer.AddServiceDescription(description, null, null);               // 添加 WSDL 文档

                //使用 CodeDom 编译客户端代理类
                CodeNamespace cn = new CodeNamespace(@namespace);
                //为代理类添加命名空间,缺省为全局空间
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);

                ServiceDescriptionImportWarnings warning = importer.Import(cn, ccu);
                CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

                //importer.Import(cn, ccu);
                //CSharpCodeProvider icc = new CSharpCodeProvider();

                //设定编译参数
                CompilerParameters parameter = new CompilerParameters();
                parameter.GenerateExecutable = false;
                parameter.GenerateInMemory   = true;
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.ReferencedAssemblies.Add("System.XML.dll");
                parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                parameter.ReferencedAssemblies.Add("System.Data.dll");
                //编译代理类
                CompilerResults result = provider.CompileAssemblyFromDom(parameter, ccu);

                if (true == result.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in result.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法
                Assembly assembly = result.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));
                // PropertyInfo propertyInfo = type.GetProperty(propertyname);
                //return propertyInfo.GetValue(obj, null);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
Пример #18
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private bool DoPost()
        {
            //tabControl1_SelectedIndexChanged(null, null);
            string sSSCVoucher = "";

            SunSystems.Connect.Client.SecurityManager oSecMan = new SunSystems.Connect.Client.SecurityManager(SessionInfo.UserInfo.SunUserIP);
            ////http://95.138.187.185:81/SecurityWebServer/Login.aspx?redirect=http://95.138.187.185:8080/ssc/login.jsp
            try
            {
                oSecMan.Login(SessionInfo.UserInfo.SunUserID, SessionInfo.UserInfo.SunUserPass);
                if (oSecMan.Authorised)
                {
                    sSSCVoucher = oSecMan.Voucher;
                    //label1.Content = sSSCVoucher;RSI, RicoSimp2
                }
                else
                {
                    this.textBox1.Text = "Password for user is incorrect.";
                    return(false);
                }
            }
            catch (Exception ex)
            {
                this.textBox1.Text = "An error occurred in validation " + oSecMan.ErrorMessage + ex;
                return(false);
            }
            finally
            {
                oSecMan = null;
            }

            try
            {
                WebClient web    = new WebClient();
                Stream    stream = web.OpenRead("http://" + SessionInfo.UserInfo.SunUserIP + ":8080/connect/wsdl/ComponentExecutor?wsdl");

                // 2. Create and format of WSDL document.
                ServiceDescription description = ServiceDescription.Read(stream);

                // 3. Create a client proxy proxy class.
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

                importer.ProtocolName          = "Soap";                               // The specified access protocol.
                importer.Style                 = ServiceDescriptionImportStyle.Client; // To generate client proxy.
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;

                importer.AddServiceDescription(description, null, null); // Add a WSDL document.

                // 4. Compile the client proxy classes using CodeDom.
                CodeNamespace   nmspace = new CodeNamespace(); // Add a namespace for the proxy class, the default is the global space.
                CodeCompileUnit unit    = new CodeCompileUnit();
                unit.Namespaces.Add(nmspace);

                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
                CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

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

                CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);

                // 5. Using Reflection to call WebService.
                if (!result.Errors.HasErrors)
                {
                    Assembly asm = result.CompiledAssembly;
                    Type     t   = asm.GetType("ComponentExecutor", true, true); // If in front of adding a namespace for the proxy class, here need to be added to the front of the namespace type.

                    object     o      = Activator.CreateInstance(t);
                    MethodInfo method = t.GetMethod("Execute");

                    string sInputPayload;
                    sInputPayload = this.txtXML.Text.Replace("\r\n", "").Replace("\n", "");;

                    object strResu = method.Invoke(o, new object[] { sSSCVoucher, null, "Journal", "Import", null, sInputPayload });
                    //MessageBox.Show(strResu.ToString(), "Message - RSystems FinanceTools", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    this.textBox1.Text = GetErrorLines(strResu.ToString());
                    if (!string.IsNullOrEmpty(this.textBox1.Text.Trim()))
                    {
                        return(false);
                    }
                    else
                    {
                        try
                        {
                            //Save journal number
                            XmlDocument xdoc = new XmlDocument();
                            xdoc.LoadXml(strResu.ToString());
                            //XmlNode node = xdoc.DocumentElement;
                            //XmlNode node = xdoc.SelectSingleNode("Nodes");
                            journalNumber = xdoc.GetElementsByTagName("JournalNumber").Item(1).InnerText;

                            if (!string.IsNullOrEmpty(journalNumber))
                            {
                                SessionInfo.UserInfo.SunJournalNumber = journalNumber;
                                MessageBox.Show("journalNumber:" + journalNumber, "Message - RSystems FinanceTools", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            //present journal number
                        }
                        catch (Exception ex)
                        { throw ex; }
                    }
                    if (strResu != null)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Message - RSystems FinanceTools", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //EventLog.WriteEntry("Finance Tool", ex.Message + "Do Post error", EventLogEntryType.Error);
                LogHelper.WriteLog(typeof(Ribbon1), ex.Message + "Do Post error");
                return(false);
            }
        }
		internal bool Import (ServiceDescriptionImporter descriptionImporter, CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, ArrayList importInfo)
		{
			this.descriptionImporter = descriptionImporter;
			this.classNames = new CodeIdentifiers();;
			this.codeNamespace = codeNamespace;
			this.codeCompileUnit = codeCompileUnit;

			warnings = (ServiceDescriptionImportWarnings) 0;
			
			bool found = false;
			
			ClasifySchemas (importInfo);

			BeginNamespace ();
			
			foreach (ImportInfo info in importInfo)
			{
				foreach (Service service in info.ServiceDescription.Services)
				{
					this.service = service;
					int bindingCount = 0;
					foreach (Port port in service.Ports)
					{
						binding = ServiceDescriptions.GetBinding (port.Binding);
						if (IsBindingSupported ()) bindingCount ++;
					}
					
					foreach (Port port in service.Ports)
					{
						this.iinfo = info;
						this.port = port;
						binding = ServiceDescriptions.GetBinding (port.Binding);
						if (!IsBindingSupported ()) continue;
						
						found = true;
						ImportPortBinding (bindingCount > 1);
					}
				}
			}
			
			if (!found)
			{
				// Looks like MS.NET generates classes for all bindings if
				// no services are present
				
				foreach (ImportInfo info in importInfo)
				{
					this.iinfo = info;
					foreach (Binding b in info.ServiceDescription.Bindings)
					{
						this.binding = b;
						this.service = null;
						this.port = null;
						if (!IsBindingSupported ()) continue;
						found = true;
						ImportPortBinding (true);
					}
				}
			}

			EndNamespace ();
			
			if (!found) warnings = ServiceDescriptionImportWarnings.NoCodeGenerated;
			return true;
		}
 public void UnsupportedOperationWarning(string text)
 {
     AddWarningComment((this.codeClass == null) ? this.codeNamespace.Comments : this.codeClass.Comments, System.Web.Services.Res.GetString("TheOperation0FromNamespace1WasIgnored2", new object[] { this.operation.Name, this.operation.PortType.ServiceDescription.TargetNamespace, text }));
     this.warnings |= ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored;
 }
		void ImportPortBinding (bool multipleBindings)
		{
			if (port != null) {
				if (multipleBindings) className = port.Name;
				else className = service.Name;
			}
			else
				className = binding.Name;
			
			className = classNames.AddUnique (CodeIdentifier.MakeValid (className), port);
			className = className.Replace ("_x0020_", "");	// MS.NET seems to do this
			
			try
			{
				portType = ServiceDescriptions.GetPortType (binding.Type);
				if (portType == null) throw new Exception ("Port type not found: " + binding.Type);

				CodeTypeDeclaration codeClass = BeginClass ();
				codeTypeDeclaration = codeClass;
				AddCodeType (codeClass, port != null ? port.Documentation : null);
				codeClass.Attributes = MemberAttributes.Public;
			
				if (service != null && service.Documentation != null && service.Documentation != "")
					AddComments (codeClass, service.Documentation);

				if (Style == ServiceDescriptionImportStyle.Client) {
					CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Diagnostics.DebuggerStepThroughAttribute");
					AddCustomAttribute (codeClass, att, true);
	
					att = new CodeAttributeDeclaration ("System.ComponentModel.DesignerCategoryAttribute");
					att.Arguments.Add (GetArg ("code"));
					AddCustomAttribute (codeClass, att, true);
				}
				else
					codeClass.TypeAttributes = System.Reflection.TypeAttributes.Abstract | System.Reflection.TypeAttributes.Public;

				if (binding.Operations.Count == 0) {
					warnings |= ServiceDescriptionImportWarnings.NoMethodsGenerated;
					return;
				}
				
				foreach (OperationBinding oper in binding.Operations) 
				{
					operationBinding = oper;
					operation = FindPortOperation ();
					if (operation == null) throw new Exception ("Operation " + operationBinding.Name + " not found in portType " + PortType.Name);

					foreach (OperationMessage omsg in operation.Messages)
					{
						Message msg = ServiceDescriptions.GetMessage (omsg.Message);
						if (msg == null) throw new Exception ("Message not found: " + omsg.Message);
						
						if (omsg is OperationInput)
							inputMessage = msg;
						else
							outputMessage = msg;
					}
					
					CodeMemberMethod method = GenerateMethod ();
					
					if (method != null)
					{
						methodName = method.Name;
						if (operation.Documentation != null && operation.Documentation != "")
							AddComments (method, operation.Documentation);
#if NET_2_0
						if (Style == ServiceDescriptionImportStyle.Client)
							AddAsyncMembers (method.Name, method);
#endif
					}
				}
				
#if NET_2_0
			if (Style == ServiceDescriptionImportStyle.Client)
				AddAsyncTypes ();
#endif
				
				EndClass ();
			}
			catch (InvalidOperationException ex)
			{
				warnings |= ServiceDescriptionImportWarnings.NoCodeGenerated;
				UnsupportedBindingWarning (ex.Message);
			}
		}
        public static Assembly BuildAssembly(Properties props, AssemblyName assemblyName, ref string nameSpace)
        {
            WebClient client = new WebClient();

            if (props.WSDLUri != null)
            {
                CredentialCache cc = new CredentialCache();
                cc.Add(new Uri(props.WSDLUri), props.AuthMode, props.GetCredentials());
                client.Credentials = cc;
            }

            ServiceDescription description;

            using (Stream stream = client.OpenRead(props.WSDLUri))
            {
                description = ServiceDescription.Read(stream);
            }

            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            //importer.ProtocolName = "Soap12";
            importer.AddServiceDescription(description, null, null);
            importer.Style = ServiceDescriptionImportStyle.Client;
            importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

            CleanupSchema(props, client, description, importer);

            CodeNamespace   cns = new CodeNamespace(nameSpace);
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(cns);

            ServiceDescriptionImportWarnings warning = importer.Import(cns, ccu);

            if (warning != ServiceDescriptionImportWarnings.NoCodeGenerated)
            {
                if (props.LogStreams)
                {
                    foreach (CodeMemberMethod cmm in ccu.Namespaces[0].Types.Cast <CodeTypeDeclaration>().SelectMany(t => t.Members.OfType <CodeMemberMethod>()
                                                                                                                     .Where(m => m.CustomAttributes.Cast <CodeAttributeDeclaration>()
                                                                                                                            .Any(c => c.Name.EndsWith("SoapDocumentMethodAttribute")))))
                    {
                        cmm.CustomAttributes.Add(new CodeAttributeDeclaration("SoapLoggerExtensionAttribute"));
                    }
                }

                if (props.FixNETBug)
                {
                    foreach (CodeTypeDeclaration cd in ccu.Namespaces[0].Types.Cast <CodeTypeDeclaration>()
                             .Where(c => c.CustomAttributes.Cast <CodeAttributeDeclaration>().All(cad => cad.AttributeType.BaseType != "System.Xml.Serialization.XmlTypeAttribute") &&
                                    c.CustomAttributes.Cast <CodeAttributeDeclaration>().Any(cad => cad.AttributeType.BaseType != "System.SerializableAttribute")))
                    {
                        cd.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(System.Xml.Serialization.XmlTypeAttribute))));
                    }

                    foreach (CodeAttributeDeclaration cd in ccu.Namespaces[0].Types.Cast <CodeTypeDeclaration>()
                             .SelectMany(c => c.CustomAttributes.Cast <CodeAttributeDeclaration>())
                             .Where(cad => cad.AttributeType.BaseType == "System.Xml.Serialization.XmlTypeAttribute" && String.IsNullOrEmpty((string)cad.Arguments.Cast <CodeAttributeArgument>().Where(arg => arg.Name == "Namespace").Select(arg => ((CodePrimitiveExpression)arg.Value).Value).FirstOrDefault()) &&
                                    (cad.Arguments.Cast <CodeAttributeArgument>().All(arg => arg.Name != "IncludeInSchema") ||
                                     cad.Arguments.Cast <CodeAttributeArgument>().Single(arg => arg.Name == "IncludeInSchema").Value == new CodePrimitiveExpression(true))))
                    {
                        var a = cd.Arguments.Cast <CodeAttributeArgument>().Where(e => e.Name == "Namespace").FirstOrDefault();
                        if (a == null)
                        {
                            cd.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(description.TargetNamespace)));
                        }
                        else
                        {
                            a.Value = new CodePrimitiveExpression(description.TargetNamespace);
                        }
                    }
                }

                if (props.LogStreams)
                {
                    CodeMemberProperty cmmRawXmlResponse = new CodeMemberProperty();
                    cmmRawXmlResponse.Name       = "RawXmlResponse";
                    cmmRawXmlResponse.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                    cmmRawXmlResponse.Type       = new CodeTypeReference(typeof(string));
                    cmmRawXmlResponse.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("SoapLoggerExtension"), "XmlResponse")));
                    ccu.Namespaces[0].Types[0].Members.Add(cmmRawXmlResponse);

                    CodeMemberProperty cmmRawXmlRequest = new CodeMemberProperty();
                    cmmRawXmlRequest.Name       = "RawXmlRequest";
                    cmmRawXmlRequest.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                    cmmRawXmlRequest.Type       = new CodeTypeReference(typeof(string));
                    cmmRawXmlRequest.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("SoapLoggerExtension"), "XmlRequest")));
                    ccu.Namespaces[0].Types[0].Members.Add(cmmRawXmlRequest);
                }

                CodeDomProvider    provider     = CodeDomProvider.CreateProvider("CSharp");
                string[]           assemblyRefs = new string[] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll", Assembly.GetExecutingAssembly().Location };
                CompilerParameters parms        = new CompilerParameters(assemblyRefs);
                parms.GenerateInMemory        = false;
                parms.CompilerOptions         = "/optimize";
                parms.OutputAssembly          = assemblyName.CodeBase;
                parms.IncludeDebugInformation = true;

                StringBuilder sb = new StringBuilder();
                provider.GenerateCodeFromCompileUnit(ccu, new StringWriter(sb), null);

                // Awfull hack to fix a weird bug with .Net proxy generation (???)
                sb = sb.Replace("[][]", "[]");

                CompilerResults cr = provider.CompileAssemblyFromSource(parms, sb.ToString());
                //cr = provider.CompileAssemblyFromDom(parms, ccu);

                if (props.KeepSource)
                {
                    //sb.ToString().Dump();
                }

                if (cr.Errors.Count > 0)
                {
                    throw new Exception("The assembly generation failed: " + String.Join("\r\n", cr.Errors.Cast <CompilerError>().Select(c => c.ErrorText).ToArray()));
                }
                else
                {
                    return(cr.CompiledAssembly);
                }
            }

            return(null);
        }
		public void UnsupportedBindingWarning (string text)
		{
			warnings |= ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored;
			AddGlobalComments ("WARNING: Could not generate proxy for binding " + binding.Name + ". " + text);
		}
Пример #24
0
        /// <summary>
        /// Gerar a estrutura e o grafo da classe
        /// </summary>
        private CodeNamespace GerarGrafo()
        {
            #region Gerar a estrutura da classe do serviço
            //Gerar a estrutura da classe do serviço
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
            importer.AddServiceDescription(this.serviceDescription, string.Empty, string.Empty);

            //Definir o nome do protocolo a ser utilizado
            //Não posso definir, tenho que deixar por conta do WSDL definir, ou pode dar erro em alguns estados
            //importer.ProtocolName = "Soap12";
            if (PadraoNFSe == PadroesNFSe.THEMA)
            {
                importer.ProtocolName = "Soap";
            }

            //Tipos deste serviço devem ser gerados como propriedades e não como simples campos
            importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;
            #endregion

            #region Se a NFSe for padrão DUETO/WEBISS/SALVADOR_BA/PRONIN preciso importar os schemas do WSDL
            switch (PadraoNFSe)
            {
            case PadroesNFSe.SMARAPD:
            case PadroesNFSe.DUETO:
            case PadroesNFSe.WEBISS:
            case PadroesNFSe.SALVADOR_BA:
            case PadroesNFSe.GIF:
            case PadroesNFSe.PRONIN:
                //Tive que utilizar a WebClient para que a OpenRead funcionasse, não foi possível fazer funcionar com a SecureWebClient. Tem que analisar melhor. Wandrey e Renan 10/09/2013
                WebClient client = new WebClient();
                Stream    stream = client.OpenRead(ArquivoWSDL);

                //Esta sim tem que ser com a SecureWebClient pq tem que ter o certificado. Wandrey 10/09/2013
                SecureWebClient client2 = new SecureWebClient(oCertificado);

                // Add any imported files
                foreach (System.Xml.Schema.XmlSchema wsdlSchema in serviceDescription.Types.Schemas)
                {
                    foreach (System.Xml.Schema.XmlSchemaObject externalSchema in wsdlSchema.Includes)
                    {
                        if (externalSchema is System.Xml.Schema.XmlSchemaImport)
                        {
                            Uri baseUri   = new Uri(ArquivoWSDL);
                            Uri schemaUri = new Uri(baseUri, ((System.Xml.Schema.XmlSchemaExternal)externalSchema).SchemaLocation);
                            stream = client2.OpenRead(schemaUri);
                            System.Xml.Schema.XmlSchema schema = System.Xml.Schema.XmlSchema.Read(stream, null);
                            importer.Schemas.Add(schema);
                        }
                    }
                }
                break;
            }
            #endregion

            #region Gerar o o grafo da classe para depois gerar o código
            CodeNamespace   @namespace = new CodeNamespace();
            CodeCompileUnit unit       = new CodeCompileUnit();
            unit.Namespaces.Add(@namespace);
            ServiceDescriptionImportWarnings warmings = importer.Import(@namespace, unit);
            #endregion

            return(@namespace);
        }
		public void UnsupportedOperationWarning (string text)
		{
			warnings |= ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored;
			AddGlobalComments ("WARNING: Could not generate operation " + OperationBinding.Name + ". " + text);
		}
        ///
        /// <summary>
        ///	Generate code for the specified ServiceDescription.
        /// </summary>
        ///
        public bool GenerateCode(ArrayList descriptions, ArrayList schemas)
        {
            // FIXME iterate over each serviceDescription.Services?
            CodeNamespace   codeNamespace = GetCodeNamespace();
            CodeCompileUnit codeUnit      = new CodeCompileUnit();
            bool            hasWarnings   = false;

            codeUnit.Namespaces.Add(codeNamespace);

            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            importer.ProtocolName = protocol;
            if (server)
            {
                importer.Style = ServiceDescriptionImportStyle.Server;
            }

            foreach (ServiceDescription sd in descriptions)
            {
                importer.AddServiceDescription(sd, appSettingURLKey, appSettingBaseURL);
            }

            foreach (XmlSchema sc in schemas)
            {
                importer.Schemas.Add(sc);
            }

            ServiceDescriptionImportWarnings warnings = importer.Import(codeNamespace, codeUnit);

            if (warnings != 0)
            {
                if ((warnings & ServiceDescriptionImportWarnings.NoCodeGenerated) > 0)
                {
                    Console.WriteLine("WARNING: No proxy class was generated");
                }
                if ((warnings & ServiceDescriptionImportWarnings.NoMethodsGenerated) > 0)
                {
                    Console.WriteLine("WARNING: The proxy class generated includes no methods");
                }
                if ((warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) > 0)
                {
                    Console.WriteLine("WARNING: At least one optional extension has been ignored");
                }
                if ((warnings & ServiceDescriptionImportWarnings.RequiredExtensionsIgnored) > 0)
                {
                    Console.WriteLine("WARNING: At least one necessary extension has been ignored");
                }
                if ((warnings & ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored) > 0)
                {
                    Console.WriteLine("WARNING: At least one binding is of an unsupported type and has been ignored");
                }
                if ((warnings & ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored) > 0)
                {
                    Console.WriteLine("WARNING: At least one operation is of an unsupported type and has been ignored");
                }
                hasWarnings = true;
            }

            string fileName    = null;
            bool   hasBindings = false;

            foreach (ServiceDescription desc in descriptions)
            {
                if (fileName == null && desc.Services.Count > 0)
                {
                    fileName = desc.Services[0].Name;
                }

                if (desc.Bindings.Count > 0 || desc.Services.Count > 0)
                {
                    hasBindings = true;
                }
            }

            if (fileName == null)
            {
                fileName = "output";
            }

            if (hasBindings)
            {
                WriteCodeUnit(codeUnit, fileName);
            }

            return(hasWarnings);
        }
Пример #27
0
        //重载Invoke原来四个参数的方法,确保版本兼容性
        //Modifed by karson 2015年11月1日
        //public object Invoke(String urlFull, String className, String methodName, object[] parm)
        //{
        //   return  Invoke(urlFull, className, methodName, parm, null);
        //}

        private object InnerInvoke(String urlFull, String className, String methodName, object[] parm, SoapHeader soapHeader = null)
        {
            object result = null;

            try
            {
                //防止url中未加入?wsdl导致调用出错
                if (!Regex.IsMatch(urlFull, "\\S*?(?i)(wsdl)$"))
                {
                    urlFull += "?wsdl";
                }
                // 1. 使用 WebClient 下载 WSDL 信息。
                WebClient web    = new WebClient();
                Stream    stream = web.OpenRead(urlFull);

                // 2. 创建和格式化 WSDL 文档。
                ServiceDescription description = ServiceDescription.Read(stream);

                // 3. 创建客户端代理代理类。
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
                importer.ProtocolName          = "Soap";                               // 指定访问协议。
                importer.Style                 = ServiceDescriptionImportStyle.Client; // 生成客户端代理。
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                importer.AddServiceDescription(description, null, null);               // 添加 WSDL 文档。

                // 4. 使用 CodeDom 编译客户端代理类。
                CodeNamespace   nmspace = new CodeNamespace(); // 为代理类添加命名空间,缺省为全局空间。
                CodeCompileUnit unit    = new CodeCompileUnit();
                unit.Namespaces.Add(nmspace);

                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
                CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

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

                CompilerResults compiler = provider.CompileAssemblyFromDom(parameter, unit);

                // 5. 使用 Reflection 调用 WebService。
                if (!compiler.Errors.HasErrors)
                {
                    Assembly asm = compiler.CompiledAssembly;
                    Type     t   = asm.GetType(className); // 如果在前面为代理类添加了命名空间,此处需要将命名空间添加到类型前面。

                    object       clientkey    = null;
                    PropertyInfo propertyInfo = null;
                    if (soapHeader != null)
                    {
                        //Soap头开始
                        propertyInfo = t.GetProperty(soapHeader.ClassName + "Value");

                        //获取客户端验证对象
                        Type type = asm.GetType(soapHeader.ClassName);

                        //为验证对象赋值
                        clientkey = Activator.CreateInstance(type);

                        foreach (KeyValuePair <string, object> property in soapHeader.Properties)
                        {
                            type.GetProperty(property.Key).SetValue(clientkey, property.Value, null);
                        }
                    }

                    object instance = Activator.CreateInstance(t);

                    if (clientkey != null)
                    {
                        propertyInfo.SetValue(instance, clientkey, null);
                    }
                    MethodInfo method = t.GetMethod(methodName);

                    result = method.Invoke(instance, parm);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(result);
        }
Пример #28
0
        /*	Function generates an assembly based on a dynamic
         *	request made for a web service.
         *  Input: req - Dynamic request object
         *  Return: location of generated assembly containing proxy
         */
        public string GenerateAssembly(ProxyGenRequest req)
        {
            string strAssemblyLoc = "";


            ServiceDescriptionImporter sdImport = new ServiceDescriptionImporter();
            // Read Service description from WSDL file
            ServiceDescription svcDesc = ServiceDescription.Read(Util.DynProxyUtil.GetHttpStream(req.WsdlUrl));

            // Set Protocol
            sdImport.ProtocolName = req.Protocol;
            sdImport.AddServiceDescription(svcDesc, null, null);
            // Set namespace for generated proxy
            CodeNamespace cnSpace = new CodeNamespace(req.Namespace);
            // Create new code compiled unit
            CodeCompileUnit ccUnit = new CodeCompileUnit();
            ServiceDescriptionImportWarnings sdiWarning = sdImport.Import(cnSpace, ccUnit);
            // Pass CodeCOmpileUnit to a System.CodeDom.CodeProvder
            // e.g. Microsoft.CSharp.CSharpCodeProvider to do the
            // compilation.
            CSharpCodeProvider cdp = new CSharpCodeProvider();
            ICodeGenerator     cg  = cdp.CreateGenerator();
            ICodeCompiler      cc  = cdp.CreateCompiler();

            // Modify proxy as appropriate
            if (m_mutator != null)
            {
                m_mutator.Mutate(ref cnSpace);
            }

            // Construct paths to source code and assembly
            string strFilenameSource = "";

            if (req.ProxyPath.Length > 0)
            {
                strFilenameSource = req.ProxyPath + "\\" + req.ServiceName + ".cs";
            }
            else
            {
                strFilenameSource = req.ServiceName + ".cs";
            }

            string strAssemblyFilename = "";

            if (req.ProxyPath.Length > 0)
            {
                strAssemblyFilename = req.ProxyPath + "\\" + req.ServiceName + ".dll";
            }
            else
            {
                strAssemblyFilename = req.ServiceName + ".dll";
            }

            // Create an output stream associated with assembly
            StreamWriter sw = new StreamWriter(strFilenameSource);

            // Generate the code
            cg.GenerateCodeFromNamespace(cnSpace, sw, null);
            sw.Flush();
            sw.Close();

            CompilerParameters cparams = new CompilerParameters(new String[] { "System.dll", "System.Xml.dll", "System.Web.Services.dll" });

            // Add compiler params from ProxyMytator
            if (m_mutator != null)
            {
                cparams.ReferencedAssemblies.AddRange(m_mutator.CompilerParameters);
            }

            cparams.GenerateExecutable      = false;
            cparams.GenerateInMemory        = false;
            cparams.MainClass               = req.ServiceName;
            cparams.OutputAssembly          = strAssemblyFilename;
            cparams.IncludeDebugInformation = false;

            CompilerResults cr = cc.CompileAssemblyFromFile(cparams, strFilenameSource);

            if (cr.Errors.HasErrors)
            {
                throw new Exception("Compilation failed with errors - see source file: " + strFilenameSource);
            }

            // Set location of proxy assembly
            strAssemblyLoc = strAssemblyFilename;

            return(strAssemblyLoc);
        } // End GenerateAssembly
Пример #29
0
        /// <summary>
        /// 实例化WebServices
        /// </summary>s
        /// <param name="url">WebServices地址</param>
        /// <param name="methodname">调用的方法</param>
        /// <param name="args">把webservices里需要的参数按顺序放到这个object[]里</param>
        public static object InvokeWebService(string url, string methodname, string ns, object[] args)
        {
            //这里的namespace是需引用的webservices的命名空间
            string @namespace = ns;

            try
            {
                //获取WSDL
                WebClient                  wc        = new WebClient();
                Stream                     stream    = wc.OpenRead(url);
                ServiceDescription         sd        = ServiceDescription.Read(stream);
                string                     classname = sd.Services[0].Name;
                ServiceDescriptionImporter sdi       = new ServiceDescriptionImporter();
                sdi.ProtocolName          = "Soap";
                sdi.Style                 = ServiceDescriptionImportStyle.Client;
                sdi.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

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

                //设定编译参数
                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);

                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                return(ex.InnerException.Message);
            }
        }
Пример #30
0
        /// <summary>
        /// 初始化话WebService,生成DLL文件
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private static bool InitWebService()
        {
            try
            {
                //_ProxyClassName = "";
                DicMethodInfo      = new Dictionary <string, MethodInfo>();
                _OutputDLLFileName = System.AppDomain.CurrentDomain.BaseDirectory + "WSDL\\" + _ProxyClassName + ".dll";
                string webServiceUrl = CommonSettings.WebServiceUrl.TrimEnd('/') + "?WSDL";
                if (File.Exists(_OutputDLLFileName))
                {
                    ReflectionBuild();
                    return(true);
                }

                using (WebClient web = new WebClient())
                {
                    Stream stream = web.OpenRead(webServiceUrl);
                    if (stream != null)
                    {
                        //格式化WSDL
                        ServiceDescription description = ServiceDescription.Read(stream);

                        //创建客户端代理类
                        ServiceDescriptionImporter importer = new ServiceDescriptionImporter
                        {
                            ProtocolName          = "Soap",
                            Style                 = ServiceDescriptionImportStyle.Client,
                            CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties | System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync
                        };

                        //添加WSDL 文档
                        importer.AddServiceDescription(description, null, null);

                        //使用CodeDom 编译客户端代理类
                        CodeNamespace   codeNameSpace = new CodeNamespace();
                        CodeCompileUnit unit          = new CodeCompileUnit();
                        unit.Namespaces.Add(codeNameSpace);

                        ServiceDescriptionImportWarnings warning = importer.Import(codeNameSpace, unit);
                        CodeDomProvider    provider  = CodeDomProvider.CreateProvider("CSharp");
                        CompilerParameters parameter = new CompilerParameters
                        {
                            GenerateExecutable = false,
                            OutputAssembly     = _OutputDLLFileName
                        };
                        parameter.ReferencedAssemblies.Add("System.dll");
                        parameter.ReferencedAssemblies.Add("System.XML.dll");
                        parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                        parameter.ReferencedAssemblies.Add("System.Data.dll");

                        //编译输出程序集
                        CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);

                        //使用Reflection 调用WebService
                        if (!result.Errors.HasErrors)
                        {
                            ReflectionBuild();
                            return(true);
                        }
                        else
                        {
                            LogHelper.Error("初始化WebService,反射生成dll文件错误");
                        }
                        stream.Close();
                        stream.Dispose();
                    }
                    else
                    {
                        LogHelper.Error("初始化WebService,打开WebServiceUrl失败");
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("初始化WebService错误", ex);
            }
            return(false);
        }
Пример #31
0
 /// <include file='doc\ProtocolImporter.uex' path='docs/doc[@for="ProtocolImporter.UnsupportedOperationBindingWarning"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public void UnsupportedOperationBindingWarning(string text)
 {
     AddWarningComment(codeClass == null ? codeNamespace.Comments : codeClass.Comments, Res.GetString(Res.TheOperationBinding0FromNamespace1WasIgnored, operationBinding.Name, operationBinding.Binding.ServiceDescription.TargetNamespace, text));
     warnings |= ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored;
 }
Пример #32
0
        public bool CreateProxyForWS(Entitron.Entity.Nexus.WS model)
        {
            Stream stream;

            System.Net.WebClient client = new System.Net.WebClient();

            if (model.WSDL_Url != null && model.WSDL_Url.Length > 0)
            {
                stream = client.OpenRead(model.WSDL_Url);
            }
            else if (model.WSDL_File != null && model.WSDL_File.Length > 0)
            {
                stream = new MemoryStream(model.WSDL_File);
            }
            else
            {
                return(true);
            }

            ServiceDescription description = ServiceDescription.Read(stream);

            // Initialize a service description importer.
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            importer.ProtocolName = "Soap12"; // Use SOAP 1.2.
            importer.AddServiceDescription(description, null, null);
            importer.Style = ServiceDescriptionImportStyle.Client;
            importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

            // Initialize a Code-DOM tree into which we will import the service.
            CodeNamespace   ns   = new CodeNamespace();
            CodeCompileUnit unit = new CodeCompileUnit();

            unit.Namespaces.Add(ns);

            // Import the service into the Code-DOM tree. This creates proxy code that uses the service.
            ServiceDescriptionImportWarnings warning = importer.Import(ns, unit);

            if (warning == 0)
            {
                // Generate the proxy code
                CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

                // Compile the assembly proxy with the appropriate references
                string[] assemblyReferences = new string[5] {
                    "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll"
                };

                // Cesta pro uložení assembly
                string path = System.Reflection.Assembly.GetAssembly(typeof(WS)).Location;
                string dir  = Path.GetDirectoryName(path);

                CompilerParameters parameters = new CompilerParameters(assemblyReferences);
                parameters.GenerateExecutable = false;
                parameters.CompilerOptions    = " /out:C:\\temp\\WSProxy" + model.Id + ".dll";

                CompilerResults results = provider.CompileAssemblyFromDom(parameters, unit);

                if (results.Errors.Count > 0)
                {
                    foreach (CompilerError oops in results.Errors)
                    {
                        System.Diagnostics.Debug.WriteLine("========Compiler error============");
                        System.Diagnostics.Debug.WriteLine(oops.ErrorText);
                    }
                    throw new System.Exception("Compile Error Occured generating webservice proxy. Check Debug ouput window.");
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #33
0
 void NoMethodsGeneratedWarning()
 {
     AddWarningComment(codeClass.Comments, Res.GetString(Res.NoMethodsWereFoundInTheWSDLForThisProtocol));
     warnings |= ServiceDescriptionImportWarnings.NoMethodsGenerated;
 }
 /// <include file='doc\ProtocolImporter.uex' path='docs/doc[@for="ProtocolImporter.UnsupportedOperationBindingWarning"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public void UnsupportedOperationBindingWarning(string text) {
     AddWarningComment(codeClass == null ? codeNamespace.Comments : codeClass.Comments, Res.GetString(Res.TheOperationBinding0FromNamespace1WasIgnored, operationBinding.Name, operationBinding.Binding.ServiceDescription.TargetNamespace, text));
     warnings |= ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored;
 }
Пример #35
0
        private void HandleImportWarnings(ServiceDescriptionImportWarnings warnings)
        {
            // TODO: explicitly handle all of the warnings generated by the ServiceImporter
            if (warnings != 0)
            {
                Trace.TraceError("Warnings: {0}", warnings);

                StringBuilder exceptionMessage = new StringBuilder();

                if ((warnings | ServiceDescriptionImportWarnings.NoCodeGenerated) == warnings)
                {
                    CompilerError error = new CompilerError();
                    error.ErrorText = ErrorMessages.NoCodeGenerated;
                    error.IsWarning = false;
                    error.FileName = m_url;
                    error.ErrorNumber = "CG110";
                    Errors.Add(error);

                    exceptionMessage.AppendLine(error.ToString());
                }
                if ((warnings | ServiceDescriptionImportWarnings.NoMethodsGenerated) == warnings)
                {
                    CompilerError error = new CompilerError();
                    error.ErrorText = ErrorMessages.NoMethodsGenerated;
                    error.IsWarning = false;
                    error.FileName = m_url;
                    error.ErrorNumber = "CG111";
                    Errors.Add(error);

                    exceptionMessage.AppendLine(error.ToString());
                }
                if ((warnings | ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) == warnings)
                {
                    CompilerError error = new CompilerError();
                    error.ErrorText = ErrorMessages.OptionalExtensionsIgnored;
                    error.IsWarning = true;
                    error.FileName = m_url;
                    error.ErrorNumber = "CG112";
                    Errors.Add(error);

                }
                if ((warnings | ServiceDescriptionImportWarnings.RequiredExtensionsIgnored) == warnings)
                {
                    CompilerError error = new CompilerError();
                    error.ErrorText = ErrorMessages.RequiredExtensionsIgnored;
                    error.IsWarning = false;
                    error.FileName = m_url;
                    error.ErrorNumber = "CG113";
                    Errors.Add(error);

                    exceptionMessage.AppendLine(error.ToString());
                }

                if ((warnings | ServiceDescriptionImportWarnings.SchemaValidation) == warnings)
                {
                    CompilerError error = new CompilerError();
                    error.ErrorText = ErrorMessages.SchemaValidation;
                    error.IsWarning = false;
                    error.FileName = m_url;
                    error.ErrorNumber = "CG114";
                    Errors.Add(error);

                    exceptionMessage.AppendLine(error.ToString());

                }
                if ((warnings | ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored) == warnings)
                {
                    CompilerError error = new CompilerError();
                    error.ErrorText = ErrorMessages.UnsupportedBindingsIgnored;
                    error.IsWarning = true;
                    error.FileName = m_url;
                    error.ErrorNumber = "CG115";
                    Errors.Add(error);

                }
                if ((warnings | ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored) == warnings)
                {
                    CompilerError error = new CompilerError();
                    error.ErrorText = ErrorMessages.UnsupportedOperationsIgnored;
                    error.IsWarning = true;
                    error.FileName = m_url;
                    error.ErrorNumber = "CG116";
                    Errors.Add(error);
                }
                if ((warnings | ServiceDescriptionImportWarnings.WsiConformance) == warnings)
                {
                    CompilerError error = new CompilerError();
                    error.ErrorText = ErrorMessages.WsiConformance;
                    error.IsWarning = true;
                    error.FileName = m_url;
                    error.ErrorNumber = "CG117";
                    Errors.Add(error);
                }

                if (exceptionMessage.Length!=0)
                {
                    throw new ApplicationException(string.Format("{0}; Warnings : {1}", exceptionMessage.ToString(), warnings));
                }
                else
                {
                    Trace.TraceWarning("Warnings occurred when generating code for web service {0}", warnings);
                }

            }
        }
Пример #36
0
        private void DynamicInvocation()
        {
            try
            {
                uri = new Uri(Session["Deviceurl"].ToString() + "?wsdl");
            }
            catch { uri = new Uri("http://localhost:60377/Service1.asmx?wsdl"); }
            WebRequest webRequest = WebRequest.Create(uri);

            System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
            // Get a WSDL file describing a service
            ServiceDescription sd     = ServiceDescription.Read(requestStream);
            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);
            // Set Warnings
            ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

            if (warnings == 0)
            {
                StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
                prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

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

                CompilerResults results = new CompilerResults(new TempFileCollection());
                results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
                Assembly assembly = results.CompiledAssembly;
                service               = assembly.GetType(sdName);
                Session["service"]    = service;
                methodInfo            = service.GetMethods();
                Session["methodInfo"] = methodInfo;
                int c = 0;
                foreach (MethodInfo t in methodInfo)
                {
                    if (t.Name == "Discover")
                    {
                        break;
                    }
                    c++;
                }
                listurl = new string[c]; c = 0;
                foreach (MethodInfo t in methodInfo)
                {
                    if (t.Name == "Discover")
                    {
                        break;
                    }
                    listurl[c++] = t.Name;
                }

                Session["listurl"] = listurl;
            }
        }
Пример #37
0
        /// <summary>
        /// 接口初始化
        /// </summary>
        /// <param name="url">接口地址(不含?wsdl)</param>
        /// <param name="error_info">错误信息</param>
        /// <returns>是否成功</returns>
        public bool InitWebService(string url, out string error_info)
        {
            error_info = "";

            #region 校验输入接口地址
            if (url.EndsWith("?wsdl") || url.EndsWith("?WSDL"))
            {
                url = url.Substring(0, url.LastIndexOf("?"));
            }
            if (url.EndsWith(".asmx") == false)
            {
                error_info = "接口地址不对,请检查后重试!";
                return(false);
            }
            #endregion

            #region  除启动目录已存在的dll文件
            if (File.Exists(dllpath) == true)
            {
                try
                {
                    File.Delete(dllpath);
                }
                catch
                {
                    error_info = "删除之前的代理类文件失败,请手动删除后重试!";
                    return(false);
                }
            }
            #endregion

            #region 生成接口代理类的dll文件
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
            try
            {
                //获取服务描述语言(WSDL)
                WebClient wc     = new WebClient();
                Stream    stream = wc.OpenRead(url + "?WSDL");

                //创建及格式化wsdl文档
                ServiceDescription description = ServiceDescription.Read(stream);

                //注意classname一定要赋值获取
                string classname = description.Services[0].Name;

                //创建客户端代理类
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
                importer.ProtocolName          = "Soap";
                importer.Style                 = ServiceDescriptionImportStyle.Client;
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;

                //添加wsdl文档
                importer.AddServiceDescription(description, "", "");

                //为代理类添加命名空间,缺省为全局空间
                CodeNamespace nmspace = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit unit = new CodeCompileUnit();
                unit.Namespaces.Add(nmspace);
                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);

                //设定编译器的参数
                CSharpCodeProvider provider  = new CSharpCodeProvider();
                CompilerParameters parameter = new CompilerParameters();
                parameter.GenerateExecutable = false;
                parameter.OutputAssembly     = "interface_yzx.dll";
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.ReferencedAssemblies.Add("System.XML.dll");
                parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                parameter.ReferencedAssemblies.Add("System.Data.dll");

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

                //初始化代理客户端
                Assembly asm = Assembly.LoadFrom("interface_yzx.dll");
                interface_type = asm.GetType("EnterpriseServerBase.WebService.DynamicWebCalling." + classname, true, true);
                interface_obj  = Activator.CreateInstance(interface_type);
                return(true);
            }
            catch (Exception ex)
            {
                error_info = ex.Message.ToString();
                return(false);
            }
            #endregion
        }
Пример #38
0
    static void Run()
    {
        // Get a WSDL file describing a service.
        ServiceDescription description = ServiceDescription.Read("DataTypes_CS.wsdl");

        // Initialize a service description importer.
        ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

        importer.ProtocolName = "Soap12"; // Use SOAP 1.2.
        importer.AddServiceDescription(description, null, null);

        // Report on the service descriptions.
        Console.WriteLine("Importing {0} service descriptions with {1} associated schemas.",
                          importer.ServiceDescriptions.Count, importer.Schemas.Count);

        // Generate a proxy client.
        importer.Style = ServiceDescriptionImportStyle.Client;

        // Generate properties to represent primitive values.
        importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

        // Initialize a Code-DOM tree into which we will import the service.
        CodeNamespace   nmspace = new CodeNamespace();
        CodeCompileUnit unit1   = new CodeCompileUnit();

        unit1.Namespaces.Add(nmspace);

        // Import the service into the Code-DOM tree. This creates proxy code
        // that uses the service.
        ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);

        if (warning == 0)
        {
            // Generate and print the proxy code in C#.
            CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
            provider1.GenerateCodeFromCompileUnit(unit1, Console.Out, new CodeGeneratorOptions());
        }
        else
        {
            // Print an error message.
            Console.WriteLine("Warning: " + warning);
        }

        string url = "AddNumbers.wsdl";

// <snippet1>
        // Read in a WSDL service description.
        XmlTextReader      reader = new XmlTextReader(url);
        ServiceDescription wsdl   = ServiceDescription.Read(reader);
// </snippet1>

// <snippet2>
        // Create a WSDL collection.
        DiscoveryClientDocumentCollection wsdlCollection = new DiscoveryClientDocumentCollection();

        wsdlCollection.Add(url, wsdl);
// </snippet2>

// <snippet3>
        // Create a namespace and a unit for compilation.
        CodeNamespace   space = new CodeNamespace();
        CodeCompileUnit unit  = new CodeCompileUnit();

        unit.Namespaces.Add(space);
// </snippet3>

// <snippet4>
        // Create a web referernce using the WSDL collection.
        WebReference reference = new WebReference(wsdlCollection, space);

        reference.ProtocolName = "Soap12";
// </snippet4>

// <snippet5>
        // Print some information about the web reference.
        Console.WriteLine("Base Url = {0}", reference.AppSettingBaseUrl);
        Console.WriteLine("Url Key = {0}", reference.AppSettingUrlKey);
        Console.WriteLine("Documents = {0}", reference.Documents.Count);
// </snippet5>

// <snippet6>
        // Create a web reference collection.
        WebReferenceCollection references = new WebReferenceCollection();

        references.Add(reference);
// </snippet6>

// <snippet7>
        // Compile a proxy client and print out the code.
        CodeDomProvider     provider = CodeDomProvider.CreateProvider("CSharp");
        WebReferenceOptions options  = new WebReferenceOptions();

        options.Style = ServiceDescriptionImportStyle.Client;
        options.CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync;
        ServiceDescriptionImporter.GenerateWebReferences(
            references,
            provider,
            unit,
            options
            );
        provider.GenerateCodeFromCompileUnit(unit, Console.Out, new CodeGeneratorOptions());
// </snippet7>
    }
Пример #39
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = null;
        GridView1.DataBind();
        lblJKguid.Text    = "";
        lblerrmsg.Text    = "";
        lblerrmsg.Visible = false;
        TextBox3.Text     = "";
        TextBox4.Text     = "";
        TextBox5.Text     = "";
        if (TextBox1.Text.Trim() == "" || TextBox2.Text.Trim() == "" || TextBox1.Text.Trim() == "请选择" || TextBox2.Text.Trim() == "请选择")
        {
            //Response.Write("接口地址及接口域名不能为空!");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "<script language='javascript' defer>alert('接口地址及接口域名不能为空!');</script>");
            return;
        }
        try
        {
            //检查接口情况
            string             mubiao_url = "http://" + TextBox1.Text + "/" + TextBox2.Text + "?wsdl";
            XmlTextReader      reader     = new XmlTextReader(mubiao_url);
            ServiceDescription service    = ServiceDescription.Read(reader);
            string             JKzhushi   = service.Documentation;    //接口注释
            string             JKleiming  = service.Services[0].Name; //接口类名。咱要求和文件名一致,所以这里用不上


            //准备获得方法的具体参数返回值等等详细资料
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); //创建客户端代理代理类
            importer.ProtocolName          = "Soap";
            importer.Style                 = ServiceDescriptionImportStyle.Client;  //生成客户端代理
            importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
            importer.AddServiceDescription(service, null, null);                    //添加WSDL文档
            //使用CodeDom编译客户端代理类
            CodeNamespace   nmspace = new CodeNamespace("临时名空间");                   //为代理类添加命名空间
            CodeCompileUnit unit    = new CodeCompileUnit();
            unit.Namespaces.Add(nmspace);


            DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
            dcp.DiscoverAny(mubiao_url);
            dcp.ResolveAll();
            foreach (object osd in dcp.Documents.Values)
            {
                if (osd is ServiceDescription)
                {
                    importer.AddServiceDescription((ServiceDescription)osd, null, null);
                }
                ;
                if (osd is XmlSchema)
                {
                    importer.Schemas.Add((XmlSchema)osd);
                }
            }


            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
            CodeDomProvider    provider  = CodeDomProvider.CreateProvider("CSharp");
            CompilerParameters parameter = new CompilerParameters();
            parameter.ReferencedAssemblies.Add("System.dll");
            parameter.ReferencedAssemblies.Add("System.XML.dll");
            parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
            parameter.ReferencedAssemblies.Add("System.Data.dll");
            parameter.GenerateExecutable      = false;
            parameter.GenerateInMemory        = false;
            parameter.IncludeDebugInformation = false;
            CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);
            provider.Dispose();

            Assembly serviceAsm  = result.CompiledAssembly;
            Type[]   types       = serviceAsm.GetTypes();
            string   objTypeName = "";
            foreach (Type t in types)
            {
                if (t.BaseType == typeof(SoapHttpClientProtocol))
                {
                    objTypeName = t.Name;
                    break;
                }
            }


            //判断接口是否在数据库中存在
            Hashtable inputHT = new Hashtable();
            DataSet   dsre    = new DataSet(); //用于接口查询返回数据集
            DataSet   dsreM   = new DataSet(); //用于接口中的方法查询返回数据集
            inputHT["@jkym"] = TextBox1.Text.Trim();
            inputHT["@jkdz"] = TextBox2.Text.Trim();
            string    sql       = "select * from AAA_ipcJK where JK_host=@jkym and JK_path=@jkdz";
            I_Dblink  I_DBL     = (new DBFactory()).DbLinkSqlMain("");
            Hashtable return_ht = I_DBL.RunParam_SQL(sql, "接口信息", inputHT);
            if ((bool)(return_ht["return_float"])) //执行完成
            {
                dsre = (DataSet)return_ht["return_ds"];
                if (dsre != null && dsre.Tables[0].Rows.Count > 0)
                {//存在对应数据
                    lblJKguid.Text         = dsre.Tables[0].Rows[0]["JK_guid"].ToString();
                    TextBox3.Text          = dsre.Tables[0].Rows[0]["JK_shuoming"].ToString();
                    TextBox4.Text          = dsre.Tables[0].Rows[0]["JK_banben"].ToString();
                    ListBox1.SelectedValue = dsre.Tables[0].Rows[0]["JK_open"].ToString();
                    TextBox5.Text          = dsre.Tables[0].Rows[0]["JK_port"].ToString();

                    //接口和方法同时添加的按钮不可用
                    Button2.Enabled = false;
                    Button2.ToolTip = "该接口已经添加,仅可添加新方法";
                    btnAddM.Enabled = true;
                    btnAddM.ToolTip = "";
                }
                else
                {//接口还没有添加过
                    Button2.Enabled = true;
                    Button2.ToolTip = "";
                    btnAddM.Enabled = false;
                    btnAddM.ToolTip = "";

                    //版本号,符合注释规则才行。
                    if (JKzhushi.IndexOf("-&gt;") >= 0)
                    {
                        TextBox3.Text = JKzhushi.Replace("-&gt;", "*").Split('*')[1];
                        TextBox4.Text = JKzhushi.Replace("-&gt;", "*").Split('*')[0];
                    }
                }
            }
            else
            {
                btnAddM.Enabled = false;
                btnAddM.ToolTip = "";
                Button2.Enabled = false;
                Button2.ToolTip = "";
                //读取数据库出错。。。
                Response.Write("接口查询出错。" + return_ht["return_errmsg"].ToString());
                return;
            }

            //如果接口已经添加过,获取此接口中已经添加过的方法
            if (lblJKguid.Text != "")
            {
                Hashtable inputM = new Hashtable();
                inputM["@jkguid"] = dsre.Tables[0].Rows[0]["JK_guid"].ToString();
                string    sqlM       = "select * from AAA_ipcFF where FF_JK_guid=@jkguid";
                Hashtable return_htM = I_DBL.RunParam_SQL(sqlM, "方法列表", inputM);

                if ((bool)(return_htM["return_float"]))
                {
                    dsreM = (DataSet)return_htM["return_ds"];
                }
                else
                {
                    //读取数据库出错。。。
                    Response.Write("接口中的方法查询出错。" + return_ht["return_errmsg"].ToString());
                    return;
                }
            }
            else
            {
                dsreM = null;
            }

            DataTable DTfangfa = new DataTable();
            DTfangfa.Columns.Add("业务名称");
            DTfangfa.Columns.Add("方法名");
            DTfangfa.Columns.Add("返回值类型");
            DTfangfa.Columns.Add("参数类型");
            DTfangfa.Columns.Add("方法注释");
            DTfangfa.Columns.Add("方法是否有效");
            DTfangfa.Columns.Add("操作特点");

            //获取接口中的所有方法
            foreach (Operation ort in service.PortTypes[0].Operations)
            {
                string FF_name          = ort.Name;          //方法名
                string FF_shuoming      = ort.Documentation; //方法注释
                string FF_yewumingcheng = ort.Messages.Input.Name;

                MethodInfo      mi        = serviceAsm.GetType("临时名空间." + objTypeName).GetMethod(FF_name);
                string          FF_rename = mi.ReturnParameter.ParameterType.Name;
                ParameterInfo[] pi        = mi.GetParameters();
                string          FF_cs     = "";
                for (int i = 0; i < pi.Length; i++)
                {
                    FF_cs = FF_cs + mi.GetParameters()[i].ParameterType.Name + "{" + mi.GetParameters()[i].Name + "}" + "★";
                }


                if (dsreM != null)
                {
                    DataRow[] dr = dsreM.Tables[0].Select("FF_name='" + FF_name + "'");
                    if (dr.Length <= 0)
                    {
                        if (FF_name != "onlinetest")//这个方法不用添加,
                        {
                            DTfangfa.Rows.Add(new string[] { FF_yewumingcheng, FF_name, FF_rename, FF_cs, FF_shuoming, "", "" });
                        }
                    }
                }
                else
                {
                    if (FF_name != "onlinetest")
                    {
                        DTfangfa.Rows.Add(new string[] { FF_yewumingcheng, FF_name, FF_rename, FF_cs, FF_shuoming, "", "" });
                    }
                }
            }
            if (DTfangfa.Rows.Count <= 0)
            {
                lblFF.Text    = "此接口中未找到没有添加过的方法";
                lblFF.Visible = true;
            }
            else
            {
                GridView1.DataSource = DTfangfa.DefaultView;
                GridView1.DataBind();
                lblFF.Text    = "";
                lblFF.Visible = false;
            }
        }
        catch (Exception ex)
        {
            //this.ClientScript.RegisterStartupScript(this.GetType(), "message", "<script language='javascript' defer>alert('"+ex.ToString ()+"');</script>");
            lblerrmsg.Text    = ex.ToString();
            lblerrmsg.Visible = true;
            //Response.Write(ex.ToString());
        }
    }
Пример #40
0
        public bool Compile()
        {
            Errors.Clear();

            if (!DownloadWsdl())
            {
                return(false);
            }

            try
            {
                #region import the service description

                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
                // add downloaded schemas here

                // add the service description (s)
                importer.AddServiceDescription(m_descriptions[0], null, null);

                // add the imported schemas
                importer.Schemas.Add(m_schemas);

                // Generate a proxy client.
                importer.Style = m_style;

                // protocol defaults to SOAP

                // Generate properties to represent primitive values.
                importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

                CreateCodeNamespace();

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

                // Import the service into the Code-DOM tree. This creates proxy code that uses the service.
                ServiceDescriptionImportWarnings warnings = importer.Import(CodeNamespace, codeCompileUnit);

                // Handle all import warnings
                HandleImportWarnings(warnings);

                #endregion

                if (!GenerateCode())
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Errors.Add(new CompilerError(string.Empty, 0, 0, string.Empty, ex.Message));
                Trace.TraceError(ex.ToString());
                if (this.ThrowExceptions)
                {
                    throw;
                }
                return(false);
            }

            return(true);
        }
 private void NoMethodsGeneratedWarning()
 {
     AddWarningComment(this.codeClass.Comments, System.Web.Services.Res.GetString("NoMethodsWereFoundInTheWSDLForThisProtocol"));
     this.warnings |= ServiceDescriptionImportWarnings.NoMethodsGenerated;
 }