WCF Getting Started Tutorial series six

Source: Internet
Author: User
Tags isearch

First, preface

The previous chapters cover a number of theoretical foundations, such as: What is WCF, A, B, and C in WCF. Transport mode for WCF. This article starts with the zero and everyone writes a small WCF application demo.

Most of the framework of learning is from the increase, delete, change, check the beginning to learn, we learn WCF is the same. From a simple point of view (not including security, optimization and other related issues), WCF additions and deletions are similar to WebForm. WCF simply writes the specific "implementation" on the "service side", while the "call" is placed on the "client side". feel help don't forget to order a praise ha, thank you Oh ~

Second, demo instructions

1) The "service Side" of the demo is hosted by native IIS, and "Client Side" takes the WebForm project as an example.

2) Demo "service-side" extraction data by beginners relatively easy to accept the hierarchical structure to build, divided into service layer, entity layer, data layer.

The reference relationship is as follows:

3) Demo database for SQL Server, table user for example (SQL statements in the downloaded compressed package init.sql), the table structure is as follows:

Field name

Column Name

Data type

Constraints

How to Generate

User number

Userid

Int

Primary key, you must enter

Automatic +1 Increase

Name

Name

VARCHAR (200)

Non-mandatory input

Manual input

Password

Password

VARCHAR (200)

Non-mandatory input

Manual input

Describe

Discribe

varchar (800)

Non-mandatory input

Manual input

Time of submission

Submittime

Datetime

Non-mandatory input

Manual input

Iii. creating a service-side host

1) Create a WCF application named: WCF.Demo.Service, such as:

2) Delete the default file IService.cs and Service.svc. and respectively create add, delete, change, check "Add.svc", "Save.svc", "Remove.svc", "get.svc,search.svc", respectively, corresponding to 4 functions of the Service Application WCF Service application, and create data operations layer and data entity layer, such as:

3) Add the entity layer and the data Operation layer code as follows:

 1//user entity 2 [DataContract] 3 public class User 4 {5 [DataMember] 6 public int UserID {GE T Set } 7 [DataMember] 8 public string UserName {get, set;} 9 [datamember]10 public string Pas Sword {get; set;} One [datamember]12 public string Discribe {get; set;} [datamember]14 public DateTime submittime {get; set;}  15}16//Data operation, calling SqlHeler17 public class User18 {private static readonly string connectionString = "server=."; database=wcfdemo;uid=sa;pwd=123456; "; 20 21//Add the public static bool Add (Model.user User) at $ {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); int result = Sqlhelper.executenonquery (connectionString, CommandType.Text, SQL); 26 if (Result &Gt         0) return true;28 else29 return false;30}31 32//Modify 33 public static bool Save (Model.user User), {+ 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); int result = Sqlhelper.executenonquery (connectionString, CommandType.Text, sql), PNS if (         Result > 0) true;39 return else40 return false;41}42 43 Delete the public static bool remove (int UserID) {String sql = string. Format ("DELETE from [dbo].[ User] WHERE UserID = {0} ", userid); int result = Sqlhelper.executenonquery (connectionString, Commandtype.tex t, SQL); if (Result > 0) return true;50 else51 retUrn false;52}53 54//Get user on public static model.user get (int UserID) Del. User user = new Model.user (), and the String sql = string. Format ("select * FROM [dbo].[ User] WHERE UserID = {0} ", userid); SqlHelper.ExecuteDataset DataSet ds = connectionString, CommandType.Text , SQL), or if (ds! = null && ds. Tables.count > 0) (DataRow Dr in DS. Tables[0]. Rows). UserID = Convert.ToInt32 (dr["UserID"]); UserName = dr["UserName"]. ToString (); Password = dr["Password"]. ToString (); Discribe = dr["Discribe"]. ToString ();         Submittime = Convert.todatetime (dr["Submittime"]);}70}71 return user;72 }73 74//Get user list list<model.user> public static GetUserS () {list<model.user> Users = new list<model.user> (); String sql = Stri Ng. Format ("select * FROM [dbo].[ User] "), the SqlHelper.ExecuteDataset DataSet ds = (connectionString, commandtype.text, SQL); s! = null && ds. Tables.count > 0) Bayi {The DataTable dt in DS. Tables) (DataRow dr in DT). Rows) Model.user user = new Model.user (); . UserID = Convert.ToInt32 (dr["UserID"); UserName = dr["UserName"]. ToString (); Password = dr["Password"]. ToString (); Discribe = dr["Discribe"]. ToString ();                 Submittime = Convert.todatetime (dr["Submittime"]); Users.add (user); 93}94 }95            }96 return users;97}98} 

