Tải bản đầy đủ (.pdf) (21 trang)

Hướng dẫn thực hành WCF Part 1 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.64 MB, 21 trang )

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


<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<services>
<service name="_02_ConsoleWCF.MathServer">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/MathServer"/>
</baseAddresses>
</host>
<endpoint address="" binding="basicHttpBinding"
contract="_02_ConsoleWCF.IMath" />
</service>
</services>
</system.serviceModel>
</configuration>

Câu hỏi: Trong một ứng dụng có thể có khai báo nhiều thẻ <service> được không?
Trong một thẻ <service> có thẻ khai báo nhiều thẻ <endpoint> được không?
Thẻ <host> khi nào cần và khi nào không cần?
3.3 Thử kết nối bằng WCF Test Client
Chạy WCF Test Client ở thư mục. Đường dẫn file này là:
“C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\WcfTestClient.exe"

Figure 5: Lỗi phát sinh vì không lấy được Metadata từ dịch vụ.
Câu hỏi: Tại sao bị lỗi? Giải thích nguyên nhân

4 Thêm MEX endpoint để cho client tìm hiểu dịch vụ
Xem ví dụ 02_ConsoleWCFWithConfig
4.1 Thêm MEX endpoint bằng code

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>

</system.serviceModel>
Câu hỏi: giải thích ý nghĩa của:
 behaviorConfiguration
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"
/>
 <serviceMetadata httpGetEnabled="True"/>

5 Tạo client để sử dụng dịch vụ WCF
Xem ví dụ 02_WPFClient
Bước 1: Tạo Windows Form như hình dưới


Bước 2: Add Service Reference

Bước 3: Viết đoạn code để gọi dịch vụ thông qua lớp proxy được tự tạo ra sau bước Add Service Reference
private void btnAdd_Click(object sender, EventArgs e)
{
try //Thói quen tốt, nên dùng try catch trước những lời gọi dịch vụ để bắt lỗi
{
MathService.MathClient mathClient = new MathService.MathClient();
int result = mathClient.Add(int.Parse(txtA.Text), int.Parse(txtB.Text));
txtResult.Text = result.ToString();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "Exception", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}


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 6 : Ấn nút Advanced để sửa đổi thông số của tham chiếu đến dịch vụ

Figure 7 : Chọn check box Generate asynchronous operations
Bước 3: Định nghĩa event handler cho sự kiện hàm được gọi dị bộ (Asynchronous call) hoàn tất công việc. Lưu ý ấn phím
Tab để tự động điền mã.


Bước 4: chạy thử chương trình.
 Khi ấn nút Add Sync, nếu trong hàm tính toán ở phía dịch vụ chạy (ở đây là rất lâu) thì người phải chờ cho đến khi
hàm tính toán hoàn tất.
 Khi ấn nút Add Async, trong lúc hàm tính toán ở phía dịch vụ chạy, người dùng vẫn có thể tương tác với control
trên giao diện, ví dụ: kéo thanh trượt slider.

Figure 8 : Hoạt động ở client bị block (ngưng trệ) nếu hàm đồng bộ chạy mất nhiều thời gian
Câu hỏi:
8 Gọi hàm Duplex


9 Hosting một ứng dụng WCF bằng IIS 7

Bước 1: Mở ví dụ 01_WCFServiceLibrary\ 01_WCFServiceLibrary.sln
Bước 2: Chọn kết xuất sau biên dịch là Release

Bước 3: Publish ra một thư mục mà IIS Application sẽ trỏ đến. Menu: Build > Publish



Bước 4: Tạo Virtual Application trong Default web site hoặc tạo một web site mới ở port mới.



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>

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:xxx/ /MathService/" />
</baseAddresses>
</host>
</service>

10 SilverLight 2.0 gọi WCF basicHttpBinding
Xem ví dụ 06_SilverLight\ListCustomer\ListCustomer.sln
Bước 1: Tạo một solution SilverLight Application có chứa website ASP.net để host SilverLight control để test thử.


Bước 2: Tạo kết nối đến database Northwind trong CSDL SQL 2005.

Bước 3: Thêm mới LINQ to SQL Classess. Đặt tên là NWCustomer.dbml


Bước 4: Từ Server Explorer, kéo bảng Customer vào khung thiết kế của NWCustomer.dbml .


Bước 5: Tiếp đó, thêm mới một WCF Service vào dự án. Đặt tên là Northwind.svc


Bước 6: Do SilverLight 2.0 chỉ sử dụng được dịch vụ web service cơ bản nên ta sẽ dùng basicHttpBinding để mô tả
endpoint dịch vụ WCF này. Mở file app.config vào phần <system.serviceModel> để sửa.


Bước 7: Tạo Service Contract và Operation Contract. Ở ví dụ này: chỉ cần một hàm getCustomerByCity. Tham số vào là
city, trả về List<Customer>. Kiểu dữ liệu Customer đã được tự động định nghĩa khi tạo LINQ to SQL ở bước 3.

[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.


Bước 13: Sau đó tạo sự kiện Click khi người dùng ấn nút Tìm Kiếm

Bước 14: Double click vào sự kiện ButtonQuery_Click để quay lại VisualStudio viết code cho hàm hứng sự kiện này.
private void ButtonQuery_Click(object sender, RoutedEventArgs e)
{
NorthwindServiceReference.NWServiceClient client = new
NorthwindServiceReference.NWServiceClient();

client.getCustomerByCityCompleted += new
EventHandler<ListCustomer.NorthwindServiceReference.getCustomerByCityCompletedEventArgs>(client_get
CustomerByCityCompleted);

client.getCustomerByCityAsync(SearchCity.Text);

}


void client_getCustomerByCityCompleted(object sender,
ListCustomer.NorthwindServiceReference.getCustomerByCityCompletedEventArgs e)
{
Result.ItemsSource = e.Result;
}

Gadget gọi WCF trả về JSON

11 ADO.NET DataService REST (thêm)
Câu hỏi: REST là gì?











Đổ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)

{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
}
}
}

Chạy thử, sẽ thấy không có hàm nào từ dịch vụ:
Ở đây ADO.NET Data Service sử dụng một kiểu binding đặc biệt của WCF, không đưa ra các hàm gọi mà lập trình viên có
thể tùy ý thêm, sửa. REST chỉ chấp nhận một số thao tác dữ liệu chuẩn: Create, Read, Update, Delete (CRUD).




×