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

Registered : 109,027

HOME > บทความจากสมาชิก > ASP.NET กับ Web Service การเขียนเว็บเซอร์วิสรับ-ส่งข้อมูลจาก Database ผ่าน DataSet และ DataTable



 
Clound SSD Virtual Server

ASP.NET กับ Web Service การเขียนเว็บเซอร์วิสรับ-ส่งข้อมูลจาก Database ผ่าน DataSet และ DataTable

ASP.NET กับ Web Service การเขียนเว็บเซอร์วิสรับส่งข้อมูลจาก Web Service ไปยัง Client ที่ถูกจัดเก็บไว้ใน Database ผ่าน DataSet และ DataTable

Screenshot

ASP.NET Web Service DataSet and DataTable

ดึงข้อมูลจาก Web Service ผ่าน ASP.NET Web Application

ASP.NET Web Service DataSet and DataTable

ดึงข้อมูลจาก Web Service ผ่าน Windows Form Application

จากบทความก่อนหน้านี้เป็นพื้นฐานการเขียนโปรแกรม ASP.NET ทำงานร่วมกับ Web Service สำหรับบทความนี้จะเป็นภาคต่อ และเพิ่มในส่วนของการใช้ Web Service ให้บริการด้านข้อมูล โดย Web Service จะมีฐานข้อมูลลูกค้า ซึ่งจะเก็บไว้ใน Database ของ SQL Server และจะเปิดช่องทางให้ Client ทำการ Request ข้อมูลโดยส่งแค่ CustomerID เข้ามา และ Web Service จะทำการส่งรายละเอียดต่าง ๆ กลับไปยัง Client

ASP.NET Web Service DataSet and DataTable

ฐานข้อมูล SQL Server ที่ถูกจัดเก็บไว้ใน Web Service

จากรูป Screenshot จะเห็นว่าทาง Client ได้ทำการส่งแค่ CustomerID และ Web Service จะทำการส่งรายละเอียดต่าง ๆ ของลูกค้ากลับมายัง Client โดยในฝั่งของ Client อาจจะถูกเรียกใช้ด้วย ASP.NET Web Application หรือ Windows Form Application


ASP.NET Web Service DataSet and DataTable

รูปอธิบายการทำงาน


จารูป Client เรียกข้อมูลทำงานผ่าน ASP.NET และ ASP.NET เรียกรับส่งข้อมูลไปยัง Web Service ซึ่ง Web Service จะมีคลังข้อมูล SQL Server ไว้ส่งค่าต่าง ๆ กลับไปยัง Client








