Windows Phone Show List Data from Web Server (Website) |
Windows Phone Show List Data from Web Server (Website) ตัวอย่างนี้จะเป็นการใช้ WebClient และ UploadStringAsync ในการทำการ Request ไปยัง Web Server (Website) และนำข้อมูลที่ได้ ที่ถูกส่งกลับมาจาก Web Server แสดงข้อมูลบนหน้า Page โดยในตัวอย่างนี้จะยกตัวอย่างการอ่านข้อมูลจากตาราง customer ที่เก็บอยู่ใน Web Server ที่ทำงานด้วย php กับ MySQL
Windows Phone Show List Data from Web Server
Web Server[/u]
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);
โครงสร้างตารางบน Web Server จะใช้ PHP ทำงานร่วมกับ MySQL
showData.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 บนฝั่ง Web Server
Windows Phone Project
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 prog As ProgressIndicator
Private Sub MainPage_Loaded(sender As Object, e As System.Windows.RoutedEventArgs)
Dim url As String = "http://localhost/myphp/showData.php"
Dim uri As Uri = New Uri(url, UriKind.Absolute)
Dim postData As StringBuilder = New StringBuilder()
postData.AppendFormat("{0}={1}", "NULL", HttpUtility.UrlEncode(""))
Dim client As WebClient
client = New WebClient()
client.Headers(HttpRequestHeader.ContentType) = "application/x-www-form-urlencoded"
client.Headers(HttpRequestHeader.ContentLength) = postData.Length.ToString()
AddHandler client.UploadStringCompleted, AddressOf client_UploadStringCompleted
AddHandler client.UploadProgressChanged, AddressOf client_UploadProgressChanged
client.UploadStringAsync(uri, "POST", postData.ToString())
prog = New ProgressIndicator()
prog.IsIndeterminate = True
prog.IsVisible = True
prog.Text = "Loading...."
SystemTray.SetProgressIndicator(Me, prog)
End Sub
Private Sub client_UploadProgressChanged(sender As Object, e As UploadProgressChangedEventArgs)
'Me.txtResult.Text = "Uploading.... " & e.ProgressPercentage & "%"
End Sub
Private Sub client_UploadStringCompleted(sender As Object, e As UploadStringCompletedEventArgs)
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
<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;
}
ProgressIndicator prog;
private void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
string url = "http://localhost/myphp/showData.php";
Uri uri = new Uri(url, UriKind.Absolute);
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "NULL", HttpUtility.UrlEncode(""));
WebClient client = default(WebClient);
client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
client.UploadStringCompleted += client_UploadStringCompleted;
client.UploadProgressChanged += client_UploadProgressChanged;
client.UploadStringAsync(uri, "POST", postData.ToString());
prog = new ProgressIndicator();
prog.IsIndeterminate = true;
prog.IsVisible = true;
prog.Text = "Loading....";
SystemTray.SetProgressIndicator(this, prog);
}
private void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
}
private void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs 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;
}
}
}
[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
แสดงข้อมูลที่ถูกส่งมาจาก Web Server ของ PHP และ MySQL
|