|    
         
        
           
            |   | 
            
			 
   
     
        Check Login ผ่าน Web Service ตัวอย่างเว็บเซอร์วิส ตรวจสอบ Username และ Password (.NET)       | 
   
 
			
  Check Login ผ่าน Web Service ตัวอย่างเว็บเซอร์วิส ตรวจสอบ Username และ Password (.NET)  ช่วงนี้พยายามทำบทความเกี่ยวกับ Web Service ให้มีหลากหลายรูปแบบ เพราะในปัจจุบันคิดว่า Web Service มีความจำเป็นต่อการพัฒนาโปรแกรม ที่ทำงานระหว่าง Server กับ Client หรือ ระว่าง Server ได้ง่ายและสะดวกยิ่งขึ้น และยังเป็นแนวทางการพัฒนาโปรแกรมได้หลากหลาย  
 
สำหรับตัวอย่างนี้จะพูดถึง Web Service ที่ให้บริการตรวจสอบ Username และ Password โดย Server ที่ทำงานเป็น Web Service จะเปิดให้ Client ส่ง Username และ Password เข้าไปตรวจสอบ เมื่อ ข้อมูลถูกต้องจะทำการ return ค่ากลับมาเป็น true และถ้าไม่ถูกต้องจะทำการ return ค่าเป็น false  และทาง Client สามารถนำค่า true หรือ false ที่ได้นี่ ไปใช้กำหนดเงื่อนไขในการแสดงข้อความตอบรับของ User 
 
สำหรับ Database ใน Web Service ใช้ Database ของ SQL Server ประกอบด้วยตาราง member และฟิวด์หลัก ๆ ที่ใช้ในการตรวจสอบคือ Username และ Password และ Method ที่ชื่อว่า  CheckUserLogin ที่ทำหน้าที่รับค่าจาก Client แล้วนำมาตรวสอบใน Database ก่อนทำการ return ค่ากลับไป 
 
 
Screenshot 
 
  
 
ตรวจสอบข้อมูลจาก Web Service ผ่าน ASP.NET Web Application 
 
  
 
ตรวจสอบข้อมูลจาก Web Service ผ่าน Windows Form Application 
 
 
  
 
 
