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 > บทความจากสมาชิก > SignalR (Windows Form) : ตัวอย่างการรับส่งข้อมูลแบบ Real Time และการจัดเก็บลงใน Database



 
Clound SSD Virtual Server

SignalR (Windows Form) : ตัวอย่างการรับส่งข้อมูลแบบ Real Time และการจัดเก็บลงใน Database

SignalR (Windows Form) : ตัวอย่างการรับส่งข้อมูลแบบ Real Time และการจัดเก็บลงใน Database บทความนี้จะเป็นตัวอย่างการเขียน SignalR บน Windows Form Application ในการรับส่งข้อมูลแบบ Real Time รับข้อมูลจาก Input จำนวน 2 รายการคือ Name และ Email โดยข้อมูลที่รับเข้ามานั้น จะแสดงผลไปยัง Client อื่นๆ ในรูปแบบของ DataGridView ที่เปิดหน้าจอไว้ในขณะนั้นๆ ซึ่งข้อมูลในทุกๆ Client จะแสดงผลแบบ Real Time ตลอดเวลา เมื่อมีข้อมูลใหม่ ๆ เกิดขึ้น และในตัวอย่างนี้ยังมีการนำข้อมูลไปจัดเก็บลงใน Table ด้วย



SignalR(Win Form) : ตัวอย่างการรับส่งข้อมูลแบบ Real Time และการจัดเก็บลงใน Database


