Windows Phone Get Retrieving Data from Web Server (PHP & MySQL and JSON) |
Windows Phone Get Retrieving Data from Web Server (PHP & MySQL and JSON) ตัวอย่างการเขียน App บน Windows Phone เพื่ออ่านข้อมูลจาก Web Server ที่ทำงานด้วย PHP กับ MySQL และส่งค่ากลับมายัง Windows Phone ในรูปแบบของ JSON และเมื่อ Windows Phone ได้ค่า JSON ก็จะนำข้อมูลเหล่านั้นไปทำการ Binding Data ให้กับ ListBox เพื่อแสดงบนในหน้า Page ของ Application
Windows Phone and JSON from PHP &MySQL
Windows Phone and JSON
Web Server สร้างไฟล์ PHP กับ MySQL บนฝั่งของ Web Server
customer
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;
--
-- Dumping data for table `customer`
--
INSERT INTO `customer` VALUES ('C001', 'Win Weerachai', '[email protected]', 'TH', 1000000, 600000);
INSERT INTO `customer` VALUES ('C002', 'John Smith', '[email protected]', 'EN', 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);
โครงสร้างของ Database ของ MySQL
getJSON.php
<?php
$objConnect = mysql_connect("localhost","root","root");
$objDB = mysql_select_db("mydatabase");
$strSQL = "SELECT * FROM customer WHERE 1 ";
$objQuery = mysql_query($strSQL);
$intNumField = mysql_num_fields($objQuery);
$resultArray = array();
while($obResult = mysql_fetch_array($objQuery))
{
$arrCol = array();
for($i=0;$i<$intNumField;$i++)
{
$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
}
array_push($resultArray,$arrCol);
}
mysql_close($objConnect);
echo json_encode($resultArray);
?>
ไฟล์ php ที่ทำน้าที่อ่านข้อมูลจาก MySQL และส่งกลับในรูปแบบของ JSON
แสดง JSON เพื่อรันผ่าน Web Browser
Windows Phone Project
ทำการ Add Reference เข้ามาใน Project 2 ตัวคือ System.Servicemodel.Web และ System.Xml.Linq
MainPage.xaml
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Margin="0,0,-12,0" x:Name="CustomerList">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding CustomerID}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Margin="5,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding Email}" TextWrapping="Wrap" Margin="5,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding CountryCode}" TextWrapping="Wrap" Margin="5,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding Budget}" TextWrapping="Wrap" Margin="5,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding Used}" TextWrapping="Wrap" Margin="5,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
MainPage.xaml.vb (VB.NET)
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Json
Imports System.Collections.ObjectModel
Imports System.IO
Imports System.Text
Partial Public Class MainPage
Inherits PhoneApplicationPage
' Constructor
Public Sub New()
InitializeComponent()
AddHandler Loaded, AddressOf MainPage_Loaded
End Sub
Dim client As WebClient
Dim prog As ProgressIndicator
Private Sub MainPage_Loaded(sender As Object, e As System.Windows.RoutedEventArgs)
Dim url As String = "http://localhost/myphp/getJSON.php"
Dim uri As New Uri(url)
client = New WebClient()
client.AllowReadStreamBuffering = True
AddHandler client.DownloadStringCompleted, AddressOf client_DownloadStringCompleted
AddHandler client.DownloadProgressChanged, AddressOf client_DownloadProgressChanged
client.DownloadStringAsync(uri)
'*** SystemTray ProgressBar ***'
prog = New ProgressIndicator()
prog.IsVisible = True
prog.IsIndeterminate = True
prog.Text = "Downloading...."
SystemTray.SetProgressIndicator(Me, prog)
End Sub
Private Sub client_DownloadStringCompleted(sender As Object, e As DownloadStringCompletedEventArgs)
If e.Cancelled = False And e.Error Is Nothing Then
Dim ms As New MemoryStream(Encoding.UTF8.GetBytes(e.Result))
Dim list As New ObservableCollection(Of Customer)()
Dim serializer As New DataContractJsonSerializer(GetType(ObservableCollection(Of Customer)))
list = DirectCast(serializer.ReadObject(ms), ObservableCollection(Of Customer))
Dim myCustomer As New List(Of Customer)
For Each cm As Customer In list
Dim sCustomerID As String = cm.CustomerID.ToString()
Dim sName As String = cm.Name.ToString()
Dim sEmail As String = cm.Email.ToString()
Dim sCountryCode As String = cm.CountryCode.ToString()
Dim sBudget As String = cm.Budget.ToString()
Dim sUsed As String = cm.Used.ToString()
myCustomer.Add(New Customer(sCustomerID, sName, sEmail, sCountryCode, sBudget, sUsed))
Next
Me.CustomerList.ItemsSource = myCustomer
prog.IsVisible = False
End If
End Sub
Private Sub client_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
End Sub
<DataContract> _
Public Class Customer
<DataMember()> _
Public Property CustomerID() As String
Get
Return m_CustomerID
End Get
Set(value As String)
m_CustomerID = value
End Set
End Property
<DataMember()> _
Public Property Name() As String
Get
Return m_Name
End Get
Set(value As String)
m_Name = value
End Set
End Property
<DataMember()> _
Public Property Email() As String
Get
Return m_Email
End Get
Set(value As String)
m_Email = value
End Set
End Property
<DataMember()> _
Public Property CountryCode() As String
Get
Return m_CountryCode
End Get
Set(value As String)
m_CountryCode = value
End Set
End Property
<DataMember()> _
Public Property Budget() As String
Get
Return m_Budget
End Get
Set(value As String)
m_Budget = value
End Set
End Property
<DataMember()> _
Public Property Used() As String
Get
Return m_Used
End Get
Set(value As String)
m_Used = value
End Set
End Property
Private m_CustomerID As String
Private m_Name As String
Private m_Email As String
Private m_CountryCode As String
Private m_Budget As String
Private m_Used As String
Public Sub New(ByVal strCustomerID As String,
ByVal strName As String,
ByVal strEmail As String,
ByVal strCountryCode As String,
ByVal strBudget As String,
ByVal strUsed As String)
Me.CustomerID = strCustomerID
Me.Name = strName
Me.Email = strEmail
Me.CountryCode = strCountryCode
Me.Budget = strBudget
Me.Used = strUsed
End Sub
End Class
End Class
MainPage.xaml.cs (C#)
using System;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using Microsoft.Phone.Shell;
using System.Net;
namespace PhoneApp
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
Loaded += MainPage_Loaded;
}
WebClient client;
ProgressIndicator prog;
private void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
string url = "http://localhost/myphp/getJSON.php";
Uri uri = new Uri(url);
client = new WebClient();
client.AllowReadStreamBuffering = true;
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadStringAsync(uri);
//*** SystemTray ProgressBar ***'
prog = new ProgressIndicator();
prog.IsVisible = true;
prog.IsIndeterminate = true;
prog.Text = "Downloading....";
SystemTray.SetProgressIndicator(this, prog);
}
private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Cancelled == false & e.Error == null)
{
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(e.Result));
ObservableCollection<Customer> list = new ObservableCollection<Customer>();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ObservableCollection<Customer>));
list = (ObservableCollection<Customer>)serializer.ReadObject(ms);
List<Customer> myCustomer = new List<Customer>();
foreach (Customer cm in list)
{
string sCustomerID = cm.CustomerID.ToString();
string sName = cm.Name.ToString();
string sEmail = cm.Email.ToString();
string sCountryCode = cm.CountryCode.ToString();
string sBudget = cm.Budget.ToString();
string sUsed = cm.Used.ToString();
myCustomer.Add(new Customer(sCustomerID, sName, sEmail, sCountryCode, sBudget, sUsed));
}
this.CustomerList.ItemsSource = myCustomer;
prog.IsVisible = false;
}
}
private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
}
}
[DataContract]
public class Customer
{
[DataMember]
public string CustomerID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public string CountryCode { get; set; }
[DataMember]
public string Budget { get; set; }
[DataMember]
public string Used { get; set; }
public Customer(string strCustomerID, string strName, string strEmail
,string strCountryCode
, string strBudget
, string strUsed)
{
this.CustomerID = strCustomerID;
this.Name = strName;
this.Email = strEmail;
this.CountryCode = strCountryCode;
this.Budget = strBudget;
this.Used = strUsed;
}
}
}
ในตัวอย่างนี้มี Code ทั้งที่เป็น VB.NET และ C# และสามารถดาวน์โหลด All Code ทั้งหมดได้จากส่วนท้ายของบทความ (Login สมาชิกก่อน)
Screenshot
แสดงค่า JSON ที่ได้จาก Web Server และผ่านการ Binding ให้กับ ListBox
|