Hướng dẫn thực hành WCF Part 1
1 Lưu ý
Trong phần 1: chúng tôi sẽ chưa đi sâu về bảo mật, khả năng chịu tải, cũng như các chuẩn truyền thông đặc biệt như
tcpBinding, MSMQ, chi tiết lập trình WCF với WF… Trong phần 2, chúng tôi sẽ đề cập sâu hơn.
2 Tạo project WCF Service Library
Figure 1: Chọn WCF Service Library project template
Figure 2: Chạy thử phương thức Add của MathServer
Figure 3: Trong một ứng dụng, có thể thêm nhiều WCF Service
3 Tạo ứng dụng WCF Console không dùng Project Template
3.1 Không dùng định nghĩa dịch vụ WCF trong app.config
Xem ví dụ: 02_ConsoleWCF
Bước 1: Tạo Console Application
Bước 2: Thêm reference tới Service.Model
Figure 4: Add Reference System.ServiceModel
Bước 3: Khai báo using System.ServiceModel;
Bước 4: Tạo Service Contract
Bước 5: Định nghĩa Operation Contract
Bước 6: Viết hàm thực hiện operation contract
Bước 7: Viết code để định nghĩa cấu hình và khởi tạo servicehost
Bước 8: Chạy thử
3.2 Khai báo cấu hình dịch vụ WCF bằng file app.config
Bước 9: Thay bằng định nghĩa cấu hình trong code bằng khai báo trong file XML app.config
Bước 1: Thêm dòng khai báo using System.ServiceModel.Description;
Bước 2: Thêm đoạn lệnh sau đây vào App.cs
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(behavior);
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
4.2 Thêm MEX endpoint bằng khai báo trong app.config
Thay nội dung app.config bằng nội dung của app-mex.config
<system.serviceModel>
<services>
<service name="_02_ConsoleWCF.MathServer" behaviorConfiguration="MathServerBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/MathServer"/>
</baseAddresses>
</host>
<endpoint address="" binding="basicHttpBinding"
contract="_02_ConsoleWCF.IMath" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MathServerBehavior">
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
6 Gọi một hàm một chiều (one way operation)
Xem ví dụ 03_OneWay\ Oneway.sln
Bước 1: Chạy server 03_OneWay\OneWay.sln
Bước 2: Chạy client 03_OneWay\ClientTest.sln
Bước 3: Liên tục ấn vài lần nút “Call OneWay operation”
Bước 4: So sánh với liên tục ấn vài lần nút “Call Non OneWay operation” rồi cho nhận xét.
Câu hỏi: Dùng dịch vụ một chiều khi nào?
Trả lời: Dùng dịch vụ một chiều khi client gọi một hàm không giá trị trả về (void) của service. Ngay sau lời gọi, client có
thể tiếp tục chạy lệnh tiếp ngay sau khi lời gọi dịch vụ được gửi đi. Có ý nghĩa khi hàm dịch vụ ở máy chủ chạy chậm.
7 Gọi hàm dị bộ (call asynchronous operation)
Xem ví dụ: 04_Asynchronous\AsynchronousCall.sln
Bước 1: Tạo AsyncMathServer với các hàm sau:
public class MathServer : IMathServer
{
public int AddSlow(int A, int B)
{
Thread.Sleep(4000); //Làm cho hàm trễ để giả lập một tác vụ chạy tốn thới gian
return A + B;
}
public int AddFast(int A, int B)
{
//Thread.Sleep(4000);
return A + B;
}
}
Bước 2: Tạo Winform client , rồi Add Service Reference đến AsyncMathServer.
Figure 9 : Đặt Alias và trỏ đến thư mực vật lý chứa mã chạy của WCF Service Bước 5: Trong thư mục được publish mã chạy dịch vụ WCF, tạo các file *.svc để trỏ đến từng service được định nghĩa
trong file web.config. Trong ví dụ này, chúng ta có 2 dịch vụ:
_01_WCFServiceLibrary.Service1
_01_WCFServiceLibrary.MathService
Nội dung file Service1.svc là
<% @ServiceHost Service="_01_WCFServiceLibrary.Service1" %>
Nội dung file Math.svc là
<% @ServiceHost Service="_01_WCFServiceLibrary.MathService" %>
Bước 6: Sử dụng web browser để kiểm tra dịch vụ
http://localhost/MyService/service1.svc (xem tổng quan)
http://localhost/MyService/service1.svc?wsdl (xem chi tiết định nghĩa nội dung XML của dịch vụ)
Figure 10 : Kiểm tra dịch vụ bằng web browser
Bước 7: hoặc dùng WCF Test Client để kiểm tra Lưu ý: Khi đã host trên IIS 7 thông tin baseAddress không còn cần thiết nữa
<service behaviorConfiguration="_01_WCFServiceLibrary.MathServiceBehavior"
name="_01_WCFServiceLibrary.MathService">
<endpoint address="" binding="wsHttpBinding" contract="_01_WCFServiceLibrary.IMathService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
[ServiceContract]
public interface INorthwind
{
[OperationContract]
List<Customer> getCustomerByCity(string city);
}
Bước 8: Viết mã thể hiện cho Operation Contract: Chuột phải menu, chọn Implement Interface…
Bước 9: Viết câu lệnh LINQ để trả vê List<Customer>
public class Northwind : INorthwind
{
public List<Customer> getCustomerByCity(string city)
{
NWCustomerDataContext db = new NWCustomerDataContext();
var result = from customer in db.Customers where customer.City.StartsWith(city) select
customer;
return result.ToList();
}
}
Bước 10: Chạy thử web service, bằng cách chọn Northwind.svc làm start page. Sau đó chạy WCF Test Client để kiểm tra
hàm getCustomerByCity. Gõ thử giá trị “London”, rồi ấn nút “Invoke” và chờ kết quả trả về ở Response.
Nếu thành công thì vào project tạo SilverLight, ở đây là SilverLight WCF để thêm tham chiếu đến dịch vụ WCF vừa tạo.
Lưu ý chọn cách gọi Asynchronous call.
Bước 11: Thiết kế giao diện SilverLight bằng Expression Blend Bước 12: tạo Grid, rồi kéo thả các control.
Đổi từ:
namespace NorthwindDataService
{
public class NorthwindDataService : DataService< /* TODO: put your data source class name here */ >
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(IDataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable,
etc.
// Examples:
// config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead);
// config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
}
}
}
Thành:
namespace NorthwindDataService
{
public class NorthwindDataService : DataService<NorthwindEntities>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(IDataServiceConfiguration config)