Sử dụng WebService trong Silverlight

Working With Web Service In Silverlight

I.Introduction

WebService là sự kết hợp các máy tính cá nhân với các thiết bị khác, các cơ sở dữ liệu và các mạng máy tính để tạo thành một cơ cấu tính toán ảo mà người sử dụng có thể làm việc thông qua các trình duyệt mạng.

Trong bài này mình xin chia sẽ cách tạo WedServive và Cách xây dựng các phương thức trên WebSerice qua đó các phương thức sẽ truyền thồng về Phía Client.

II.Creating Project And Coding

Mở Visual Studio 2010 và tạo Silverlight Application

image

Tiếp theo chúng ta thiết kế giao diện, gồm 1 Button và Một DataGrid

image

Code XAML giao diện:

   1: <UserControl x:Class="WebSeives.MainPage"

   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   4:     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

   5:     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

   6:     mc:Ignorable="d"

   7:     d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

   8:  

   9:     <Grid x:Name="LayoutRoot">

  10:         <Grid.RowDefinitions>

  11:             <RowDefinition Height="40"/>

  12:             <RowDefinition Height="*"/>

  13:         </Grid.RowDefinitions>

  14:         <Button Grid.Row="0" Name="btnLoad" Content="WebSerives"></Button>

  15:         <sdk:DataGrid Grid.Row="1" Name="dataGrid" >

  16:             <sdk:DataGrid.Background>

  17:                 <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

  18:                     <GradientStop Color="#FFA38CDE" Offset="0" />

  19:                     <GradientStop Color="White" Offset="1" />

  20:                 </LinearGradientBrush>

  21:             </sdk:DataGrid.Background>

  22:         </sdk:DataGrid>

  23:     </Grid>

  24: </UserControl>

Tiếp theo các bạn vào Project WedServices.Web tạo mới một Class để làm CSDL:

image

Class Database:

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Web;

   5:  

   6: namespace WebSeives.Web

   7: {

   8:     public class Database

   9:     {

  10:         public string Name { get; set; }

  11:         public string Fone { get; set; }

  12:         public string Email { get; set; }

  13:         public List<Database> GetData()

  14:         {

  15:             List<Database> myData = new List<Database>

  16:             {

  17:                 new Database{Name = "Pham Nguyen",Fone = "01699942228",Email = "pham.nguyen@hotmail.com"},    

  18:                 new Database{Name = "Phi Diep",Fone = "01234567890",Email="123@live.com"},

  19:                 new Database{Name = "Ken Chan",Fone = "01234567890",Email="123@live.com"},

  20:                 new Database{Name = "Binh Nguyen",Fone = "01234567890",Email="123@live.com"},

  21:                 new Database{Name = "Duy Nguyen",Fone = "01234567890",Email="123@live.com"},

  22:                 new Database{Name = "Trong Khoa",Fone = "01234567890",Email="123@live.com"},

  23:                 new Database{Name = "Minh Phuc",Fone = "01234567890",Email="123@live.com"},

  24:                 new Database{Name = "Quang Huy",Fone = "01234567890",Email="123@live.com"},

  25:                 new Database{Name = "jack Black",Fone = "01234567890",Email="123@live.com"},

  26:                 new Database{Name = "Ngoc Son",Fone = "01234567890",Email="123@live.com"},

  27:             };

  28:  

  29:             return myData;

  30:         }

  31:     }

  32: }

Add Web Service: các bạn chọn Right Click vào project WebServices.Web –> Add New Item –> Wed Service

image

Sau khi Add Xong các bạn sẽ thấy có một file Web Service Mới xuất hiện ở Project WebServices.Web

image

Tiếp theo chúng ta kiểm tra xem Web Service đã hoạt động chưa? các bạn chọn Right Click vào file Web Service và chọn View In Browser, nếu như các bạn thấy kết quả giống hình phía dưới là OK .

image

Bây giờ chúng ta chỉnh Port cho ứng dụng. Right Click vào project WebServices.Web chọn Properties và làm theo hình phía dưới

image

image

Đến đây chúng ta đã tùy chỉnh Port xong.

