Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone



Clound SSD Virtual Server

Windows Phone Search Data from Web Server

Windows Phone Search Data from Web Server บทความและตัวอย่างการทำระบบค้นหา Search ข้อมูลบน Windows Phone App โดยข้อมูลที่ต้องการค้นหาจะถูกจัดเก็บไว้ที่ Web Server และในการค้นหาข้อมูลเหล่านี้ในฝั่งของ Web Server จะต้องออกแบบ Application ที่จะรองรับการ Request และในตัวอย่างนี้จะใช้ PHP ทำหน้าที่เป็นตัวรับ Request และ Response ข้อมูลกลับมายัง Windows Phone ในการค้นหาข้อมูลฝั่งของ Windows Phone จะต้องทำการส่ง Keyword ไปด้วย ซึ่งเราจะใช้ WebClient และ UploadStringAsync เข้ามาจัดการการรับส่ง Request ระหว่าง Client กับ Web Server ได้แบบง่าย ๆ

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);


โครงสร้างตารางของ MySQL Database ที่อยู่บน Web Server

Windows Phone Search Data in Web Server

searchData.php
<?php
	$objConnect = mysql_connect("localhost","root","root");
	$objDB = mysql_select_db("mydatabase");
	
	// $_POST["txtKeyword"] = "a"; // for Sample

	$strKeyword = $_POST["txtKeyword"];
	$strSQL = "SELECT * FROM customer WHERE 1 AND Name LIKE '%".$strKeyword."%'  ";

	$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 ที่ทำหน้าที่รับ Request จาก Windows Phone และส่งค่า Result กลับมายัง Windows Phone App


Windows Phone Project

MainPage.xaml

Windows Phone Search Data in Web Server

    <!--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}"/>
            <Grid>
            <TextBox Height="72" Name="txtKeyword" Text="" Margin="4,0,0,0" HorizontalAlignment="Left" Width="284" />
                <Button Content="Search" Height="72" HorizontalAlignment="Left" Margin="275,9,0,0" Name="btnSearch" Click="btnSearch_Click" VerticalAlignment="Top" Width="160" />
            </Grid>
        </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
Imports System.Xml.Linq
Imports System.Windows.Media.Imaging
Imports System.Xml
Imports System.IO.IsolatedStorage
Imports Microsoft.Phone.Tasks

Partial Public Class MainPage
    Inherits PhoneApplicationPage

    ' Constructor
    Public Sub New()
        InitializeComponent()
    End Sub

    Dim prog As ProgressIndicator

    Private Sub btnSearch_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)

        Dim url As String = "http://localhost/myphp/searchData.php"
        Dim uri As Uri = New Uri(url, UriKind.Absolute)

        Dim postData As StringBuilder = New StringBuilder()
        postData.AppendFormat("{0}={1}", "txtKeyword", HttpUtility.UrlEncode(Me.txtKeyword.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_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();
        }

        ProgressIndicator prog;

        private void btnSearch_Click(System.Object sender, System.Windows.RoutedEventArgs e)
        {
            string url = "http://localhost/myphp/searchData.php";
            Uri uri = new Uri(url, UriKind.Absolute);

            StringBuilder postData = new StringBuilder();
            postData.AppendFormat("{0}={1}", "txtKeyword", HttpUtility.UrlEncode(this.txtKeyword.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_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

Windows Phone Search Data in Web Server

แสดง Result ข้อมูลที่ทำการ Search ค้นหาจาก Web Server และการส่งค่ากลับมายัง Windows Phone

   
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2012-09-15 13:32:17 / 2017-03-25 21:58:05
  Download : Download  Windows Phone Search Data from Web Server
 Sponsored Links / Related

 
การสร้าง ApplicationBar (MenuItem) บน Windows Phone
Rating :

 
Dynamically Create Controls AddHandler (Event Handler) บน Windows Phone
Rating :

 
ตัวอย่างโปรแกรม Code Samples สำหรับ Windows Phone
Rating :

 
Windows Phone Posting Data to Web Server URL (Website)
Rating :

 
Windows Phone Show List Data from Web Server (Website)
Rating :

 
Windows Phone Edit Update data to Web Server
Rating :

 
Windows Phone Delete data in Web Server
Rating :

 
Windows Phone and BackgroundWorker
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 02
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่