Database ของ SQL Server
USE [mydatabase]
GO
/****** Object:  Table [dbo].[customer]    Script Date: 05/01/2012 16:44:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[customer](
	[CustomerID] [varchar](4) NOT NULL,
	[Name] [varchar](50) NULL,
	[Email] [varchar](50) NULL,
	[CountryCode] [varchar](2) NULL,
	[Budget] [float] NULL,
	[Used] [float] NULL,
 CONSTRAINT [PK_customer] PRIMARY KEY CLUSTERED 
(
	[CustomerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

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


นำ Query ไปรันเพื่อสร้าง Table และข้อมูล




เริ่มต้นการสร้าง Web Service ฝั่ง Server

ASP.NET Web Service DataSet and DataTable

คลิกวาที่ Project -> Add -> New Item...

ASP.NET Web Service DataSet and DataTable

เลือก Web Service และ กำหนดชื่อเป็น getCustomerDetail.asmx

ASP.NET Web Service DataSet and DataTable

getCustomerDetail.asmx ถูก Add เข้ามาใน Project คลิกเข้าไปที่ getCustomerDetail.asmx เพิ่มคำสั่งต่อไปนี้

- VB.NET

getCustomerDetail.asmx.vb
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Data
Imports System.Data.SqlClient

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class getCustomerDetail
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function DetailCustomer(ByVal strCusID As String) As DataTable
        Dim objConn As New SqlConnection
        Dim objCmd As New SqlCommand
        Dim dtAdapter As New SqlDataAdapter

        Dim ds As New DataSet
        Dim dt As DataTable
        Dim strConnString As String
        Dim strSQL As New StringBuilder

        strConnString = "Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;"

        strSQL.Append(" SELECT * FROM customer ")
        strSQL.Append(" WHERE [CustomerID] = '" & strCusID & "' ")

        objConn.ConnectionString = strConnString
        With objCmd
            .Connection = objConn
            .CommandText = strSQL.ToString()
            .CommandType = CommandType.Text
        End With
        dtAdapter.SelectCommand = objCmd

        dtAdapter.Fill(ds)
        dt = ds.Tables(0)

        dtAdapter = Nothing
        objConn.Close()
        objConn = Nothing

        Return dt

    End Function

End Class


- C#

getCustomerDetail.asmx.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Data.SqlClient;

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// <System.Web.Script.Services.ScriptService()> _
[System.Web.Services.WebService(Namespace = "http://tempuri.org/")]
[System.Web.Services.WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class getCustomerDetail : System.Web.Services.WebService
{

	[WebMethod()]
	public DataTable DetailCustomer(string strCusID)
	{
		SqlConnection objConn = new SqlConnection();
		SqlCommand objCmd = new SqlCommand();
		SqlDataAdapter dtAdapter = new SqlDataAdapter();

		DataSet ds = new DataSet();
		DataTable dt = null;
		string strConnString = null;
		StringBuilder strSQL = new StringBuilder();

		strConnString = "Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;";

		strSQL.Append(" SELECT * FROM customer ");
		strSQL.Append(" WHERE [CustomerID] = '" + strCusID + "' ");

		objConn.ConnectionString = strConnString;
		var _with1 = objCmd;
		_with1.Connection = objConn;
		_with1.CommandText = strSQL.ToString();
		_with1.CommandType = CommandType.Text;
		dtAdapter.SelectCommand = objCmd;

		dtAdapter.Fill(ds);
		dt = ds.Tables[0];

		dtAdapter = null;
		objConn.Close();
		objConn = null;

		return dt;

	}

}


บันทึกและทำการทดสอบการรัน Web Service

ASP.NET Web Service DataSet and DataTable

http://localhost:5377/getCustomerDetail.asmx


จะได้ URL ของ Web Service ดังรูป ซึ่งตอนนี้จะประกอบด้วย Method ที่ชื่อว่า DetailCustomer


ASP.NET Web Service DataSet and DataTable

ทดสอบ DetailCustomer กรอก C001

ASP.NET Web Service DataSet and DataTable

สิ่งที่ Web Service ส่งค่ากลับ








XML
<?xml version="1.0" encoding="utf-8"?>
<DataTable xmlns="http://tempuri.org/">
  <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="Table" msdata:UseCurrentLocale="true">
      <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="Table">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="CustomerID" type="xs:string" minOccurs="0" />
                <xs:element name="Name" type="xs:string" minOccurs="0" />
                <xs:element name="Email" type="xs:string" minOccurs="0" />
                <xs:element name="CountryCode" type="xs:string" minOccurs="0" />
                <xs:element name="Budget" type="xs:double" minOccurs="0" />
                <xs:element name="Used" type="xs:double" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
    <NewDataSet xmlns="">
      <Table diffgr:id="Table1" msdata:rowOrder="0">
        <CustomerID>C001</CustomerID>
        <Name>Win Weerachai</Name>
        <Email>[email protected]</Email>
        <CountryCode>TH</CountryCode>
        <Budget>1000000</Budget>
        <Used>600000</Used>
      </Table>
    </NewDataSet>
  </diffgr:diffgram>
</DataTable>


เมื่อ View Source ในหน้า Web Browser จะเห็น XML ที่ถูกสร้างด้วย Web Service ดังรูป





ตัวอย่างเรียก Web Service ด้วย ASP.NET

ASP.NET Web Service DataSet and DataTable

สร้าง ASP.NET Web Application

ASP.NET Web Service DataSet and DataTable

ในหน้า Web Form ให้ออกแบบหน้าจอด้วย Control ดังรูป

ASP.NET Web Service DataSet and DataTable

คลิกขวาที่ Project เลือก Add Web Reference

ASP.NET Web Service DataSet and DataTable

กรอก URL ของ Web Service และคลิกที่ Go และตั้งชื่อให้กับ Web reference name : เหมือนในรูปตัวอย่าง

กลับมาที่ Web Form ให้คลิกสร้าง Event ที่ปุ่ม Button และใส่คำสั่งดังต่อไปนี้

- VB.NET

Default.aspx.vb
Partial Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub


    Protected Sub btnGet_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGet.Click

        Dim myCusDetail As New cusDetail.getCustomerDetail
        Dim dt As DataTable = myCusDetail.DetailCustomer(Me.txtCusID.Text)
        If dt.Rows.Count > 0 Then
            Me.lblCustomerID.Text = dt.Rows(0)("CustomerID").ToString()
            Me.lblName.Text = dt.Rows(0)("Name").ToString()
            Me.lblEmail.Text = dt.Rows(0)("Email").ToString()
            Me.lblCountryCode.Text = dt.Rows(0)("CountryCode").ToString()
            Me.lblBudget.Text = dt.Rows(0)("Budget").ToString()
            Me.lblUsed.Text = dt.Rows(0)("Used").ToString()
        End If

    End Sub

End Class


- C#

Default.aspx.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public partial class _Default : System.Web.UI.Page
{

	protected void btnGet_Click(object sender, EventArgs e)
	{
		cusDetail.getCustomerDetail myCusDetail = new cusDetail.getCustomerDetail();
		DataTable dt = myCusDetail.DetailCustomer(this.txtCusID.Text);
		if (dt.Rows.Count > 0) {
			this.lblCustomerID.Text = (string)dt.Rows[0]["CustomerID"];
			this.lblName.Text = (string)dt.Rows[0]["Name"];
			this.lblEmail.Text = (string)dt.Rows[0]["Email"];
			this.lblCountryCode.Text = (string)dt.Rows[0]["CountryCode"];
			this.lblBudget.Text = (string)dt.Rows[0]["Budget"].ToString();
			this.lblUsed.Text = (string)dt.Rows[0]["Used"].ToString();
		}

	}

}


ทดสอบการทำงานของ Client เรียไปบยัง Web Service

ASP.NET Web Service DataSet and DataTable

กรอกเพียง CustomerID ก็จะได้รายละเอียดซึ่งถูกส่งมาจาก Web Service




Windows Form เรียกใช้งาน Web Service



สร้าง Windows Form Application เหมือนในรูป

ASP.NET Web Service DataSet and DataTable

สร้าง Form และ Control เหมือนในตัวอย่าง



คลิกขวาที่ Project เลือก Add Service Reference

ASP.NET Web Service DataSet and DataTable

ใส่ URL ของ Web Service : http://localhost:5377/getCustomerDetail.asmx

กลับมาที่ Form ให้สร้าง Event ที่ Button

- VB

Form1.vb
Public Class Form1

    Private Sub btnGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGet.Click
        Dim myCusDetail As New cusDetail.getCustomerDetailSoapClient
        Dim dt As DataTable = myCusDetail.DetailCustomer(Me.txtCusID.Text)
        If dt.Rows.Count > 0 Then
            Me.lblCustomerID.Text = dt.Rows(0)("CustomerID").ToString()
            Me.lblName.Text = dt.Rows(0)("Name").ToString()
            Me.lblEmail.Text = dt.Rows(0)("Email").ToString()
            Me.lblCountryCode.Text = dt.Rows(0)("CountryCode").ToString()
            Me.lblBudget.Text = dt.Rows(0)("Budget").ToString()
            Me.lblUsed.Text = dt.Rows(0)("Used").ToString()
        End If
    End Sub

End Class


- C#

Form1.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class Form1
{

	private void btnGet_Click(System.Object sender, System.EventArgs e)
	{
		cusDetail.getCustomerDetailSoapClient myCusDetail = new cusDetail.getCustomerDetailSoapClient();
		DataTable dt = myCusDetail.DetailCustomer(this.txtCusID.Text);
		if (dt.Rows.Count > 0) {
			this.lblCustomerID.Text = (string)dt.Rows[0]["CustomerID"];
			this.lblName.Text = (string)dt.Rows[0]["Name"];
			this.lblEmail.Text = (string)dt.Rows[0]["Email"];
			this.lblCountryCode.Text = (string)dt.Rows[0]["CountryCode"];
			this.lblBudget.Text = (string)dt.Rows[0]["Budget"].ToString();
			this.lblUsed.Text = (string)dt.Rows[0]["Used"].ToString();
		}
	}

}


ทดสอบการทำงาน

Screenshot

ASP.NET Web Service DataSet and DataTable

กรอกเพียง CustomerID ก็จะได้รายละเอียดซึ่งถูกส่งมาจาก Web Service



เพิ่มเติมสำหรับ Windows Form Application

กรณีที่ต้องการเรียกใช้งาน Web Service ในส่วนของ Windows Form Application ให้เรียกแบบ Add Web Reference

Windows Form Application Add Web Reference

ตรง Add Service Reference จะมีปุ่มให้เลือก Advanced....

Windows Form Application Add Web Reference

คลิกเลือก Add Web Reference

Windows Form Application Add Web Reference

หน้าจอสำหรับ Add Web Reference ซึ่งสามารถเลือกรูปแบบและ คำสั่งจะเหมือนในส่วนของ ASP.NET Web Application


Download Code !!

บทความอื่น ๆ ที่เกี่ยวข้อง
Go to : ASP.NET การสร้าง Web Service และการเรียกใช้งาน Web Service ด้วย ASP.NET แบบ Step by Step
Go to : รบกวนขอความรู้เรื่อง dataset กับ Webservice หน่อยครับ
Go to : ดึงข้อมูลจาก Webservice มาแสดงใน Webpage ยังไงครับ
Go to : VB.NET รบกวนถามการเขียน Web Service ให้สามารถ Return ค่าในลักษณะของ DataSet ครับ


   
Share
Bookmark.   

  By : TC Admin
  Article : บทความเป็นการเขียนโดยสมาชิก หากมีปัญหาเรื่องลิขสิทธิ์ กรุณาแจ้งให้ทาง webmaster ทราบด้วยครับ
  Score Rating :
  Create Date : 2012-05-01
  Download : No files
Sponsored Links
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 01
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 อัตราราคา คลิกที่นี่