Windows Phone Login Username and Password (PHP & MySQL Web Server) |
Windows Phone Login Username and Password (PHP & MySQL Web Server) ตัวอย่างบทความการเขียน App บน Windows Phone และการทำระบบสมาชิก Login ข้อมูล Username และ Password โดยข้อมูลของสมาชิกจะถูกจัดเก็บไว้ที่ Web Server ผ่าน PHP กับ MySQL ที่จะทำหน้าที่แลกเปลี่ยนข้อมูลระหว่าง Windows Phone กับ Web Server ขั้นตอนการทำงานง่าย ๆ ก็คือ Windows Phone จะส่ง Username และ Password ไปตรวจสอบที่ฝั่งของ Web Server ซึ่งจะมี php ทำหน้าที่ตรวจสอบและส่งค่ากลับมายัง Windows Phone และหลังจากที่ Login ผ่านแล้ว จะมีหน้าจอ Page สำหรับให้สมาชิสามารถทำการแก้ไขอัพเดดข้อมูลของตัวเอง
Windows Phone Login Username and Password
ออกแบบ Web Server และหน้าจอ Page ของ Windows Phone ดังนี้
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
checkLogin.php ไฟล์สำหรับตรวจสอบการ Login
<?php
$objConnect = mysql_connect("localhost","root","root");
$objDB = mysql_select_db("mydatabase");
//$_POST["sUsername"] = "weerachai"; // for Sample
//$_POST["sPassword"] = "weerachai@1"; // for Sample
$strUsername = $_POST["sUsername"];
$strPassword = $_POST["sPassword"];
$strSQL = "SELECT * FROM member WHERE 1
AND Username = '".$strUsername."'
AND Password = '".$strPassword."'
";
$objQuery = mysql_query($strSQL);
$objResult = mysql_fetch_array($objQuery);
$intNumRows = mysql_num_rows($objQuery);
if($intNumRows==0)
{
echo "0|0|Incorrect Username and Password";
}
else
{
echo "1|".$objResult["MemberID"]."|";
}
/**
return
x|y|z
x // (0=Failed , 1=Complete)
y // MemberID
z // Error Message
*/
mysql_close($objConnect);
?>
getByMemberID.php ไฟล์สำหรับแสดงข้อมูลรายละเอียดของสมาชิกที่ Login
<?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 ไฟล์สำหรับ Update และแก้ไขข้อมูลส่วนตัว
<?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 ออกแบบ Page ขึ้นมา 2 หน้าคือ หน้าจอสำหรับ Login และ หน้าจอสำหรับการแก้ไข Update Profile ข้อมูลส่วนตัว
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" Margin="12,159,12,2" Grid.RowSpan="2">
<TextBlock Height="30" HorizontalAlignment="Left" Margin="28,45,0,0" Text="Login Username and Password" VerticalAlignment="Top" FontSize="24" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="28,110,0,0" Text="Password" VerticalAlignment="Top" FontSize="24" />
<TextBox Height="72" HorizontalAlignment="Right" Margin="0,0,70,444" Name="txtUsername" Text="" VerticalAlignment="Bottom" Width="235" />
<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="txtPassword" Password="" VerticalAlignment="Top" Width="236" />
<Button Content="Login" Height="72" HorizontalAlignment="Left" Margin="151,269,0,0" Name="btnLogin" Click="btnLogin_Click" VerticalAlignment="Top" Width="160" />
</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()
End Sub
Dim prog As ProgressIndicator
Private Sub btnLogin_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
Dim url As String = "http://localhost/myphp/checkLogin.php"
Dim uri As Uri = New Uri(url, UriKind.Absolute)
Dim postData As StringBuilder = New StringBuilder()
postData.AppendFormat("{0}={1}", "sUsername", HttpUtility.UrlEncode(Me.txtUsername.Text))
postData.AppendFormat("&{0}={1}", "sPassword", HttpUtility.UrlEncode(Me.txtPassword.Password.ToString))
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
prog.IsVisible = False
Dim result As String() = e.Result.ToString.Split("|")
Dim strStatus As String = result(0).ToString()
Dim strMemberID As String = result(1).ToString()
Dim strError As String = result(2).ToString()
If strStatus = "0" Then
MessageBox.Show(strError)
Else
NavigationService.Navigate(New Uri("/DetailPage.xaml?sMemberID=" & strMemberID, UriKind.Relative))
End If
End If
End Sub
End Class
MainPage.xaml.cs (C#)
using System;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Collections.Generic;
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();
}
ProgressIndicator prog;
private void btnLogin_Click(System.Object sender, System.Windows.RoutedEventArgs e)
{
string url = "http://localhost/myphp/checkLogin.php";
Uri uri = new Uri(url, UriKind.Absolute);
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "sUsername", HttpUtility.UrlEncode(this.txtUsername.Text));
postData.AppendFormat("&{0}={1}", "sPassword", HttpUtility.UrlEncode(this.txtPassword.Password.ToString()));
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)
{
prog.IsVisible = false;
string[] result = e.Result.ToString().Split('|');
string strStatus = result[0].ToString();
string strMemberID = result[1].ToString();
string strError = result[2].ToString();
if (strStatus == "0")
{
MessageBox.Show(strError);
}
else
{
NavigationService.Navigate(new Uri("/DetailPage.xaml?sMemberID=" + strMemberID, UriKind.Relative));
}
}
}
}
}
ในตัวอย่างนี้มี Code ทั้งที่เป็น VB.NET และ C# และสามารถดาวน์โหลด All Code ทั้งหมดได้จากส่วนท้ายของบทความ (Login สมาชิกก่อน)
DetailPage.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>
DetailPage.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 DetailPage
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 = "Connecting to server...."
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.IsIndeterminate = True
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
DetailPage.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 DetailPage : PhoneApplicationPage
{
public DetailPage()
{
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
หน้าจอ Page สำหรับ Login ซึ่งจะต้องกรอก Username และ Password
ในกรณีที่ Login ไม่ถูกต้อง
ในกรณีที่ Login ถูกต้อง จะแสดงข้อมูลและรายละเอียดของสมาชิกที่ Login เข้ามา
ในกรณีที่ทำการแก้ไข Update ข้อมูลส่วนตัว
..
|