4) Modify the code and implementation of the add interface as follows:

1     [ServiceContract] 2 public     Interface Iadd 3     {4         [OperationContract] 5         bool DoWork (model.user user); 6     } 7  8 public     class Add:iadd 9     {Ten public         bool DoWork (Model.user User) One         {             return DAL . User.add (user);         }14     }

5) Modify the code and implementation of the Save interface as follows:

1     [ServiceContract] 2 public     Interface Isave 3     {4         [OperationContract] 5         bool DoWork ( Model.user User); 6     } 7  8 public     class Save:isave 9     {Ten public         bool DoWork (model.user User)             Return DAL. User.save (user);         }14     }

6) Modify the code and implementation of the Remove interface as follows:

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) Ten         {one             return DAL. User.remove (UserID);         }13     }

7) Modify the code and implementation of the search interface as follows:

1     [ServiceContract] 2 public     Interface ISearch 3     {4         [OperationContract] 5         list< Model.user> DoWork (); 6     } 7  8 public     class Search:isearch 9     {         list<model.user> isearch.dowork ()         {             return DAL. User.getusers ();         }14     }

8) Modify the code and implementation of the Get interface as follows:

1     [ServiceContract] 2 public     Interface Iget 3     {4         [OperationContract] 5         model.user DoWork (int UserID); 6     } 7  8 public     class Get:iget 9     {Ten public         model.user DoWork (int UserID) One         {             return DAL. User.get (UserID);         }14     }
Iv. deployment of server-side procedures

1) Publish the program and deploy it to IIS, setting port: 8080 as shown in:

2) to target the ADD.SVC service application, test whether the deployment was successful, as shown in the following:

V. Create a client-side Web application

New WebForm Project WCF.Demo.Client, and create additions and deletions to change files, add.aspx,save.aspx,searchandremove.aspx. As shown in the following:

Vi. generating client code and configuration using SvcUtil.exe

SvcUtil.exe is a vs command-line tool located at: C:\Program Files\Microsoft Sdks\windows\v7.0a\bin or C:\Program Files (x86) \microsoft SDKs \windows\v7.0a\bin\ generally we add SvcUtil.exe to the VS development tool for later use (or you can use the command line tool directly).

1) In the Tools menu in vs---select external tools and open the Admin window as shown in:

In the title input Svcutil,command Select SvcUtil.exe full path, Initial directory bar to select the generated client code and configuration file to put the directories (here is the solution directory), select Prompt for Arguments, do not select close on exit. Click OK.

2) Once added, this menu will appear under the VS tool. As shown in the following:

3) Add a reference to the service on the client side. Open the Svutil tool and fill in the arguments with the address of the service, such as:

After clicking OK, the code class and configuration file generation succeeds (under the solution target), as shown in:

At this point the proxy class and configuration file are downloaded to the physical directory of the solution as shown in:

Vii. using proxy classes and configuration on client side

Copy the proxy class from the server's physical directory, put it on the client side, and modify the code appropriately to add the namespace you need, as shown in:

