無廢話WCF入門教程六[一個簡單的Demo]

1、前言

    前面的幾個章節介紹了不少理論基礎,如:什麼是WCF、WCF中的A、B、C。WCF的傳輸模式。本文從零開始和你們一塊兒寫一個小的WCF應用程序Demo。html

    大多框架的學習都是從增、刪、改、查開始來學習的,咱們學習WCF也是同樣的。從簡單來看(不包括安全、優化等相關問題),WCF的增刪改查和WebForm相差無幾。WCF只是把具體「實現」寫在「Service端」,而「調用」放在了「Client端」。以爲有幫助別忘了點個贊哈,謝謝哦~sql

2、Demo說明

1)Demo的 「Service端」以本機IIS爲宿主,「Client端」以WebForm項目爲例。數據庫

2)Demo的「Service端」提取數據採用初學者比較容易接受的分層結構進行搭建,分別分爲服務層、實體層、數據層。安全

引用關係以下圖所示:app

3)Demo以數據庫爲SqlServer,表User爲例(sql語句在下載的壓縮包中Init.sql),表結構以下所示:框架

字段名工具

列名學習

數據類型開發工具

約束測試

生成方式

用戶編號

UserID

int

主鍵,必須輸入

自動增+1

姓名

Name

varchar(200)

非必須輸入

人工輸入

密碼

Password

varchar(200)

非必須輸入

人工輸入

描述

Discribe

varchar(800)

非必須輸入

人工輸入

提交時間

SubmitTime

datetime

非必須輸入

人工輸入

3、建立Service端宿主

1)建立WCF應用程序命名爲:WCF.Demo.Service,以下圖:

2)刪除默認文件IService.csService.svc。並分別建立增、刪、改、查」Add.svc」「Save.svc」「Remove.svc」「Get.svc,Search.svc」,分別對應4個功能的服務應用程序WCF服務應用程序,並建立數據操做層和數據實體層,以下圖:

3)增長實體層和數據操做層代碼,以下所示:

 1     //用戶實體
 2     [DataContract]
 3     public class User
 4     {
 5         [DataMember]
 6         public int UserID { get; set; }
 7         [DataMember]
 8         public string UserName { get; set; }
 9         [DataMember]
10         public string Password { get; set; }
11         [DataMember]
12         public string Discribe { get; set; }
13         [DataMember]
14         public DateTime SubmitTime { get; set; }
15     }
16     //數據操做,調用SqlHeler
17     public class User
18     {
19         private static readonly string connectionString = "server=.;database=wcfDemo;uid=sa;pwd=123456;";
20 
21         //添加
22         public static bool Add(Model.User user)
23         {
24             string sql = string.Format("INSERT INTO [dbo].[User]([UserName],[Password],[Discribe],[SubmitTime]) VALUES('{0}','{1}','{2}','{3}')", user.UserName, user.Password, user.Discribe, user.SubmitTime);
25             int result = SqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, sql);
26             if (result > 0)
27                 return true;
28             else
29                 return false;
30         }
31 
32         //修改
33         public static bool Save(Model.User user)
34         {
35             string sql = string.Format("UPDATE [dbo].[User] SET [UserName] = '{0}',[Discribe] = '{2}',[SubmitTime] = '{3}' WHERE UserID = {4}", user.UserName, user.Password, user.Discribe, user.SubmitTime, user.UserID);
36             int result = SqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, sql);
37             if (result > 0)
38                 return true;
39             else
40                 return false;
41         }
42 
43         //刪除
44         public static bool Remove(int UserID)
45         {
46             string sql = string.Format("DELETE FROM [dbo].[User] WHERE UserID = {0}", UserID);
47             int result = SqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, sql);
48             if (result > 0)
49                 return true;
50             else
51                 return false;
52         }
53 
54         //獲取用戶
55         public static Model.User Get(int UserID)
56         {
57             Model.User user = new Model.User();
58             string sql = string.Format("SELECT * FROM [dbo].[User] WHERE UserID = {0}", UserID);
59             DataSet ds = SqlHelper.ExecuteDataset(connectionString, CommandType.Text, sql);
60             if (ds != null && ds.Tables.Count > 0)
61             {
62                 foreach (DataRow dr in ds.Tables[0].Rows)
63                 {
64                     user.UserID = Convert.ToInt32(dr["UserID"]);
65                     user.UserName = dr["UserName"].ToString();
66                     user.Password = dr["Password"].ToString();
67                     user.Discribe = dr["Discribe"].ToString();
68                     user.SubmitTime = Convert.ToDateTime(dr["SubmitTime"]);
69                 }
70             }
71             return user;
72         }
73 
74         //獲取用戶列表
75         public static List<Model.User> GetUsers()
76         {
77             List<Model.User> Users = new List<Model.User>();
78             string sql = string.Format("SELECT * FROM [dbo].[User]");
79             DataSet ds = SqlHelper.ExecuteDataset(connectionString, CommandType.Text, sql);
80             if (ds != null && ds.Tables.Count > 0)
81             {
82                 foreach (DataTable dt in ds.Tables)
83                 {
84                     foreach (DataRow dr in dt.Rows)
85                     {
86                         Model.User user = new Model.User();
87                         user.UserID = Convert.ToInt32(dr["UserID"]);
88                         user.UserName = dr["UserName"].ToString();
89                         user.Password = dr["Password"].ToString();
90                         user.Discribe = dr["Discribe"].ToString();
91                         user.SubmitTime = Convert.ToDateTime(dr["SubmitTime"]);
92                         Users.Add(user);
93                     }
94                 }
95             }
96             return Users;
97         }
98     }

