Windows Store App and Web Services & JSON (C#) |
Windows Store App and Web Services & JSON (C#) บทความนี้จะเป็นการประยุกต์การเขียน Windows Store Apps เพื่อติดต่อ Web Services ใช้การรับส่งข้อมูลในรูปแบบของ JSON วิธีการก็คือ ฝั่ง Web Services ที่ถูกเขียนด้วย ASP.Net (C#) จะสร้าง Services ที่มีชื่อว่า getCustomerData() ทำหน้าที่อ่านข้อมูลจาก MySQL Database แล้วแปลงข้อมูลที่ได้ให้อยู่ในรูปแบบของ JSON เพื่อที่จะรอ Client ทำการ Request ช่องทางผ่าน Web Services และนำค่า JSON ที่ได้ไปใช้งานตามต้องการ
ฝั่ง Web Services (ASP.Net/C#/MySQL)
MySQL Table บน Web Services
![Windows Store App and Web Services & JSON (C#) Windows Store App and Web Services & JSON (C#)](https://www.thaicreate.com/upload/tutorial/windows-store-app-web-services-json-01.jpg?v=1001)
CREATE TABLE `customer` (
`CustomerID` varchar(4) NOT NULL,
`Name` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`CountryCode` varchar(2) NOT NULL,
`Budget` double NOT NULL,
`Used` double NOT NULL,
PRIMARY KEY (`CustomerID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `customer` VALUES ('C001', 'Win Weerachai', '[email protected]', 'TH', 1000000, 600000);
INSERT INTO `customer` VALUES ('C002', 'John Smith', '[email protected]', 'UK', 2000000, 800000);
INSERT INTO `customer` VALUES ('C003', 'Jame Born', '[email protected]', 'US', 3000000, 600000);
INSERT INTO `customer` VALUES ('C004', 'Chalee Angel', '[email protected]', 'US', 4000000, 100000);
![](/images/adv.jpg)
เรียกใช้ NameSpace ไว้จัดการกับ MySQL Database
using System.Data;
using Newtonsoft.Json;
using MySql.Data.MySqlClient;
Method บน Web Services ซึ่งจะอ่านข้อมูลจาก MySQL แล้วส่งกลับเป็น JSON Code
[WebMethod]
public string getCustomerData()
{
MySqlConnection objConn = new MySqlConnection();
MySqlCommand objCmd = new MySqlCommand();
MySqlDataAdapter dtAdapter = new MySqlDataAdapter();
DataSet ds = new DataSet();
DataTable dt;
String strConnString, strSQL;
strConnString = "Server=localhost;User Id=root; Password=root; Database=mydatabase; Pooling=false";
strSQL = "SELECT * FROM customer";
objConn.ConnectionString = strConnString;
objCmd.Connection = objConn;
objCmd.CommandText = strSQL;
objCmd.CommandType = CommandType.Text;
dtAdapter.SelectCommand = objCmd;
dtAdapter.Fill(ds);
dt = ds.Tables[0];
dtAdapter = null;
objConn.Close();
objConn = null;
string json = JsonConvert.SerializeObject(dt, Formatting.Indented);
return json;
}
เมื่อทดสอบเรียก Web Services เราจะได้ Result ที่เป็น JSON ดังนี้
![Windows Store App and Web Services & JSON (C#) Windows Store App and Web Services & JSON (C#)](https://www.thaicreate.com/upload/tutorial/windows-store-app-web-services-json-02.jpg?v=1001)
ชื่อ Method ว่า getCustomerData()
![Windows Store App and Web Services & JSON (C#) Windows Store App and Web Services & JSON (C#)](https://www.thaicreate.com/upload/tutorial/windows-store-app-web-services-json-03.jpg?v=1001)
คลิกที่ Invoke โดยใน Method นี้ไม่มี Parameters ฉะนั้นสามารถคลิกได้ทันที
![Windows Store App and Web Services & JSON (C#) Windows Store App and Web Services & JSON (C#)](https://www.thaicreate.com/upload/tutorial/windows-store-app-web-services-json-04.jpg?v=1001)
เป็นไฟล์ JSON ที่ถูกส่งมาจาก Web Services
[
{"CustomerID":"C001","Name":"Win Weerachai","Email":"[email protected]" ,"CountryCode":"TH","Budget":"1000000","Used":"600000"},
{"CustomerID":"C002","Name":"John Smith","Email":"[email protected]" ,"CountryCode":"UK","Budget":"2000000","Used":"800000"},
{"CustomerID":"C003","Name":"Jame Born","Email":"[email protected]" ,"CountryCode":"US","Budget":"3000000","Used":"600000"},
{"CustomerID":"C004","Name":"Chalee Angel","Email":"[email protected]" ,"CountryCode":"US","Budget":"4000000","Used":"100000"}
]
รูปแบบการอ่านค่า JSON ฝั่ง Windows Store Apps (C#)
![Windows Store App and Web Services & JSON (C#) Windows Store App and Web Services & JSON (C#)](https://www.thaicreate.com/upload/tutorial/windows-store-app-web-services-json-05.jpg?v=1001)
ในการเรียกใช้งาน Web Services บน Windows Store Apps จะอาศัยการ Add Services Reference ซึ่งนั่นหมายถึงการอ้างถึง URL ของ Web Services ด้วยการ คลิกขวาที่ Reference เลือก Add Services Reference
![Windows Store App and Web Services & JSON (C#) Windows Store App and Web Services & JSON (C#)](https://www.thaicreate.com/upload/tutorial/windows-store-app-web-services-json-06.jpg?v=1001)
กรอก URL ของ Web Services ให้เลือก Go จากนั้นเราจะเห็นรายชื่อ Method ที่อยู่บน Web Services และขั้นตอนสุดท้ายให้ตั้งชื่อของ Web Services นี้ว่าชื่ออะไร เพื่อใช้สำหรับการอ้างอิงถึง
![Windows Store App and Web Services & JSON (C#) Windows Store App and Web Services & JSON (C#)](https://www.thaicreate.com/upload/tutorial/windows-store-app-web-services-json-07.jpg?v=1001)
รายการ Web Services ได้ถูก Add เข้ามาใน Project เรียบร้อยแล้ว โดยชื่อว่า "myWebServices"
หลังจากที่ได้ Web Services เรียบร้อยแล้ว ขั้นตอนถัดไปคือการเขียน C# เพื่อเรียกใช้งาน Web Services ซึ่งมีรูปแบบง่าย ๆ ดังนี้
สร้าง Class สำหรับ Mapping Column
public class myCustomer
{
public string CustomerID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string CountryCode { get; set; }
public string Budget { get; set; }
public string Used { get; set; }
}
ดึงค่า Result จาก Web Services ซึ่งจะได้ค่าเป็น JSON Code กลับมา
var client = new myWebServices.myWSVSoapClient();
var result = await client.getCustomerDataAsync();
string jsonData = result.Body.getCustomerDataResult;
การ Decode JSON และ Mapping กับ Column
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
ObservableCollection<myCustomer> list = new ObservableCollection<myCustomer>();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ObservableCollection<myCustomer>));
list = (ObservableCollection<myCustomer>)serializer.ReadObject(ms);
กำหนด DataSource ให้กับ Control เพื่อแสดงผลหรือ Binding
this.myListView.ItemsSource = list;
ลองมาดูตัวอย่างแบบเต็ม ๆ
Example การเขียน Windows Store Apps เพื่ออ่านค่า JSON จาก Web Services และนำค่าที่ได้ Binding กับ ListView
![Windows Store App and Web Services & JSON (C#) Windows Store App and Web Services & JSON (C#)](https://www.thaicreate.com/upload/tutorial/windows-store-app-web-services-json-07.jpg?v=1001)
ออกแบบหน้าจอประกอบด้วย Button และ ListView
MainPage.xaml
<Page
x:Class="WindowsStoreApps.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WindowsStoreApps"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button x:Name="btnSubmit" Content="Submit" HorizontalAlignment="Left" Margin="137,68,0,0" VerticalAlignment="Top" FontSize="20" Width="120" Click="btnSubmit_Click"/>
<ListView x:Name="myListView" HorizontalAlignment="Left" Height="386" Margin="140,165,0,0" VerticalAlignment="Top" Width="907">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<StackPanel Width="80">
<TextBlock Text="{Binding CustomerID}" TextWrapping="Wrap" FontSize="20" Foreground="#FFBFB9B9" Margin="5,0,0,0" FontFamily="Global User Interface"/>
</StackPanel>
<StackPanel Width="150">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" FontSize="20" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
</StackPanel>
<StackPanel Width="300">
<TextBlock Text="{Binding Email}" TextWrapping="Wrap" FontSize="20" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
</StackPanel>
<StackPanel Width="50">
<TextBlock Text="{Binding CountryCode}" TextWrapping="Wrap" FontSize="20" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
</StackPanel>
<StackPanel Width="100">
<TextBlock Text="{Binding Budget}" TextWrapping="Wrap" FontSize="20" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
</StackPanel>
<StackPanel Width="100">
<TextBlock Text="{Binding Used}" TextWrapping="Wrap" FontSize="20" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Page>
MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WindowsStoreApps.myWebServices;
using System.Xml.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Collections.ObjectModel;
using System.Text;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WindowsStoreApps
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
///
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
public class myCustomer
{
public string CustomerID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string CountryCode { get; set; }
public string Budget { get; set; }
public string Used { get; set; }
}
private async void btnSubmit_Click(object sender, RoutedEventArgs e)
{
var client = new myWebServices.myWSVSoapClient();
var result = await client.getCustomerDataAsync();
string jsonData = result.Body.getCustomerDataResult;
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
ObservableCollection<myCustomer> list = new ObservableCollection<myCustomer>();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ObservableCollection<myCustomer>));
list = (ObservableCollection<myCustomer>)serializer.ReadObject(ms);
this.myListView.ItemsSource = list;
}
}
}
![Windows Store App and Web Services & JSON (C#) Windows Store App and Web Services & JSON (C#)](https://www.thaicreate.com/upload/tutorial/windows-store-app-web-services-json-09.jpg?v=1001)
ค่าที่ได้ซึ่งถูก Decode ค่า JSON และ Binding แสดงผลบน ListViewแบบง่าย ๆ
.
|