ฐานข้อมูล SQL Server ที่ถูกจัดเก็บไว้ใน Server ของ Web Service  
 
 
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].[member](
	[CustomerID] [varchar](4) NOT NULL,
	[Username] [varchar](50) NULL,
	[Password] [varchar](50) NULL,
	[Name] [varchar](50) NULL,
	[Email] [varchar](50) NULL,
	[CountryCode] [varchar](2) NULL,
	[Budget] [float] NULL,
	[Used] [float] NULL,
 CONSTRAINT [PK_member] 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 [member] VALUES ('C001','win', 'win001', 'Win Weerachai', '[email protected]', 'TH', 1000000, 600000);
INSERT INTO [member] VALUES ('C002','john', 'jhon002', 'John  Smith', '[email protected]', 'EN', 2000000, 800000);
INSERT INTO [member] VALUES ('C003','jame', 'jame003',  'Jame Born', '[email protected]', 'US', 3000000, 600000);
INSERT INTO [member] VALUES ('C004','chalee', 'chalee004', 'Chalee Angel', '[email protected]', 'US', 4000000, 100000);
 
 
นำ Query ไปรันเพื่อสร้าง Table และข้อมูล 
 
 
 
เริ่มต้นการสร้าง Web Service ฝั่ง Server 
 
  
 
 
คลิกวาที่ Project -> Add -> New Item... 
 
  
 
เลือก Web Service และ กำหนดชื่อเป็น userLogin.asmx 
 
userLogin.asmx ถูก Add เข้ามาใน Project คลิกเข้าไปที่ userLogin.asmx เพิ่มคำสั่งต่อไปนี้ 
 
- VB.NET 
 
userLogin.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 userLogin
    Inherits System.Web.Services.WebService
    <WebMethod()> _
       Public Function CheckUserLogin(ByVal strUser As String, _
        ByVal strPassword As String) As Boolean
        Dim objConn As New SqlConnection
        Dim objCmd As New SqlCommand
        Dim dtAdapter As SqlDataAdapter
        Dim dt As New 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;"
        objConn.ConnectionString = strConnString
        strSQL.Append(" SELECT * FROM member ")
        strSQL.Append(" WHERE [Username] = @sUsername ")
        strSQL.Append(" AND [Password] = @sPassword ")
        dtAdapter = New SqlDataAdapter(strSQL.ToString(), objConn)
        objCmd = dtAdapter.SelectCommand
        With objCmd
            .Parameters.Add("@sUsername", SqlDbType.VarChar).Value = strUser
            .Parameters.Add("@sPassword", SqlDbType.VarChar).Value = strPassword
        End With
        dtAdapter.Fill(dt)
        dtAdapter = Nothing
        objConn.Close()
        objConn = Nothing
        If dt.Rows.Count > 0 Then
            Return True
        Else
            Return False
        End If
    End Function
End Class
 
 
- C# 
 
userLogin.asmx.cs 
using Microsoft.VisualBasic;
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 userLogin : System.Web.Services.WebService
{
	[WebMethod()]
	public bool CheckUserLogin(string strUser, string strPassword)
	{
		SqlConnection objConn = new SqlConnection();
		SqlCommand objCmd = new SqlCommand();
		SqlDataAdapter dtAdapter = null;
		DataTable dt = new DataTable();
		string strConnString = null;
		StringBuilder strSQL = new StringBuilder();
		strConnString = "Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;";
		objConn.ConnectionString = strConnString;
		strSQL.Append(" SELECT * FROM member ");
		strSQL.Append(" WHERE [Username] = @sUsername ");
		strSQL.Append(" AND [Password] = @sPassword ");
		dtAdapter = new SqlDataAdapter(strSQL.ToString(), objConn);
		objCmd = dtAdapter.SelectCommand;
		var _with1 = objCmd;
		_with1.Parameters.Add("@sUsername", SqlDbType.VarChar).Value = strUser;
		_with1.Parameters.Add("@sPassword", SqlDbType.VarChar).Value = strPassword;
		dtAdapter.Fill(dt);
		dtAdapter = null;
		objConn.Close();
		objConn = null;
		if (dt.Rows.Count > 0) {
			return true;
		} else {
			return false;
		}
	}
}
 
 
บันทึกและทำการทดสอบการรัน Web Service 
 
  
 
http://localhost:5377/userLogin.asmx  
 
จะได้ URL ของ Web Service ดังรูป ซึ่งตอนนี้จะประกอบด้วย Method ที่ชื่อว่า CheckUserLogin 
 
 
  
 
ทดสอบ CheckUserLogin กรอก strUserID = win และ strPassword = win001 
 
  
 
ถ้าข้อมูลถูกต้อง Web Service จะมีการ return ค่าเป็น true และถ้าไม่ถูกต้องจะทำการ return ค่าเป็น false 
 
 
 
  
 
ตัวอย่างเรียก Web Service ด้วย ASP.NET 
 
  
 
สร้าง ASP.NET Web Application 
 
  
 
ในหน้า Web Form ให้ออกแบบหน้าจอด้วย Control ดังรูป 
 
  
 
คลิกขวาที่ Project เลือก Add Web Reference   
 
  
 
กรอก URL ของ Web Service และคลิกที่ Go และตั้งชื่อให้กับ Web reference name : เหมือนในรูปตัวอย่าง 
 
กลับมาที่ Web Form ให้คลิกสร้าง Event ที่ปุ่ม Button Login และใส่คำสั่งดังต่อไปนี้ 
 
- 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 btnLogin_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnLogin.Click
        Dim cLogin As New ChkLogin.userLogin
        If cLogin.CheckUserLogin(Me.txtUsername.Text, Me.txtPassword.Text) = True Then
            Me.lblStatus.Text = "ชื่อ User และ Password ถูกต้อง"
            Me.lblStatus.ForeColor = Drawing.Color.Green
        Else
            Me.lblStatus.Text = "ชื่อ User และ Password ไม่ถูกต้อง"
            Me.lblStatus.ForeColor = Drawing.Color.Red
        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 Page_Load(object sender, System.EventArgs e)
	{
	}
	protected void btnLogin_Click(object sender, EventArgs e)
	{
		ChkLogin.userLogin cLogin = new ChkLogin.userLogin();
		if (cLogin.CheckUserLogin(this.txtUsername.Text, this.txtPassword.Text) == true) {
			this.lblStatus.Text = "ชื่อ User และ Password ถูกต้อง";
			this.lblStatus.ForeColor = System.Drawing.Color.Green;
		} else {
			this.lblStatus.Text = "ชื่อ User และ Password ไม่ถูกต้อง";
			this.lblStatus.ForeColor = System.Drawing.Color.Red;
		}
	}
}
 
 
ทดสอบการทำงานของ Client เรียไปบยัง Web Service 
 
  
 