4)修改Add接口的代碼和實現,以下所示:

 1     [ServiceContract]
 2     public interface IAdd
 3     {
 4         [OperationContract]
 5         bool DoWork(Model.User user);
 6     }
 7 
 8     public class Add : IAdd
 9     {
10         public bool DoWork(Model.User user)
11         {
12             return DAL.User.Add(user);
13         }
14     }

 5)修改Save接口的代碼和實現,以下所示:

 1     [ServiceContract]
 2     public interface ISave
 3     {
 4         [OperationContract]
 5         bool DoWork(Model.User user);
 6     }
 7 
 8     public class Save : ISave
 9     {
10         public bool DoWork(Model.User user)
11         {
12             return DAL.User.Save(user);
13         }
14     }

6)修改Remove接口的代碼和實現,以下所示:

 1     [ServiceContract]
 2     public interface IRemove
 3     {
 4         [OperationContract]
 5         bool DoWork(int UserID);
 6     }
 7     public class Remove : IRemove
 8     {
 9         public bool DoWork(int UserID)
10         {
11             return DAL.User.Remove(UserID);
12         }
13     }

7)修改Search接口的代碼和實現,以下所示:

 1     [ServiceContract]
 2     public interface ISearch
 3     {
 4         [OperationContract]
 5         List<Model.User> DoWork();
 6     }
 7 
 8     public class Search : ISearch
 9     {
10         List<Model.User> ISearch.DoWork()
11         {
12             return DAL.User.GetUsers();
13         }
14     }

8)修改Get接口的代碼和實現,以下所示:

 1     [ServiceContract]
 2     public interface IGet
 3     {
 4         [OperationContract]
 5         Model.User DoWork(int UserID);
 6     }
 7 
 8     public class Get : IGet
 9     {
10         public Model.User DoWork(int UserID)
11         {
12             return DAL.User.Get(UserID);
13         }
14     }

4、部署服務端程序

1)將程序發佈,並部署到IIS上,設置端口:8080,以下圖所示:

2)以Add.svc服務應用程序爲目標,測試部署是否成功,成功後以下圖所示:

5、建立Client端Web應用程序

新建WebForm項目WCF.Demo.Client,並建立增刪改查文件,Add.aspx,Save.aspx,SearchAndRemove.aspx。以下圖所示:

6、使用SvcUtil.exe生成客戶端代碼和配置

SvcUtil.exe是一個VS命令行工具,該工具位於:C:\Program Files\Microsoft  SDKs\Windows\v7.0A\bin 或 C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\通常狀況下咱們將SvcUtil.exe添加到VS開發工具中方便之後的運用(也可直接使用該命令行工具)。