Use the code as follows:

 1//Add 2 public partial class Add:System.Web.UI.Page 3 {4 Service.addclient addclient = new Servic E.addclient (); 5 protected void Page_Load (object sender, EventArgs e) 6 {7 8} 9 10//Submit one Prot             ected void btnSubmit_Click (object sender, EventArgs e) {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); Response.Write ("Add success! 20}21}22//Modify the public partial class Save:System.Web.UI.Page24 {Service.saveclie NT Saveclient = new Service.saveclient (); service.getclient getclient = new Service.getclient (); prote CTED void Page_Load (object sender, EventArgs e), {if (! Page.IsPostBack&&!string. IsNullOrEmpty (request.querystring["UserID")) (GetUser) 32}33}34 3 5 protected void GetUser () $ {PNS int UserID = Convert.ToInt32 (request.querystring["userid"]); 3 8 Model.user user = Getclient.dowork (UserID), This.txtUserName.Text = user. username;40 this.txtDiscribe.Text = user.              discribe;41}42 43//Submit protected void btnSubmit_Click (object sender, EventArgs e) 45 {46 int UserID = Convert.ToInt32 (request.querystring["UserID"]); Model.user User = Getclient.dowork (UserID); UserName = this.txtusername.text;49 user. Discribe = this.txtdiscribe.text;50 saveclient.dowork (user); Response.Write ("Modified successfully! "); 52}53}54//list and delete the public partial class SearchAndRemove:System.Web.UI.Page56 {$ Se Rvice. Searchclient searchclient = new Service.searchclient (); service.removeclient removeclient = new Service.removeclient (); tected void Page_Load (object sender, EventArgs e) (. Page.IsPostBack) getusers (),}65}66, protected void Get Users () This.repUsers.DataSource = Searchclient.dowork (); This.repUsers.DataBind () ;}72 protected void Lbtnremovecommand (object sender, CommandEventArgs e) NT UserID = Convert.ToInt32 (e.commandname), Removeclient.dowork (userid), Response.Write ("Delete succeeded ~ "); Getusers (); 79}80}

