Windows Phone Edit Update data to Web Server |
Windows Phone Edit Update data to Web Server ตัวอย่างการเขียนโปรแกรมบน Windows Phone ในการแก้ไขและ udpate ข้อมูลต่าง ๆ ที่อยู่บน Web Server โดยใช้ WebClient และ UploadStringAsync เข้ามาจัดการในการ Request และ Response ข้อมูลระหว่าง Windows Phone (Client) และ PHP MySQL (Server) และการที่จะทำการแลกเปลี่ยนข้อมูลระหว่างกันนั้นในฝั่งของ Web Server จะต้องออกแบบโปรแกรมไว้สำหรับการ Update ข้อมูลต่าง ๆ ดังนี้
PHP Web Server
- โปรแกรมสำหรับแสดงข้อมูลทั้งหมด
- โปรแกรมสำหรับอ่านรายละเอียดข้อมูลของรายการที่เลือก
- โปรแกรมสำหรับบันทึการแก้ไขข้อมูล
member
CREATE TABLE `member` (
`MemberID` int(2) NOT NULL auto_increment,
`Username` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
`Name` varchar(50) NOT NULL,
`Tel` varchar(50) NOT NULL,
`Email` varchar(150) NOT NULL,
PRIMARY KEY (`MemberID`),
UNIQUE KEY `Username` (`Username`),
UNIQUE KEY `Email` (`Email`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `member`
--
INSERT INTO `member` VALUES (1, 'weerachai', 'weerachai@1', 'Weerachai Nukitram', '0819876107', '[email protected]');
INSERT INTO `member` VALUES (2, 'adisorn', 'adisorn@2', 'Adisorn Bunsong', '021978032', '[email protected]');
INSERT INTO `member` VALUES (3, 'surachai', 'surachai@3', 'Surachai Sirisart', '0876543210', '[email protected]');
INSERT INTO `member` VALUES (4, 'surapong', 'surapong@4', 'Surapong Siriphun', '0812345678', '[email protected]');
โครงสร้างตารางของ MySQL Database ที่งานอยู่บน Web Server
showAllData.php ไฟล์สำหรับแสดงข้อมูลทั้งหมด
<?php
$objConnect = mysql_connect("localhost","root","root");
$objDB = mysql_select_db("mydatabase");
$strSQL = "SELECT * FROM member WHERE 1 ORDER BY MemberID ASC ";
$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);
?>
getByMemberID.php ไฟล์สำหรับแสดงรายการที่เลือก
<?php
$objConnect = mysql_connect("localhost","root","root");
$objDB = mysql_select_db("mydatabase");
//$_POST["sMemberID"] = "1"; // for Sample
$strMemberID = $_POST["sMemberID"];
$strSQL = "SELECT * FROM member WHERE 1 AND MemberID = '".$strMemberID."' ";
$objQuery = mysql_query($strSQL);
$obResult = mysql_fetch_array($objQuery);
if($obResult)
{
$arr["MemberID"] = $obResult["MemberID"];
$arr["Username"] = $obResult["Username"];
$arr["Password"] = $obResult["Password"];
$arr["Name"] = $obResult["Name"];
$arr["Email"] = $obResult["Email"];
$arr["Tel"] = $obResult["Tel"];
}
mysql_close($objConnect);
/*** return JSON by MemberID ***/
/* Eg :
{"MemberID":"2",
"Username":"adisorn",
"Password":"adisorn@2",
"Name":"Adisorn Bunsong",
"Tel":"021978032",
"Email":"[email protected]"}
*/
echo json_encode($arr);
?>
updateData.php ไฟล์สำหรับบันทึกการแก้ไขข้อมูล
<?php
$objConnect = mysql_connect("localhost","root","root");
$objDB = mysql_select_db("mydatabase");
/*** for Sample
$_POST["sMemberID"] = "2";
$_POST["sPassword"] = "adisorn@2";
$_POST["sName"] = "Adisorn Bunsong";
$_POST["sEmail"] = "[email protected]";
$_POST["sTel"] = "021978032";
*/
$strMemberID = $_POST["sMemberID"];
$strPassword = $_POST["sPassword"];
$strName = $_POST["sName"];
$strEmail = $_POST["sEmail"];
$strTel = $_POST["sTel"];
/*** Check Email Exists ***/
$strSQL = "SELECT * FROM member WHERE Email = '".$strEmail."' AND MemberID != '".$strMemberID."' ";
$objQuery = mysql_query($strSQL);
$objResult = mysql_fetch_array($objQuery);
if($objResult)
{
echo "0|Email Exists!";
exit();
}
/*** Update ***/
$strSQL = " UPDATE member SET
Password = '".$strPassword."'
,Name = '".$strName."'
,Email = '".$strEmail."'
,Tel = '".$strTel."'
WHERE MemberID = '".$strMemberID."'
";
$objQuery = mysql_query($strSQL);
if(!$objQuery)
{
echo "0|Cannot save data!";
}
else
{
echo "1|";
}
/**
x|y
x = (0=Failed , 1=Complete)
y = Error Message
*/
mysql_close($objConnect);
?>
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="MemberList" SelectionChanged="MemberList_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Username}" 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 Tel}" TextWrapping="Wrap" Margin="5,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding Email}" 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/showAllData.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 MemberList_SelectionChanged(sender As Object, e As SelectionChangedEventArgs)
Dim data As Member = TryCast(TryCast(sender, ListBox).SelectedItem, Member)
'MessageBox.Show(data.MemberID)
NavigationService.Navigate(New Uri("/UpdatePage.xaml?sMemberID=" + data.MemberID, UriKind.Relative))
'Dim selectedItem As ListBoxItem = TryCast(Me.GalleryList.ItemContainerGenerator.ContainerFromItem(data), ListBoxItem)
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 Member)()
Dim serializer As New DataContractJsonSerializer(GetType(ObservableCollection(Of Member)))
list = DirectCast(serializer.ReadObject(ms), ObservableCollection(Of Member))
Dim myMember As New List(Of Member)
For Each cm As Member In list
Dim sMemberID As String = cm.MemberID.ToString()
Dim sUsername As String = cm.Username.ToString()
Dim sPassword As String = cm.Password.ToString()
Dim sName As String = cm.Name.ToString()
Dim sTel As String = cm.Tel.ToString()
Dim sEmail As String = cm.Email.ToString()
myMember.Add(New Member(sMemberID, sUsername, sPassword, sName, sTel, sEmail))
Next
Me.MemberList.ItemsSource = myMember
prog.IsVisible = False
End If
End Sub
<DataContract()> _
Public Class Member
<DataMember()> _
Public Property MemberID() As String
Get
Return m_MemberID
End Get
Set(value As String)
m_MemberID = value
End Set
End Property
<DataMember()> _
Public Property Username() As String
Get
Return m_Username
End Get
Set(value As String)
m_Username = value
End Set
End Property
<DataMember()> _
Public Property Password() As String
Get
Return m_Password
End Get
Set(value As String)
m_Password = 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 Tel() As String
Get
Return m_Tel
End Get
Set(value As String)
m_Tel = 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
Private m_MemberID As String
Private m_Username As String
Private m_Password As String
Private m_Name As String
Private m_tel As String
Private m_Email As String
Public Sub New(ByVal strMemberID As String,
ByVal strUsername As String,
ByVal strPassword As String,
ByVal strName As String,
ByVal strTel As String,
ByVal strEmail As String)
Me.MemberID = strMemberID
Me.Username = strUsername
Me.Password = strPassword
Me.Name = strName
Me.Tel = strTel
Me.Email = strEmail
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.Windows.Controls;
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/showAllData.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 MemberList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Member data = (sender as ListBox).SelectedItem as Member;
//MessageBox.Show(data.MemberID)
NavigationService.Navigate(new Uri("/UpdatePage.xaml?sMemberID=" + data.MemberID, UriKind.Relative));
//Dim selectedItem As ListBoxItem = TryCast(Me.GalleryList.ItemContainerGenerator.ContainerFromItem(data), ListBoxItem)
}
private void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
//Me.txtResult.Text = "Uploading.... " & e.ProgressPercentage & "%"
}
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<Member> list = new ObservableCollection<Member>();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ObservableCollection<Member>));
list = (ObservableCollection<Member>)serializer.ReadObject(ms);
List<Member> myMember = new List<Member>();
foreach (Member cm in list)
{
string sMemberID = cm.MemberID.ToString();
string sUsername = cm.Username.ToString();
string sPassword = cm.Password.ToString();
string sName = cm.Name.ToString();
string sTel = cm.Tel.ToString();
string sEmail = cm.Email.ToString();
myMember.Add(new Member(sMemberID, sUsername, sPassword, sName, sTel, sEmail));
}
this.MemberList.ItemsSource = myMember;
prog.IsVisible = false;
}
}
[DataContract]
public class Member
{
[DataMember]
public string MemberID { get; set; }
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Tel { get; set; }
[DataMember]
public string Email { get; set; }
public Member(string strMemberID, string strUsername, string strPassword
, string strName
, string strTel
, string strEmail)
{
this.MemberID = strMemberID;
this.Username = strUsername;
this.Password = strPassword;
this.Name = strName;
this.Tel = strTel;
this.Email = strEmail;
}
}
}
}
ในตัวอย่างนี้มี Code ทั้งที่เป็น VB.NET และ C# และสามารถดาวน์โหลด All Code ทั้งหมดได้จากส่วนท้ายของบทความ (Login สมาชิกก่อน)
UpdatePage.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" Margin="12,159,12,2" Grid.RowSpan="2">
<TextBlock Height="30" HorizontalAlignment="Left" Margin="28,45,0,0" Text="Username" VerticalAlignment="Top" FontSize="24" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="163,45,0,0" Name="txtUsername" Text="{Binding Username}" VerticalAlignment="Top" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="28,110,0,0" Text="Password" VerticalAlignment="Top" FontSize="24" />
<PasswordBox Height="72" HorizontalAlignment="Right" Margin="0,0,118,444" Name="txtPassword" Password="{Binding Password}" VerticalAlignment="Bottom" Width="187" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="28,182,0,0" Text="Confirm" VerticalAlignment="Top" FontSize="24" />
<PasswordBox Height="72" HorizontalAlignment="Left" Margin="150,157,0,0" Name="txtConPassword" Password="{Binding Password}" VerticalAlignment="Top" Width="188" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="28,240,0,0" Text="Name" VerticalAlignment="Top" FontSize="24" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="150,223,0,0" Name="txtName" Text="{Binding Name}" VerticalAlignment="Top" Width="306" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="28,312,0,0" Text="Tel" VerticalAlignment="Top" FontSize="24" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="150,293,0,0" Name="txtTel" Text="{Binding Tel}" VerticalAlignment="Top" Width="240" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="28,382,0,0" Text="Email" VerticalAlignment="Top" FontSize="24" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="150,359,0,0" Name="txtEmail" Text="{Binding Email}" VerticalAlignment="Top" Width="300" />
<Button Content="Save" Height="72" HorizontalAlignment="Left" Margin="146,437,0,0" Name="btnSave" Click="btnSave_Click" VerticalAlignment="Top" Width="160" />
</Grid>
</Grid>
UpdatePage.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 UpdatePage
Inherits PhoneApplicationPage
Public Sub New()
InitializeComponent()
AddHandler Loaded, AddressOf MainPage_Loaded
End Sub
Dim prog As ProgressIndicator
Dim strMemberID As String = ""
Private Sub MainPage_Loaded(sender As Object, e As System.Windows.RoutedEventArgs)
Dim url As String = "http://localhost/myphp/getByMemberID.php"
Dim uri As Uri = New Uri(url, UriKind.Absolute)
NavigationContext.QueryString.TryGetValue("sMemberID", strMemberID)
Dim postData As StringBuilder = New StringBuilder()
postData.AppendFormat("{0}={1}", "sMemberID", HttpUtility.UrlEncode(strMemberID))
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 myMember As Member = ReadToObject(e.Result.ToString())
Me.txtUsername.Text = myMember.Username.ToString()
Me.txtPassword.Password = myMember.Password.ToString()
Me.txtConPassword.Password = myMember.Password.ToString()
Me.txtName.Text = myMember.Name.ToString()
Me.txtTel.Text = myMember.Tel.ToString()
Me.txtEmail.Text = myMember.Email.ToString()
prog.IsVisible = False
End If
End Sub
Public Shared Function ReadToObject(ByVal json As String) As Member
Dim deserializedMember As New Member()
Dim ms As New MemoryStream(Encoding.UTF8.GetBytes(json))
Dim ser As New DataContractJsonSerializer(deserializedMember.GetType())
deserializedMember = TryCast(ser.ReadObject(ms), Member)
ms.Close()
Return deserializedMember
End Function
Private Sub btnSave_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
If Me.txtPassword.Password.ToString = "" Then
MessageBox.Show("Please input (Password)")
Exit Sub
End If
If Me.txtConPassword.Password.ToString = "" Then
MessageBox.Show("Please input (Confirm Username)")
Exit Sub
End If
If Me.txtPassword.Password.ToString <> Me.txtConPassword.Password.ToString Then
MessageBox.Show("Password Not Match!")
Exit Sub
End If
If Me.txtName.Text = "" Then
MessageBox.Show("Please input (Name)")
Exit Sub
End If
If Me.txtTel.Text = "" Then
MessageBox.Show("Please input (Tel)")
Exit Sub
End If
If Me.txtEmail.Text = "" Then
MessageBox.Show("Please input (Email)")
Exit Sub
End If
Dim url As String = "http://localhost/myphp/updateData.php"
Dim uri As Uri = New Uri(url, UriKind.Absolute)
Dim postData As StringBuilder = New StringBuilder()
postData.AppendFormat("{0}={1}", "sMemberID", HttpUtility.UrlEncode(strMemberID))
postData.AppendFormat("&{0}={1}", "sPassword", HttpUtility.UrlEncode(Me.txtPassword.Password.ToString))
postData.AppendFormat("&{0}={1}", "sName", HttpUtility.UrlEncode(Me.txtName.Text))
postData.AppendFormat("&{0}={1}", "sTel", HttpUtility.UrlEncode(Me.txtTel.Text))
postData.AppendFormat("&{0}={1}", "sEmail", HttpUtility.UrlEncode(Me.txtEmail.Text))
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_SaveUploadStringCompleted
AddHandler client.UploadProgressChanged, AddressOf client_SaveUploadProgressChanged
client.UploadStringAsync(uri, "POST", postData.ToString())
prog = New ProgressIndicator()
prog.IsVisible = True
prog.Text = "Connecting update to server...."
SystemTray.SetProgressIndicator(Me, prog)
End Sub
Private Sub client_SaveUploadStringCompleted(sender As Object, e As UploadStringCompletedEventArgs)
If e.Cancelled = False And e.Error Is Nothing Then
Dim result As String() = e.Result.ToString.Split("|")
'*** Check Status
If result(0).ToString = "0" Then
MessageBox.Show(result(1))
Else
MessageBox.Show("Update Data Successfully")
NavigationService.Navigate(New Uri("/MainPage.xaml", UriKind.Relative))
End If
prog.IsVisible = False
End If
End Sub
Private Sub client_SaveUploadProgressChanged(sender As Object, e As UploadProgressChangedEventArgs)
'Me.txtResult.Text = "Uploading.... " & e.ProgressPercentage & "%"
End Sub
<DataContract()> _
Public Class Member
<DataMember()> _
Public Property MemberID() As String
Get
Return m_MemberID
End Get
Set(value As String)
m_MemberID = value
End Set
End Property
<DataMember()> _
Public Property Username() As String
Get
Return m_Username
End Get
Set(value As String)
m_Username = value
End Set
End Property
<DataMember()> _
Public Property Password() As String
Get
Return m_Password
End Get
Set(value As String)
m_Password = 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 Tel() As String
Get
Return m_tel
End Get
Set(value As String)
m_tel = 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
Private m_MemberID As String
Private m_Username As String
Private m_Password As String
Private m_Name As String
Private m_tel As String
Private m_Email As String
Public Sub New()
End Sub
Public Sub New(ByVal strMemberID As String,
ByVal strUsername As String,
ByVal strPassword As String,
ByVal strName As String,
ByVal strTel As String,
ByVal strEmail As String)
Me.MemberID = strMemberID
Me.Username = strUsername
Me.Password = strPassword
Me.Name = strName
Me.Tel = strTel
Me.Email = strEmail
End Sub
End Class
End Class
UpdatePage.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.Windows.Controls;
using System.Net;
namespace PhoneApp
{
public partial class UpdatePage : PhoneApplicationPage
{
public UpdatePage()
{
InitializeComponent();
Loaded += MainPage_Loaded;
}
ProgressIndicator prog;
string strMemberID = "";
private void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
string url = "http://localhost/myphp/getByMemberID.php";
Uri uri = new Uri(url, UriKind.Absolute);
NavigationContext.QueryString.TryGetValue("sMemberID",out strMemberID);
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "sMemberID", HttpUtility.UrlEncode(strMemberID));
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)
{
//Me.txtResult.Text = "Uploading.... " & e.ProgressPercentage & "%"
}
private void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Cancelled == false && e.Error == null)
{
Member myMember = ReadToObject(e.Result.ToString());
this.txtUsername.Text = myMember.Username.ToString();
this.txtPassword.Password = myMember.Password.ToString();
this.txtConPassword.Password = myMember.Password.ToString();
this.txtName.Text = myMember.Name.ToString();
this.txtTel.Text = myMember.Tel.ToString();
this.txtEmail.Text = myMember.Email.ToString();
prog.IsVisible = false;
}
}
public static Member ReadToObject(string json)
{
Member deserializedMember = new Member();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedMember.GetType());
deserializedMember = ser.ReadObject(ms) as Member;
ms.Close();
return deserializedMember;
}
private void btnSave_Click(System.Object sender, System.Windows.RoutedEventArgs e)
{
if (string.IsNullOrEmpty(this.txtPassword.Password.ToString()))
{
MessageBox.Show("Please input (Password)");
return;
}
if (string.IsNullOrEmpty(this.txtConPassword.Password.ToString()))
{
MessageBox.Show("Please input (Confirm Username)");
return;
}
if (this.txtPassword.Password.ToString() != this.txtConPassword.Password.ToString())
{
MessageBox.Show("Password Not Match!");
return;
}
if (string.IsNullOrEmpty(this.txtName.Text))
{
MessageBox.Show("Please input (Name)");
return;
}
if (string.IsNullOrEmpty(this.txtTel.Text))
{
MessageBox.Show("Please input (Tel)");
return;
}
if (string.IsNullOrEmpty(this.txtEmail.Text))
{
MessageBox.Show("Please input (Email)");
return;
}
string url = "http://localhost/myphp/updateData.php";
Uri uri = new Uri(url, UriKind.Absolute);
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "sMemberID", HttpUtility.UrlEncode(strMemberID));
postData.AppendFormat("&{0}={1}", "sPassword", HttpUtility.UrlEncode(this.txtPassword.Password.ToString()));
postData.AppendFormat("&{0}={1}", "sName", HttpUtility.UrlEncode(this.txtName.Text));
postData.AppendFormat("&{0}={1}", "sTel", HttpUtility.UrlEncode(this.txtTel.Text));
postData.AppendFormat("&{0}={1}", "sEmail", HttpUtility.UrlEncode(this.txtEmail.Text));
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_SaveUploadStringCompleted;
client.UploadProgressChanged += client_SaveUploadProgressChanged;
client.UploadStringAsync(uri, "POST", postData.ToString());
prog = new ProgressIndicator();
prog.IsVisible = true;
prog.Text = "Connecting update to server....";
SystemTray.SetProgressIndicator(this, prog);
}
private void client_SaveUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Cancelled == false && e.Error == null)
{
string[] result = e.Result.ToString().Split('|');
//*** Check Status
if (result[0].ToString() == "0")
{
MessageBox.Show(result[1].ToString());
}
else
{
MessageBox.Show("Update Data Successfully");
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
prog.IsVisible = false;
}
}
private void client_SaveUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
//Me.txtResult.Text = "Uploading.... " & e.ProgressPercentage & "%"
}
}
[DataContract]
public class Member
{
[DataMember]
public string MemberID { get; set; }
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Tel { get; set; }
[DataMember]
public string Email { get; set; }
public Member()
{
}
public Member(string strMemberID, string strUsername, string strPassword
, string strName
, string strTel
, string strEmail)
{
this.MemberID = strMemberID;
this.Username = strUsername;
this.Password = strPassword;
this.Name = strName;
this.Tel = strTel;
this.Email = strEmail;
}
}
}
ในตัวอย่างนี้มี Code ทั้งที่เป็น VB.NET และ C# และสามารถดาวน์โหลด All Code ทั้งหมดได้จากส่วนท้ายของบทความ (Login สมาชิกก่อน)
Screenshot
แสดงข้อมูลทั้งหมดจาก Web Server
แสดงรายการที่เลือกเพื่อทำการแก้ไข
ทดสอบการแก้ไขข้อมูล
บันทึกการแก้ไข
เมื่อกลับมาหน้าแสดงรายการ จะเห็นว่าข้อมุลถูกแก้ไขเรียบร้อยแล้ว
บนฐานข้อมูลก็เช่นเดียวกัน ข้อมูลถูกแก้ไขเรียบร้อยแล้ว
.
|