SignalR กับ Windows Form Application รับ-ส่ง ข้อมูลแบบ Real Time (VB.Net, C#)

ก่อนอื่นให้ทำความเข้าใจเกี่ยวกับ SignalR กับ Windows Form Application ในบทความก่อนหน้านี้ให้เข้าใจ ก่อนที่จะเริ่มในหัวข้อนี้
SignalR (Windows Form) Database

สร้าง Table ใหม่ชื่อว่า mytable มีคำสั่งดังนี้

CREATE TABLE [dbo].[mytable](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[name] [varchar](150) NULL,
	[email] [varchar](150) NULL,
 CONSTRAINT [PK_mytable] PRIMARY KEY CLUSTERED 
(
	[id] ASC
));
คำสั่งสำหรับสร้าง Table

SignalR (Windows Form) Database

Table ที่ได้

SignalR (Windows Form) Database

ตัวอย่างจัดเก็บข้อมูล

SignalR Server ในส่วนของ Server ตั้งชื่อ Hub ว่า MyHub








MyHub.cs (C#)
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Hosting;
using System.Collections.Generic;
using Owin;
using System;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;

namespace SignalRServer
{

    public class MyHub : Hub
    {
        public class mytable
        {
            public string name { get; set; }
            public string email { get; set; }
        }

        public void SaveData(string name, string email)
        {
            string json = string.Empty;

            SqlConnection objConn;
            SqlCommand objCmd;
            String strConnString, strSQL;
            SqlDataReader dtReader;

            strConnString = @"Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;";
            objConn = new System.Data.SqlClient.SqlConnection(strConnString);
            objConn.Open();

            // Insert New Data
            if (name != string.Empty && email != string.Empty)
            {
                strSQL = "INSERT INTO mytable (name, email) " +
                "VALUES ('" + name + "','" + email + "')";
                objCmd = new SqlCommand();
                objCmd.Connection = objConn;
                objCmd.CommandType = CommandType.Text;
                objCmd.CommandText = strSQL;
                objCmd.ExecuteNonQuery();
            }

            // Get Data
            strSQL = "SELECT * FROM mytable order by id asc";
            objCmd = new SqlCommand(strSQL, objConn);
            dtReader = objCmd.ExecuteReader();

            var ls = new List<mytable>();
            if(dtReader.HasRows)
            {
                while (dtReader.Read())
                {
                    ls.Add(new mytable { name = dtReader["name"].ToString(), email = dtReader["email"].ToString() });
                }
            }
            json = JsonConvert.SerializeObject(ls);

            dtReader.Close();
            objCmd = null;
            objConn.Close();
            objConn = null;


            Clients.All.displayData(json);
        }
        public override Task OnConnected()
        {
            Program.MainForm.WriteToConsole("Client connected: " + Context.ConnectionId);
            return base.OnConnected();
        }
        public override Task OnDisconnected(bool stopCalled)
        {
            Program.MainForm.WriteToConsole("Client disconnected: " + Context.ConnectionId);
            return base.OnDisconnected(true);
        }
    }

}
จาก Code จะเป็นคำสั่งง่ายๆ คือ รับค่า name และ email เพื่อ Insert ลงใน table จากนั้นส่งค่าทั้งหมดกลับไปทุก ๆ client ในรูปแบบของ JSON

SignalR Client ออกแบบ Form สำหรับ ส่ง-รับ ข้อมูล เพื่อแสดงผลบน DataGridView

SignalR (Windows Form) Database

ออกแบบ Form โดยเพิ่ม DataGridView เข้ามาสำหรับแสดงผลข้อมูล

ClientStart.cs (C#)
using Microsoft.AspNet.SignalR.Client;
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace SignalRClient
{
    public partial class ClientStart : Form
    {
        public class mytable
        {
            public string name { get; set; }
            public string email { get; set; }
        }

        private IHubProxy HubProxy { get; set; }
        const string ServerURI = "http://localhost:8080/signalr";
        private HubConnection Connection { get; set; }

        public ClientStart()
        {
            InitializeComponent();
        }

        private void ButtonConnect_Click(object sender, EventArgs e)
        {
            StatusText.Visible = true;
            StatusText.Text = "Connecting to server...";
            ConnectAsync();
        }
        private void ButtonSave_Click(object sender, EventArgs e)
        {
            HubProxy.Invoke("SaveData", TextBoxName.Text, TextBoxEmail.Text);
            TextBoxName.Text = String.Empty;
            TextBoxEmail.Text = String.Empty;
        }

        private async void ConnectAsync()
        {
            Connection = new HubConnection(ServerURI);
            Connection.Closed += Connection_Closed;
            HubProxy = Connection.CreateHubProxy("MyHub");
            HubProxy.On<string>("DisplayData", (json) =>
                this.Invoke((Action)(() =>
                    SetDataGridView(json)
                ))
            );
            try
            {
                await Connection.Start();
            }
            catch (HttpRequestException)
            {
                StatusText.Text = "Unable to connect to server: Start server before connecting clients.";
                return;
            }

            //Activate UI
            ButtonSave.Enabled = true;
            TextBoxName.Enabled = true;
            TextBoxEmail.Enabled = true;
            ButtonConnect.Enabled = false;
            RichTextBoxConsole.AppendText("Connected to server at " + ServerURI + Environment.NewLine);
            FirstLoad();
        }

        public void FirstLoad()
        {
            HubProxy.Invoke("SaveData", string.Empty, string.Empty);
        }

        public void SetDataGridView(string json) {

            var ls = JsonConvert.DeserializeObject<List<mytable>>(json);
            this.myDataGridView.DataSource = ls;
        }

        private void Connection_Closed()
        {
            //Deactivate chat UI; show login UI. 
            this.Invoke((Action)(() => ButtonSave.Enabled = false));
            this.Invoke((Action)(() => StatusText.Text = "You have been disconnected."));
        }

    }
}
จาก Code ของ Client มีรูปแบบการทำงานคือ รับค่า Name และ Email เพื่อส่งไปยัง Server และมีส่วนของ รับข้อมูลจาก Server




โดยรับจาก Server ในรุปแบบของ JSON และนำมา Parser ก่อนที่จะแสดงผลบน DataGridView

Result

SignalR (Windows Form) Database

รัน SignalR Server

SignalR (Windows Form) Database

จากนั้นเปิดตัว Client ขึ้นมา แล้วทำการเชื่อมต่อผ่านปุ่ม Connect

SignalR (Windows Form) Database

โดยแนะนำให้เปิดจากโฟเดอร์ Debug เพราะสามารถรันได้หลาย ๆ หน้าจอ

SignalR (Windows Form) Database

ทดสอบ Input ข้อมูลจาก Form ใด Form หนึ่ง

SignalR (Windows Form) Database

ทดสอบการ Input ข้อมูลจาก Form

SignalR (Windows Form) Database

จะเห็นว่าข้อมูลจะถูกแสดงบน DataGridView ของทุกๆ Form แบบ Real Time ในทันที

SignalR (Windows Form) Database

เมื่อดูใน Database และ Table จะเห็นว่าข้อมูลถูก Insert เข้ามา

Download Code

Query ข้อมูลจาก SQL Server เป็น JSON และการ Deserialize (Decode) ข้อมูล (VB.Net,C#)




.


   
Share
Bookmark.   

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