Copy <system.serviceModel> from the generated configuration file to the client's web. config with the following code:

 1 <system.serviceModel> 2 <bindings> 3 <basicHttpBinding> 4 <binding name= "Basic Httpbinding_iadd "closetimeout=" 00:01:00 "5 opentimeout=" 00:01:00 "receivetimeout=" 00:10:00 "sendTimeout=" 00:0             "6 allowcookies=" false "Bypassproxyonlocal=" false "Hostnamecomparisonmode=" StrongWildcard "7 Maxbuffersize= "65536" maxbufferpoolsize= "524288" maxreceivedmessagesize= "65536" 8 messageencoding= "Text" TextE ncoding= "Utf-8" transfermode= "Buffered" 9 usedefaultwebproxy= "true" >10 <readerquotas maxdepth= "Maxstringcontentlength=" "8192" maxarraylength= "16384" one maxbytesperread= "4096" maxnametablecharcount= "16 384 "/>12 <security mode=" None ">13 <transport clientcredentialtype=" None "Proxycredentia Ltype= "None" realm= ""/>15 <message clientcredentialtype= "UserName" algorithmsuite= "De          Fault "/>16 </security>17 </binding>18 <binding name= "Basichttpbinding_iremove" closeTimeout= "00:01:00 "Opentimeout=" 00:01:00 "receivetimeout=" 00:10:00 "sendtimeout=" 00:01:00 "ALLOWC Ookies= "false" Bypassproxyonlocal= "false" hostnamecomparisonmode= "StrongWildcard" maxbuffersize= "6553 6 "maxbufferpoolsize=" 524288 "maxreceivedmessagesize=" 65536 "messageencoding=" Text "textencoding=" utf -8 "transfermode=" Buffered "usedefaultwebproxy=" true ">24 <readerquotas maxdepth=" 32 " Maxstringcontentlength= "8192" maxarraylength= "16384" maxbytesperread= "4096" maxnametablecharcount= "16384" />26 <security mode= "None" >27 <transport clientcredentialtype= "None" Proxycredentialtype = "None" 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" allowcookies= "false" bypass  Proxyonlocal= "false" hostnamecomparisonmode= "StrongWildcard" maxbuffersize= "65536" maxbufferpoolsize= "524288"            Maxreceivedmessagesize= "65536" messageencoding= "Text" textencoding= "Utf-8" transfermode= "Buffered" 37 Usedefaultwebproxy= "true" >38 <readerquotas maxdepth= "+" maxstringcontentlength= "8192" maxArrayLength= "16384" maxbytesperread= "4096" maxnametablecharcount= "16384"/>40 <security mode= "None"             ; <transport clientcredentialtype= "None" proxycredentialtype= "None" realm= ""/>43         <message clientcredentialtype= "UserName" algorithmsuite= "Default"/>44 </security>45   </binding>46      <binding name= "Basichttpbinding_isave" closetimeout= "00:01:00"-opentimeout= "00:01:00" Receiv etimeout= "00:10:00" sendtimeout= "00:01:00" allowcookies= "false" Bypassproxyonlocal= "false" Hostnameco Mparisonmode= "StrongWildcard" maxbuffersize= "65536" maxbufferpoolsize= "524288" maxreceivedmessagesize = "65536" messageencoding= "Text" textencoding= "Utf-8" transfermode= "Buffered" Defaultwebproxy= "true" >52 <readerquotas maxdepth= "+" maxstringcontentlength= "8192" maxarraylength= "16384"             Maxbytesperread= "4096" maxnametablecharcount= "16384"/>54 <security mode= "None" >55             <transport clientcredentialtype= "None" proxycredentialtype= "None" realm= ""/>57 <message clientcredentialtype= "UserName" algorithmsuite= "Default"/>58 </security>59 < /binding>60 &Lt;binding name= "Basichttpbinding_iget" closetimeout= "00:01:00", opentimeout= "00:01:00" receiveTimeout = "00:10:00" sendtimeout= "00:01:00" allowcookies= "false" Bypassproxyonlocal= "false" Hostnamecomparison Mode= "StrongWildcard" maxbuffersize= "65536" maxbufferpoolsize= "524288" maxreceivedmessagesize= "65536" messageencoding= "Text" textencoding= "Utf-8" transfermode= "Buffered" USEDEFAULTW               Ebproxy= "true" >66 <readerquotas maxdepth= "+" maxstringcontentlength= "8192" maxarraylength= "16384" 67             Maxbytesperread= "4096" maxnametablecharcount= "16384"/>68 <security mode= "None" >69 <transport clientcredentialtype= "None" proxycredentialtype= "None" realm= ""/>71 <m Essage clientcredentialtype= "UserName" algorithmsuite= "Default"/>72 </security>73 </binding >74 </basichttpbinding>75 </bindings>76 <client>77 <endpoint address= "Http://localhost:8080/Add.svc" b inding= "BasicHttpBinding" bindingconfiguration= "Basichttpbinding_iadd" contract= "Iadd" Name= "Basic               Httpbinding_iadd "/>80 <endpoint address=" http://localhost:8080/Remove.svc "binding=" BasicHttpBinding "81 bindingconfiguration= "Basichttpbinding_iremove" contract= "Iremove" "Name=" "/>83 <endpoint address=" http://localhost:8080/Search.svc "binding=" BasicHttpBinding "-BINDINGC onfiguration= "Basichttpbinding_isearch" contract= "ISearch" name= "Basichttpbinding_isearch"/>86 &L T;endpoint address= "Http://localhost:8080/Save.svc" binding= "BasicHttpBinding" for bindingconfiguration= "Basi Chttpbinding_isave "contract=" Isave "name=" Basichttpbinding_isave "/>89 <endpoint address=" HT Tp://localhost:8080/get.Svc "binding=" BasicHttpBinding "bindingconfiguration=" Basichttpbinding_iget "contract=" IGet "91 Name= "Basichttpbinding_iget"/>92 </client>93 </system.serviceModel>

-------------------------Final Effect-----------------------

Add to:

Modify:

List and Delete:

Eight, source code download

Click I download this article demo

WCF Getting Started Tutorial series six

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.