1)在VS中的 Tools菜單---選擇External Tools,打開管理窗口以下圖所示:

在Title中輸入SvcUtil,Command中選擇SvcUtil.exe全路徑,Initial  directory欄選擇生成的客戶端代碼和配置文件所放的目錄(此處爲解決方案所在目錄),選上Prompt for arguments,不選上Close on  exit。點擊OK.

2)添加完成後,在VS的工具下會出現這個菜單。以下圖所示:

3)在Client端添加對服務的引用。打開SvUtil工具,在Arguments裏填寫服務的地址,以下圖:

點擊OK後出現下圖,說明代碼類和配置文件生成成功(在解決方案目標下),以下圖所示:

此時代理類和配置文件被下載到解決方案的物理目錄中,以下圖所示:

7、在Client端使用代理類與配置

將代理類從服務端的物理目錄拷貝出來,放到Client端,並適當的修改代碼,加入本身須要的名稱空間,以下圖所示:

使用代碼以下所示:

 1     //增長
 2     public partial class Add : System.Web.UI.Page
 3     {
 4         Service.AddClient addClient = new Service.AddClient();
 5         protected void Page_Load(object sender, EventArgs e)
 6         {
 7 
 8         }
 9 
10         //提交
11         protected void btnSubmit_Click(object sender, EventArgs e)
12         {
13             Model.User user = new Model.User();
14             user.UserName = this.txtUserName.Text;
15             user.Password = this.txtPassword.Text;
16             user.Discribe = this.txtDiscribe.Text;
17             user.SubmitTime = System.DateTime.Now;
18             addClient.DoWork(user);
19             Response.Write("添加成功!");
20         }
21     }
22     //修改
23     public partial class Save : System.Web.UI.Page
24     {
25         Service.SaveClient saveClient = new Service.SaveClient();
26         Service.GetClient getClient = new Service.GetClient();
27         protected void Page_Load(object sender, EventArgs e)
28         {
29             if (!Page.IsPostBack && !string.IsNullOrEmpty(Request.QueryString["UserID"]))
30             {
31                 GetUser();
32             }
33         }
34 
35         protected void GetUser()
36         {
37             int UserID = Convert.ToInt32(Request.QueryString["UserID"]);
38             Model.User user = getClient.DoWork(UserID);
39             this.txtUserName.Text = user.UserName;
40             this.txtDiscribe.Text = user.Discribe;
41         }
42 
43         //提交
44         protected void btnSubmit_Click(object sender, EventArgs e)
45         {
46             int UserID = Convert.ToInt32(Request.QueryString["UserID"]);
47             Model.User user = getClient.DoWork(UserID);
48             user.UserName = this.txtUserName.Text;
49             user.Discribe = this.txtDiscribe.Text;
50             saveClient.DoWork(user);
51             Response.Write("修改爲功!");
52         }
53     }
54     //列表及刪除
55     public partial class SearchAndRemove : System.Web.UI.Page
56     {
57         Service.SearchClient searchClient = new Service.SearchClient();
58         Service.RemoveClient removeClient = new Service.RemoveClient();
59         protected void Page_Load(object sender, EventArgs e)
60         {
61             if (!Page.IsPostBack)
62             {
63                 GetUsers();
64             }
65         }
66 
67         protected void GetUsers()
68         {
69             this.repUsers.DataSource = searchClient.DoWork();
70             this.repUsers.DataBind();
71         }
72 
73         protected void lbtnRemoveCommand(object sender, CommandEventArgs e)
74         {
75             int UserID = Convert.ToInt32(e.CommandName);
76             removeClient.DoWork(UserID);
77             Response.Write("刪除成功~");
78             GetUsers();
79         }
80     }

將生成的配置文件中的 <system.serviceModel>複製到Client的Web.config中,代碼以下:

 1   <system.serviceModel>
 2     <bindings>
 3       <basicHttpBinding>
 4         <binding name="BasicHttpBinding_IAdd" closeTimeout="00:01:00"
 5             openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
 6             allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
 7             maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
 8             messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
 9             useDefaultWebProxy="true">