กรณีที่ Login ไม่ถูกต้อง 
 
  
 
กรณีที่ Login ถูกต้อง 
 
 
 
 
Windows Form เรียกใช้งาน Web Service 
 
  
 
สร้าง Windows Form Application เหมือนในรูป 
 
  
 
สร้าง Form และ Control เหมือนในตัวอย่าง 
 
  
 
คลิกขวาที่ Project เลือก Add Service Reference  
 
  
 
 
ใส่ URL ของ Web Service : http://localhost:5377/userLogin.asmx เลือก Go และ กำหนดชื่อ NameSpace ของ Web Service ตามรูปตัวอย่าง 
 
กลับมาที่ Form ให้สร้าง Event ที่ Button Login 
 
- VB 
 
Form1.vb 
Public Class Form1
    Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        Dim cLogin As New chkLogin.userLoginSoapClient
        If cLogin.CheckUserLogin(Me.txtUsername.Text, Me.txtPassword.Text) = True Then
            MsgBox("ชื่อ User และ Password ถูกต้อง")
        Else
            MsgBox("ชื่อ User และ Password ไม่ถูกต้อง")
        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 btnLogin_Click(System.Object sender, System.EventArgs e)
	{
		chkLogin.userLoginSoapClient cLogin = new chkLogin.userLoginSoapClient();
		if (cLogin.CheckUserLogin(this.txtUsername.Text, this.txtPassword.Text) == true) {
			Interaction.MsgBox("ชื่อ User และ Password ถูกต้อง");
		} else {
			Interaction.MsgBox("ชื่อ User และ Password ไม่ถูกต้อง");
		}
	}
}
 
 
ทดสอบการทำงาน 
 
Screenshot    
 
  
 
 
กรณีที่ Login ไม่ถูกต้อง   
 
  
 
กรณีที่ Login ถูกต้อง   
 
Download Code !!           
 
บทความอื่น ๆ ที่เกี่ยวข้อง 
Go to : ASP.NET การสร้าง Web Service และการเรียกใช้งาน Web Service ด้วย ASP.NET แบบ Step by Step 
Go to : ASP.NET กับ Web Service การเขียนเว็บเซอร์วิสรับ-ส่งข้อมูลจาก Database ผ่าน DataSet และ DataTable 
Go to : รบกวนขอความรู้เรื่อง dataset กับ Webservice หน่อยครับ 
Go to : ดึงข้อมูลจาก Webservice มาแสดงใน Webpage ยังไงครับ 
Go to : VB.NET รบกวนถามการเขียน Web Service ให้สามารถ Return ค่าในลักษณะของ DataSet ครับ      
		          
                 
    
                             					
			
              			             
                           
                             |   | 
                               | 
                             	
		                        | 
                            
                           
                             | 
 | 
                               | 
                              
                             			
 | 
           
         
           
          
            
              
                  
                     | 
                   
                  
                    |   | 
                    By :  | 
                    
                      
                      TC Admin	
                     | 
                   
                  
                    |   | 
                    Article :  | 
                    บทความเป็นการเขียนโดยสมาชิก หากมีปัญหาเรื่องลิขสิทธิ์ กรุณาแจ้งให้ทาง webmaster ทราบด้วยครับ  | 
                   
				  
                  
                    |   | 
                    Score Rating :  | 
                    
                                               | 
                   
                  
                    |   | 
                    Create Date :  | 
                    2012-05-03 | 
                   
				  
                  
                    |   | 
                    Download :  | 
                    
                       No files                     | 
                   
                | 
             
           
		
		
        
        
       | 
     
   
 
		  
         | 
		
          
		   
		  
              
      
     |