后绑定webservice, 下帖引用自他人

严重感谢   :   JollyFred   (蝈蝈)    
  他发的贴子帮我解决了问题!!一下的内容基本上是   JollyFred   (蝈蝈)   的思想,本人仅加上了注释,方便类似于我这种菜鸟的阅读。同时加入了在配置文件中自动提取配置信息以自动连接web引用的一个小技巧,总不算全偷   :)    
  说明:要运行此程序,必须先有配置文件(如果是web程序。配置文件就是Web.config;如果是windows程序就是app.config)至于如何把这两个文件加入工程中请自行搜索“配置文件”。  
  打开配置文件,在紧挨这</configuration>的上方添加如下代码:  
    <appSettings>  
  <add   key="WSDL"   value="提供web服务说明的网址,例如:http://localhost/DynamicWebService2/WSReturnString.asmx?wsdl"   />  
    </appSettings>  
   
  然后在你的工程主类中添加如下方法:  
  private   void   getSoapService(string   WSDL)       //   vinent     050715     成功了!!!   //并且不需要安装SOAP   ToolKit   3.0   !!!  
  {  
  //1)用XML阅读器从一个文件路径或者是网络路径中读入WSDL文件:  
  XmlTextReader   reader   =   new   XmlTextReader(System.Configuration.ConfigurationSettings.AppSettings[WSDL]);//加入   using   System.Xml;  
  //2〉把读到的内容用ServiceDescription来描述:  
  ServiceDescription   sd   =   ServiceDescription.Read(reader);   //   加入   using   System.Web.Services.Description;  
  //3)用服务导入器把得到的描述导入服务描述中:  
  ServiceDescriptionImporter   sdi   =   new   ServiceDescriptionImporter();  
  sdi.AddServiceDescription(sd,   null,   null);  
  //4)指定要动态编译的代码的命名空间:  
  CodeNamespace   cn   =   new   CodeNamespace("DynamicServices");  
  //5)指定要动态编译的代码单元:  
  CodeCompileUnit   ccu   =   new   CodeCompileUnit();  
  //6)把命名空间添加到动态编译的代码单元的命名空间组中去:  
  ccu.Namespaces.Add(cn);  
  //7)指示服务导入器把该动态编译单元内该命名空间的代码导进去,作为新的动态服务描述:  
  sdi.Import(cn,   ccu);  
  //8)新建一个   C#编译器来编译:  
  ICodeCompiler   icc   =   new   Microsoft.CSharp.CSharpCodeProvider().CreateCompiler();   //CSharpCodeProvider().CreateCompiler();  
  //9)新建一个编译参数对象(在这里我们设置它为空的编译参数):  
  CompilerParameters   cp=new   CompilerParameters();                           //   add   by   GUOGUO  
  //10)指示C#编译器,按照   CP   编译参数对象提供的参数来进行   CCU   单元的编译。并把编译结果传给     编译结果对象     cr:  
  CompilerResults   cr   =   icc.CompileAssemblyFromDom(cp,   ccu);  
  //11)从动态编译结果中获取   某个   字符串(通常是该类型名字)所表示的真实类   :  
  Type   t   =   cr.CompiledAssembly.GetType("DynamicServices.WSReturnString");   //   其中的DynamicServices必须和CodeNamespace   cn   =   new   CodeNamespace("DynamicServices");定义的同名       //Type   t   =   cr.CompiledAssembly.GetType("CodeDom.Service1");   //something   wrong   here  
  //12)创建该类的实例:  
  Object   obj   =   Activator.CreateInstance(t);          
  //13)根据方法名称字符串   反射到该方法的实体:  
  System.Reflection.MethodInfo     mi   =   obj.GetType().GetMethod("要调用的方法名称"); //MethodInfo   mi   =   obj.GetType().GetMethod("Add");  
  //14)用该方法实体的.Invoke()来调用该方法:  
  Label1.Text   =   System.Convert.ToString(mi.Invoke(obj,new   object[]{"传给方法的参数1","传给方法的参数2"}))   ;   //,new   object[]{1,2}))   ;     //Console.WriteLine(System.Convert.ToString(mi.Invoke(obj,   new   object[]{1,2})));  
  }  
  调用这个方法,只要写语句:     getSoapService("WSDL");   就可以了。赶快试试吧。   :)  
  另:谁能告诉我怎么散分,顶者有份?  
   
  再次声明:本文绝大部分参照JollyFred   (蝈蝈)   的原文。严重感谢JollyFred   (蝈蝈)   同志。

posted on 2009-02-15 14:21  zz  阅读(228)  评论(0编辑  收藏  举报

导航