10           <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
11               maxBytesPerRead="4096" maxNameTableCharCount="16384" />
12           <security mode="None">
13             <transport clientCredentialType="None" proxyCredentialType="None"
14                 realm="" />
15             <message clientCredentialType="UserName" algorithmSuite="Default" />
16           </security>
17         </binding>
18         <binding name="BasicHttpBinding_IRemove" closeTimeout="00:01:00"
19                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
20                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
21                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
22                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
23                    useDefaultWebProxy="true">
24           <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
25               maxBytesPerRead="4096" maxNameTableCharCount="16384" />
26           <security mode="None">
27             <transport clientCredentialType="None" proxyCredentialType="None"
28                 realm="" />
29             <message clientCredentialType="UserName" algorithmSuite="Default" />
30           </security>
31         </binding>
32         <binding name="BasicHttpBinding_ISearch" closeTimeout="00:01:00"
33            openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
34            allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
35            maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
36            messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
37            useDefaultWebProxy="true">
38           <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
39               maxBytesPerRead="4096" maxNameTableCharCount="16384" />
40           <security mode="None">
41             <transport clientCredentialType="None" proxyCredentialType="None"
42                 realm="" />
43             <message clientCredentialType="UserName" algorithmSuite="Default" />
44           </security>
45         </binding>
46         <binding name="BasicHttpBinding_ISave" closeTimeout="00:01:00"
47                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
48                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
49                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
50                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
51                    useDefaultWebProxy="true">
52           <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
53               maxBytesPerRead="4096" maxNameTableCharCount="16384" />
54           <security mode="None">
55             <transport clientCredentialType="None" proxyCredentialType="None"
56                 realm="" />
57             <message clientCredentialType="UserName" algorithmSuite="Default" />
58           </security>
59         </binding>
60         <binding name="BasicHttpBinding_IGet" closeTimeout="00:01:00"
61                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
62                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
63                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
64                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
65                    useDefaultWebProxy="true">
66           <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
67               maxBytesPerRead="4096" maxNameTableCharCount="16384" />
68           <security mode="None">
69             <transport clientCredentialType="None" proxyCredentialType="None"
70                 realm="" />
71             <message clientCredentialType="UserName" algorithmSuite="Default" />
72           </security>
73         </binding>
74       </basicHttpBinding>
75     </bindings>
76     <client>
77       <endpoint address="http://localhost:8080/Add.svc" binding="basicHttpBinding"
78           bindingConfiguration="BasicHttpBinding_IAdd" contract="IAdd"
79           name="BasicHttpBinding_IAdd" />
80       <endpoint address="http://localhost:8080/Remove.svc" binding="basicHttpBinding"
81               bindingConfiguration="BasicHttpBinding_IRemove" contract="IRemove"
82               name="BasicHttpBinding_IRemove" />
83       <endpoint address="http://localhost:8080/Search.svc" binding="basicHttpBinding"
84              bindingConfiguration="BasicHttpBinding_ISearch" contract="ISearch"
85              name="BasicHttpBinding_ISearch" />
86       <endpoint address="http://localhost:8080/Save.svc" binding="basicHttpBinding"
87                bindingConfiguration="BasicHttpBinding_ISave" contract="ISave"
88                name="BasicHttpBinding_ISave" />
89       <endpoint address="http://localhost:8080/Get.svc" binding="basicHttpBinding"
90                bindingConfiguration="BasicHttpBinding_IGet" contract="IGet"
91                name="BasicHttpBinding_IGet" />
92     </client>
93   </system.serviceModel>

 

-------------------------最終效果-----------------------

添加:

修改:

 列表及刪除:

 

8、源碼下載

 點我下載本文章Demo

9、wcf入門教程目錄

無廢話WCF入門教程一[什麼是WCF]

無廢話WCF入門教程二[WCF應用的通訊過程]

無廢話WCF入門教程三[WCF的宿主]

無廢話WCF入門教程四[WCF的配置文件]

無廢話WCF入門教程五[WCF的通訊模式]

版權:http://www.cnblogs.com/iamlilinfeng

相關文章
相關標籤/搜索