動態調用WebServices

--Services--
Web.Config
<connectionStrings>
  <add name="SqlServer" connectionString ="Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=" providerName="System.Data.SqlClient"/>
 </connectionStrings>

C#:
DB-

public class ConnSQLDB
    {
     public ConnSQLDB()
     {
      //
      // TODO: 在此加入建構函式的程式碼
      //
     }

        string _connstring=ConfigurationManager.ConnectionStrings["AMASqlServer"].ToString();

        public SqlConnection GetSQLConnect()
        {
            try
            {
                SqlConnection scon = new SqlConnection(_connstring);
                scon.Open();
                return scon;
            }
            catch
            {
                throw new Exception( "連接數據庫失敗,請查看數據連接!");
            }
        }

        public SqlCommand GetCommand(string strCmd)
        {
           
            SqlCommand scmd = new SqlCommand();
            scmd.Connection = GetSQLConnect();
            try
            {   
                scmd.CommandText = strCmd;
                scmd.CommandType = CommandType.Text;
                return scmd;
            }
            catch
            {
                throw new Exception( "當前SQL語句執行失敗,請查看執行的SQL語句!");
            }
        }

        public DataSet GetDataSet(string strcmd)
        {
            SqlCommand cmd = GetCommand(strcmd);
            SqlDataAdapter sda = new SqlDataAdapter();
            sda.SelectCommand = cmd;
            DataSet ds = new DataSet();   
            try
            {   
                sda.Fill(ds);
                return ds;
            }
            catch
            {
               throw new Exception("打開數據集失敗,請查看打開的狀況!");
            }
        }
    }

BLL-

 public class BLL
    {
        public BLL()
        {
            //
            // TODO: 在此加入建構函式的程式碼
            //
        }

        private ConnSQLDB SqlDB =new ConnSQLDB();

        public string ApproveUser(string UserName)
        {
            string strCmd = "";
            int rows;

           try
            {
                strCmd = "Select t1.IsApproved from ASPNET_memberShip t1 left join ASPNET_Users t2 on t1.Userid=t2.Userid where t2.UserName='" + UserName + "'";
                DataSet ds = SqlDB.GetDataSet(strCmd);
                rows = ds.Tables[0].Rows.Count;
                ds = null;
                if (rows > 0)
                {
                    return UserName.ToString() + "用戶已經驗證過,不能重復作業!";
                }
                else
                {
                    strCmd = "Update t1 set t1.IsApproved=1 from ASPNET_memberShip t1 left join ASPNET_Users t2 on t1.Userid=t2.Userid where t2.UserName='" + UserName + "'";
                    SqlCommand scmd = SqlDB.GetCommand(strCmd);
                    rows = scmd.ExecuteNonQuery();
                    if (rows > 0)
                    {
                        return UserName.ToString() + "用戶驗證完畢成功!";
                    }
                    else
                    {
                        return UserName.ToString() + "用戶不存在,不能進行驗證作業!";
                    }
                }

            }
            catch(Exception e)
            {
                return e.Message;
            }
        }
    }

Asmx-
[WebMethod]
    public string ApproveUser(string UserName)
    {
        return Approve.ApproveUser(UserName);
    }


--頁面調用--
Web.config
<appSettings>
  <add key="Services" value="http://localhost/UserApprove.asmx"/>
 </appSettings>

C#:
Dim ii As String = InvokeWebservice(System.Configuration.ConfigurationManager.AppSettings("Services").ToString, "", "UserApprove", "ApproveUser", New Object() {TextBox1.Text})
        Response.Write("<script>alert('" + ii + "')</script>")



Public Shared Function InvokeWebservice(ByVal url As String, ByVal [namespace] As String, ByVal classname As String, ByVal methodname As String, ByVal args As Object()) As Object


        Try


            Dim wc As New System.Net.WebClient()

            Dim stream As System.IO.Stream = wc.OpenRead(url + "?WSDL")


            Dim sd As System.Web.Services.Description.ServiceDescription = System.Web.Services.Description.ServiceDescription.Read(stream)


            Dim sdi As New System.Web.Services.Description.ServiceDescriptionImporter()

            sdi.AddServiceDescription(sd, "", "")

            Dim cn As New System.CodeDom.CodeNamespace([namespace])

            Dim ccu As New System.CodeDom.CodeCompileUnit()

            ccu.Namespaces.Add(cn)

            sdi.Import(cn, ccu)

 

            Dim csc As New Microsoft.CSharp.CSharpCodeProvider()

            Dim icc As System.CodeDom.Compiler.ICodeCompiler = csc.CreateCompiler()

 


            Dim cplist As New System.CodeDom.Compiler.CompilerParameters()

            cplist.GenerateExecutable = False

            cplist.GenerateInMemory = True

            cplist.ReferencedAssemblies.Add("System.dll")

            cplist.ReferencedAssemblies.Add("System.XML.dll")

            cplist.ReferencedAssemblies.Add("System.Web.Services.dll")

            cplist.ReferencedAssemblies.Add("System.Data.dll")

 

            Dim cr As System.CodeDom.Compiler.CompilerResults = icc.CompileAssemblyFromDom(cplist, ccu)

            If True = cr.Errors.HasErrors Then


                Dim sb As New System.Text.StringBuilder()

                For Each ce As System.CodeDom.Compiler.CompilerError In cr.Errors


                    sb.Append(ce.ToString())


                    sb.Append(System.Environment.NewLine)
                Next


                Throw New Exception(sb.ToString())
            End If

            Dim assembly As System.Reflection.Assembly = cr.CompiledAssembly

            Dim t As Type = assembly.[GetType]([namespace] + "." + classname, True, True)

            Dim obj As Object = Activator.CreateInstance(t)

            Dim mi As System.Reflection.MethodInfo = t.GetMethod(methodname)


            Return mi.Invoke(obj, args)
        Catch ex As Exception
            Throw New Exception(ex.InnerException.Message, New Exception(ex.InnerException.StackTrace))
        End Try

    End Function

posted @ 2008-02-01 16:58  马建康  阅读(276)  评论(0)    收藏  举报