با عرض سلام و درود.

یکی از دغدغه هایی که اکثر طراحان نرم افزار امروزه با آن روبرو هستند استفاده از داده های مستقر در یک هاست می باشد که یکی از بهترین روش ها استفاده از وب سرویس می باشد.

در پست زیر در نظر داریم از طریق یک وب سرویس نوشته شده به زبان php با استفاده از زبان سی شارپ به دیتابیس MySql متصل شویم.



در آموزش زیر ما فرض میکنیم که قرار است عملیات را در LocalHost انجام دهیم.



ابتدا یک دیتابیس با نام dbwebservice ایجاد و فایلی با نام تست ایجاد و کد زیر را در آن ذخیره و Import تا جدول مربوطه ایجاد گردد.

کد:
-- phpMyAdmin SQL Dump
-- version 4.6.6
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Aug 18, 2017 at 10:56 AM
-- Server version: 5.5.56-cll-lve
-- PHP Version: 5.6.30

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `ayaskc_webService`
--

-- --------------------------------------------------------

--
-- Table structure for table `tblStudent`
--

CREATE TABLE `tblStudent` (
  `stuName` varchar(20) COLLATE utf8_persian_ci NOT NULL,
  `stuFamil` varchar(20) COLLATE utf8_persian_ci NOT NULL,
  `stuTell` varchar(11) COLLATE utf8_persian_ci NOT NULL,
  `stuAddress` varchar(200) COLLATE utf8_persian_ci NOT NULL,
  `stuId` varchar(10) COLLATE utf8_persian_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci;

--
-- Dumping data for table `tblStudent`
--

INSERT INTO `tblStudent` (`stuName`, `stuFamil`, `stuTell`, `stuAddress`, `stuId`) VALUES
('ابوالفضل', 'عربی', '09380291826', 'بندرعباس - دانشگاه آزاد بندرعباس', '1'),
('وحید', 'محمد زاده', '09352148796', 'بندرعباس - دانشگاه سما', '2'),
('مهدی', 'منتظر', '09362145698', 'بندرعباس - دانشگاه سما', '3'),
('محسن', 'صفری', '09192563245', 'بندرعباس - دانشگاه آزاد', '4');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tblStudent`
--
ALTER TABLE `tblStudent`
  ADD PRIMARY KEY (`stuId`);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
سپس قطه کد زیر را با نام connector.php ذخیره نمایید.


کد:
<?php
header('Content-type: text/html');
define("APIKEY", "AbolfazlArabi");

function dbconnection() {

	
	$dbHost = "localhost";
	$dbUser = "root";
	$dbPass = "";
	$dbName = 'dbwebservice';
		$connect = new mysqli($dbHost,$dbUser,$dbPass,$dbName);
		mysqli_set_charset($connect , 'utf8');
 
    return $connect;
}


if(isset($_POST["apikey"]) && isset($_POST["stuId"]) && $_POST["func"]==1 ) {
    if($_POST["apikey"] == APIKEY) {
        $param = addslashes(htmlentities(trim($_POST["stuId"])));
        $connect = dbconnection();
        $sqlCommand = "SELECT * FROM tblStudent where stuId = '$param'";
        $result = $connect->query($sqlCommand);
		while($row = mysqli_fetch_array($result))
		{
            echo $row["stuName"].",".$row["stuFamil"].",".$row["stuTell"].",".$row["stuAddress"];
      }
    } else {
        echo "APIKEY invalid";
    }
} elseif(isset($_POST["apikey"]) &&  $_POST["func"]==2 ) {
    if($_POST["apikey"] == APIKEY) {

        $connect = dbconnection();
        $sqlCommand = "SELECT * FROM tblStudent";
        $result = $connect->query($sqlCommand);
		while($row = mysqli_fetch_array($result))
		{
            echo $row["stuName"].",".$row["stuFamil"].",".$row["stuTell"].",".$row["stuAddress"].",";
      }
    } else {
        echo "APIKEY invalid";
    }
}  elseif(isset($_POST["apikey"])&& isset($_POST["stuId"]) &&  $_POST["func"]==3 ) {
    if($_POST["apikey"] == APIKEY) {
         $stuId = trim($_POST["stuId"]);
         $stuName = trim($_POST["stuName"]);
         $stuFamil = trim($_POST["stuFamil"]);
         $stuTell = trim($_POST["stuTell"]);
         $stuAddress = trim($_POST["stuAddress"]);
        $connect = dbconnection();
        $sqlCommand = "insert into tblStudent(stuId,stuName,stuFamil,stuTell,stuAddress) values ('$stuId','$stuName','$stuFamil','$stuTell','$stuAddress')";
        $connect->query($sqlCommand);
	
    } else {
        echo "APIKEY invalid";
    }
}else {
    echo "Irandelphi Web Service.";
}

?>
حال کافی است ویژوال استودیو را باز نموده ویک پروژه با نام post_get_information ایجاد و سپس یک کلاس با نام MyWebRequest.cs ایجاد و کد زیر را در آن قرار می دهیم.

کد:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;


namespace post_get_information
{
    class MyWebRequest
    {
        private WebRequest request;
        private Stream dataStream;

        private string status;

        public String Status
        {
            get
            {
                return status;
            }
            set
            {
                status = value;
            }
        }

        public MyWebRequest(string url)
        {
            // Create a request using a URL that can receive a post.

            request = WebRequest.Create(url);
        }

        public MyWebRequest(string url, string method)
            : this(url)
        {

            if (method.Equals("GET") || method.Equals("POST"))
            {
                // Set the Method property of the request to POST.
                request.Method = method;
            }
            else
            {
                throw new Exception("Invalid Method Type");
            }
        }

        public MyWebRequest(string url, string method, string data)
            : this(url, method)
        {

            // Create POST data and convert it to a byte array.
            string postData = data;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";

            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;

            // Get the request stream.
            dataStream = request.GetRequestStream();

            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);

            // Close the Stream object.
            dataStream.Close();

        }

        public string GetResponse()
        {
            // Get the original response.
            WebResponse response = request.GetResponse();

            this.Status = ((HttpWebResponse)response).StatusDescription;

            // Get the stream containing all content returned by the requested server.
            dataStream = response.GetResponseStream();

            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);

            // Read the content fully up to the end.
            string responseFromServer = reader.ReadToEnd();

            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();

            return responseFromServer;
        }
    }
}
در ادامه بر روی فرم یک Button با نام Button1 و 5 تکست باکس با نام های زیر در روی فرم قرار می دهیم.



txtid

txtname

txtfamil

txttell

txtaddress



و سپس روی فرم کلیک و کدهای زیر را جایگزین کدهای Form1.cs می نماییم.

کد:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace post_get_information
{
    public partial class Form1 : Form
    {
      //  string urlWebService = "http://iaubnd.ir/webService/connector.php";//web
        string urlWebService = "http://localhost:90/webService/connector.php";//local
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                MyWebRequest myRequerst =new MyWebRequest (urlWebService, "POST","apikey=AbolfazlArabi&stuId="+txtid.Text + "&func=1");
                string s = myRequerst.GetResponse();
              
               // MessageBox.Show(s);
                string[] values = s.Split(',');
                for (int i = 0; i < values.Length ;i++)
                {
                    values[i] = values[i].Trim();
                    txtname.Text = values[0];
                    txtfamil.Text = values[1];
                    txttell.Text = values[2];
                    txtaddress.Text = values[3];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " <-خطای روبرو رخ داده است");
              
            }
        }

      

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
    }
}
چنانچه مایل باشید تمامی اطلاعات را که در وب سرویس ما با نام func2 در دسترس است در فرم خود داشته باشید ، ابتدا یک لیست باکس با نام listBox1 بر روی فرم قرار و سپس Button2 را اضافه و قطعه کد زیر را درClick Event مربوطه به جهت نمایش تمامی اطلاعات قرار می دهیم.

کد:
 private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                listBox1.Items.Clear();
                MyWebRequest myRequerst = new MyWebRequest(urlWebService, "POST", "apikey=AbolfazlArabi&func=2");
               
                string s = myRequerst.GetResponse();
               //  MessageBox.Show(s);
                string[] values = s.Split(',');

               
                for (int i = 0; i < values.Length-1; i=i+4)
                {
                    values[i] = values[i].Trim();
                    String str = "نام : " + values[i] + " نشان : " + values[i+1] + " تلفن : " + values[i+2] + " آدرس : " + values[i+3]+ " . ";
                    listBox1.Items.Add(str);
                    listBox1.Items.Add("____________________________________________________");

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " <-خطای روبرو رخ داده است");

            }
        }
همچنین چنانچه مایل به درج اطلاعات از سی شارپ به دیتابیس MySql هستید میبایست ابتدا یک Button بر روی فرم قرار داده و از کد زیر استفاده نمایید.
کد:
 private void button1_Click(object sender, EventArgs e)
        {
            try
            {


                MyWebRequest myRequerst = new MyWebRequest(urlWebService, "POST", "apikey=AbolfazlArabi&stuId=" + txtid.Text +"&stuName="+ txtname.Text + "&stuFamil=" + txtfamil.Text + "&stuTell=" + txttell.Text + "&stuAddress=" + txtaddress.Text + "&func=3");
             
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " <-خطای روبرو رخ داده است");

            }
        }
موفق و موید باشید.