Để thực hiện việc truyền thông với Phía Project Siverlight WebService, các bạn chọn Right Click vào Reference –> Add Service Reference

image

Chọn Discover thấy ở thanh Address hiện ra Link : http://localhost:8080/MSPWebService.asmx –> các bạn chọn OK

image

Bây giờ trong Project WebService của chúng ta đã có thêm một Folder là ServiceReference chịu trách nhiệm truyền thông với Web Service

image

Bây giờ ở phía Web Service các bạn thêm một phương thức LoadData trong file MSPWebService.asmx

   1: [WebMethod]

   2: public List<Database> LoadData()

   3: {

   4:     List<Database> myData = new List<Database>();

   5:     Database Student = new Database();

   6:     myData = Student.GetData();

   7:     return myData;

   8: }

Bây giờ khi chạy Web Service chúng ta thấy là đã có thêm một phương thức LoadData.

Các bạn lưu ý là nếu như ko viết dòng [WebMeThod] ở trước các phương thức, thì phía Client sẽ ko nhìn thấy.

image

các bạn quay lại Project WebService –> Right Click vào biểu tượng ServiceReference –> Update Service Reference

image

Một Lưu ý nữa, là mỗi khi các bạn thêm các phương thức ở Web Service(trong file MSPWebService.asmx) thì phải Update, nếu không ở phía Client sẽ không có những phương thức mới

Quay lại trang MainPage, các bạn vào file MainPage.xaml.cs và tạo sự kiện cho Button

Chung ta dùng Lớp SoapClient để sử dụng các phương thức đã định nghĩa ở Web Service. các bạn khai báo đối tượng MSPWebServiceSoapClient Services; và đừng quên using WebSeives.ServiceReference;

Tiếp theo chúng ta vào Phương thức Click đã vừa tạo và tạo sự kiện Completed (trong bài này là LoadDataCompleted)

   1: void btnLoad_Click(object sender, RoutedEventArgs e)

   2:  

   3:    Services = new MSPWebServiceSoapClient();

   4:    Services.LoadDataCompleted += new EventHandler<LoadDataCompletedEventArgs>(Services_LoadDataCompleted);

   5:    Services.LoadDataAsync();

Lưu Ý : Các bạn phải gọi phương thức Async(trong bài là Services.LoadDataAsync();) thì Phương thức mới được kích hoạt.

Tiếp theo các bạn vào Phương thức LoadDataComplete để xử lý việc Show dữ liệu ra ngoài:

   1: void Services_LoadDataCompleted(object sender, LoadDataCompletedEventArgs e)

   2: {

   3:     dataGrid.ItemsSource = e.Result;

   4: }

Full Souce Mainpage.xaml.cs

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Net;

   5: using System.Windows;

   6: using System.Windows.Controls;

   7: using System.Windows.Documents;

   8: using System.Windows.Input;

   9: using System.Windows.Media;

  10: using System.Windows.Media.Animation;

  11: using System.Windows.Shapes;

  12: using WebSeives.ServiceReference;

  13: namespace WebSeives

  14: {

  15:     public partial class MainPage : UserControl

  16:     {

  17:         MSPWebServiceSoapClient Services;

  18:         public MainPage()

  19:         {

  20:             InitializeComponent();

  21:             this.btnLoad.Click += new RoutedEventHandler(btnLoad_Click);

  22:         }

  23:  

  24:         void btnLoad_Click(object sender, RoutedEventArgs e)

  25:         {

  26:             Services = new MSPWebServiceSoapClient();

  27:             Services.LoadDataCompleted += new EventHandler<LoadDataCompletedEventArgs>(Services_LoadDataCompleted);

  28:             Services.LoadDataAsync();

  29:         }

  30:  

  31:         void Services_LoadDataCompleted(object sender, LoadDataCompletedEventArgs e)

  32:         {

  33:             dataGrid.ItemsSource = e.Result;

  34:         }

  35:     }

  36: }

Run Application và xem kết quả

image

/*Web is beautiful*/

Source Code Download Here !

Leave a comment