Sp Rec

Материал из Wiki МИАЦ ВО
Перейти к навигации Перейти к поиску

Основной модуль

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using spsdksvr;
using spsdksw;
using SpRecord;
using System.Threading; 
using System.IO;
using System.Windows.Forms;
using namespase_mysql_connection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Net;
using System.Web;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Web.Script.Serialization;

namespace sprec
{
    public class myThread
        {
            public static Thread thread;

            public myThread(string name,int start_stop,int count_thread) //Конструктор получает имя функции
            {

                if (start_stop == 1)
                {
                    thread = new Thread(Program.ChannelListen);
                    thread.Name = name;
                    Console.WriteLine("thread.Name =" + thread.Name + ", " + thread.ManagedThreadId);
                    thread.IsBackground = true;
                    thread.Start();//передача параметра в поток
                }
                else if (start_stop == 2)
                {
                    thread.Abort();
                }

            }
            
/*            void func(object num)//Функция потока, передаем параметр
            {
                {
                    Console.WriteLine(Thread.CurrentThread.Name + " выводит " );
                    Thread.Sleep(0);
                }
                Console.WriteLine(Thread.CurrentThread.Name + " завершился");
            }
*/      
        
        }

    public class Connect_to_sprecord
    {
        public const int SPR_CHANNEL_INFO_CONVERSATIONACTIVE = 0x00000001; // WordBool //Запрашивается информация о наличии сеанса связи с удаленным абонентом. Value будет содержать TRUE, если сеанс связи начался, и FALSE, если нет. 
        public const int SPR_CHANNEL_INFO_PHONEFROM = 0x00000007;// BSTR  //  информация о телефоном номере вызывающего абонента. Value будет содержать строку с номером телефона. 
        public const int SPR_CHANNEL_INFO_SUBPHONEFROM = 0x00000008; // BSTR //  информация о дополнительном/внутреннем телефоном номере вызывающего абонента. Value будет содержать строку с номером телефона. 
        public const int SPR_CHANNEL_INFO_RINGFIRSTDATETIME = 0x0000000E; // DateTime
        public const int SPR_CHANNEL_INFO_PHONETO = 0x00000009; // BSTR //информация о телефоном номере вызываемого абонента. Value будет содержать строку с номером телефона. 
        public const int SPR_S_OK = 0x00000000;
        public const int SPR_CHANNEL_INFO_RECORDTYPE = 0x0000000B; // LONG // титп записи (вх, исх)
        public const int SPR_CHANNEL_INFO_FILENAME = 0x0000000C; // BSTR // имя файла
        public const int SPR_CHANNEL_INFO_CONVERSATIONLENG = 0x00000003;// LONG //  информация о времени с момента начала сеанса связи с удаленным абонентом. Value будет содержать время в секундах с момента начала сеанса связи. 
        public const int SPR_CHANNEL_INFO_RINGCOUNT = 0x00000010;  // LONG  // информация о количестве сигналов вызова
        public const int SPR_CHANNEL_INFO_CONVERSATIONDATETIME = 0x00000002; // DateTime // информация о времени начала сеанса связи с удаленным абонентом
        static string FileLogFileName = "connect_log.log";
        public Connect_to_sprecord(string ch_name, int start_stop) //Конструктор получает имя функции
        {

            if (start_stop == 1)
            {
                string ChannelName = ch_name;
                Console.WriteLine(ChannelName);
                string FileName = "";
                string TimeLine = "";
                string PhoneFrom = "";
                string SubPhoneFrom = "";
                string StartTime = "";
                bool GetLineState;
                bool GetWriting;
                int WaitMessage;
                string TypeCall = "";
                bool IsLineActive;
                object ChannelInfo = "";
                object IsLineActiveObj = "";
                int a = 0;

                SpRecordChannelClientW SPRecordChannel = new spsdksw.SpRecordChannelClientW();
                SPRecordChannel.Connect(ChannelName, 1, "", "");
                while (SPRecordChannel.Connected == true)
                {
                    if (Program.glo_status_int == 1) break;
                    //SPRecordChannel.GetLineState(out GetLineState);
                    //Console.WriteLine(GetLineState);
                    //SPRecordChannel.GetLineState(out GetWriting);
                    //Console.WriteLine(GetWriting);
                    //export_to_file(FileLogFileName, ChannelInfo.ToString());
                    //SPRecordChannel.GetReadyToCall(out IsLineActive);
                    SPRecordChannel.GetLineState(out IsLineActive);
                    if (IsLineActive != true) break;
                    //Console.WriteLine("IsLineActive1=" + IsLineActive);                
                    IsLineActive = true;
                    //while (IsLineActive == true)
                    //{
                    WaitMessage = SPRecordChannel.WaitMessage(-1);
                    if (WaitMessage == SPR_S_OK)
                    {
                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONACTIVE, out IsLineActiveObj);
                        IsLineActive = (bool)IsLineActiveObj;
                        if (IsLineActive == false) continue;
                        /*object Msg;
                        var eee = SPRecordChannel.PeekMessage(out Msg);
                        byte[] bytes = (byte[])Msg;
                        string str = System.Text.Encoding.ASCII.GetString(bytes);
                        export_to_file(FileLogFileName, str);*/
                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_FILENAME, out ChannelInfo);
                        FileName = ChannelInfo.ToString();
                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONLENG, out ChannelInfo);
                        TimeLine = ChannelInfo.ToString();
                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONDATETIME, out ChannelInfo);
                        StartTime = ChannelInfo.ToString();
                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_RECORDTYPE, out ChannelInfo);
                        TypeCall = ChannelInfo.ToString();
                        //export_to_file(FileLogFileName, ChannelInfo.ToString());
                        //SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONACTIVE, out ChannelInfo);
                        //export_to_file(FileLogFileName, ChannelInfo.ToString());
                        if ((int)TypeCall[0] == 2)
                        {
                            SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_PHONEFROM, out ChannelInfo);
                            PhoneFrom = ChannelInfo.ToString();
                            SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_SUBPHONEFROM, out ChannelInfo);
                            SubPhoneFrom = ChannelInfo.ToString();
                        }
                        System.Threading.Thread.Sleep(100); // пауза 0.1 сек.
                        Console.WriteLine("ChannelName=" + ChannelName + ", StartTime= " + StartTime + ", TimeLine=" + TimeLine + ", FileName=" + FileName + ", TypeCall= " + TypeCall[0] + ", PhoneFrom=" + PhoneFrom + ", SubPhoneFrom=" + SubPhoneFrom);
                        //glo_status1 = ChannelName + " " + TypeCall[0];
                        if (TypeCall[0] == 2)
                        {
                            TypeCall = "входящий, номер: " + PhoneFrom + "," + SubPhoneFrom;
                        }
                        else
                        {
                            TypeCall = "исходящий";
                        }
                        Program.glo_status1 = "Канал " + ChannelName + " , звонок " + TypeCall;
                    }
                    else
                    {
                        Program.export_to_file(FileLogFileName, FileName + " " + TimeLine + " " + PhoneFrom);
                    }
                    //export_to_file(FileLogFileName, WaitMessage.ToString());
                    //SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_PHONEFROM, out ChannelInfo);
                    //Console.WriteLine("Идет разговор ... ");
                    Console.WriteLine(WaitMessage);
                    System.Threading.Thread.Sleep(300); // пауза 0.1 сек.
                    //}
                }
                SPRecordChannel.Disconnect();
            }

        }

        /*            void func(object num)//Функция потока, передаем параметр
                    {
                        {
                            Console.WriteLine(Thread.CurrentThread.Name + " выводит " );
                            Thread.Sleep(0);
                        }
                        Console.WriteLine(Thread.CurrentThread.Name + " завершился");
                    }
        */

    }

    class Program
    {
        public const int SPR_CHANNEL_INFO_CONVERSATIONACTIVE = 0x00000001; // WordBool //Запрашивается информация о наличии сеанса связи с удаленным абонентом. Value будет содержать TRUE, если сеанс связи начался, и FALSE, если нет. 
        public const int SPR_CHANNEL_INFO_PHONEFROM = 0x00000007;// BSTR  //  информация о телефоном номере вызывающего абонента. Value будет содержать строку с номером телефона. 
        public const int SPR_CHANNEL_INFO_SUBPHONEFROM = 0x00000008; // BSTR //  информация о дополнительном/внутреннем телефоном номере вызывающего абонента. Value будет содержать строку с номером телефона. 
        public const int SPR_CHANNEL_INFO_RINGFIRSTDATETIME=0x0000000E; // DateTime
        public const int SPR_CHANNEL_INFO_PHONETO = 0x00000009; // BSTR //информация о телефоном номере вызываемого абонента. Value будет содержать строку с номером телефона. 
        public const int SPR_S_OK = 0x00000000;
        public const int SPR_CHANNEL_INFO_RECORDTYPE = 0x0000000B; // LONG // титп записи (вх, исх)
        public const int SPR_CHANNEL_INFO_FILENAME = 0x0000000C; // BSTR // имя файла
        public const int SPR_CHANNEL_INFO_CONVERSATIONLENG = 0x00000003;// LONG //  информация о времени с момента начала сеанса связи с удаленным абонентом. Value будет содержать время в секундах с момента начала сеанса связи. 
        public const int SPR_CHANNEL_INFO_RINGCOUNT = 0x00000010;  // LONG  // информация о количестве сигналов вызова
        public const int SPR_CHANNEL_INFO_CONVERSATIONDATETIME = 0x00000002; // DateTime // информация о времени начала сеанса связи с удаленным абонентом
        public const int SPR_CHANNEL_INFO_RING = 0x0000000D; // WordBool
        public const int SPR_CHANNEL_INFO_SUBPHONETO = 0x0000000A; // BSTR

        // max число каналов =4 
        public static string glo_status1 = " Ожидание запуска ...";
        public static int glo_status_int = 0;
        static string FileLogFileName = "connect_log.log";
        static void Main(string[] args)
        {
            /*string json1 ="{\"error\":[],\"data\":{\"status\":\"ok\",\"unicod\":42}}";
            var json2 ="{\"error\":{\"id\":1,\"text\":\"error autorization\"},\"data\":[]}";
          
            var json3 ="{\"response\":[{\"id\":269058571,\"first_name\":\"Name\",\"last_name\":\"LastName\",\"photo_50\":\"http://cs624717.vk.me/v624717571/21718/X8.jpg\"}]}";


            using (var reader = new StreamReader(json1))
            {
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                var objText = reader.ReadToEnd();
                var jsonData = (Dictionary<string, object>)js.DeserializeObject(json1);
                Console.WriteLine(jsonData);
                Console.WriteLine("end");
            }
            return;		*/
            // Подключаемся
            //SpRecordClient SPRecordClient = new spsdksvr.SpRecordClient();
            Form1 Forma = new Form1();
            Forma.ShowDialog();
            //Forma.SetLabelText(glo_status1);
            //Forma.Show();
            //Console.ReadKey();
        }

        class RootObject
        {
            public Item1 error { get; set; }
            public Item2 data { get; set; }
        }
        class Item1
        {
            public string id { get; set; }
            public string text { get; set; }
        }
        class Item2
        {
            public string status { get; set; }
            public string unicod { get; set; }
        }
        public static void Connect_to_stop()
        {
            try
            {
                glo_status_int = 1;
            }
            catch (ThreadAbortException)
            {
                    Console.WriteLine("Поток не прерван ");
            }
        }
        public static void Connect_to_asp()
        {
            //MessageBox.Show("hello pr");
            try
            {
                glo_status_int = 0;
                SpRecordClient SPRecordClient = new SpRecordClient();
                Console.WriteLine("Connect_to_asp =");
                var Connect = SPRecordClient.Connect(0, "", "");
                // Получаем список каналов
                string ChannelList = "";
                string FileLogFileName = "connect_log.log";
                var Channel = SPRecordClient.GetChannelNames(out ChannelList, 1);
                Char delimiter = '|';
                String[] substrings = ChannelList.Split(delimiter);
                //export_to_file(FileLogFileName, "1 start");
                //Program p = new Program();
                int i = 0;
                foreach (var substring in substrings)
                {
                    i += 1;
                    Console.WriteLine("substring " + substring);
                    //myThread t1 = new myThread(substring, 1, i);
                    switch (i)
                    {
                        case 1:
                            //Connect_to_sprecord t1 = new Connect_to_sprecord(substring, 1);
                            myThread t1 = new myThread(substring, 1, i);
                            break;
                        case 2:
                            //Connect_to_sprecord t2 = new Connect_to_sprecord(substring, 1);
                            myThread t2= new myThread(substring, 1, i);
                            break;
                        case 3:
                            //Connect_to_sprecord t3 = new Connect_to_sprecord(substring, 1);
                            myThread t3 = new myThread(substring, 1, i);
                            break;
                        case 4:
                            myThread t4 = new myThread(substring, 1, i);
                            //Connect_to_sprecord t4 = new Connect_to_sprecord(substring, 1);
                            break;
                    }
                    //Console.ReadKey();
                    System.Threading.Thread.Sleep(300); // пауза 0.1 сек. для инициализации
                    Console.WriteLine("pause ");
                }
                SPRecordClient.Disconnect();
                //var devName = SPRecordClient.GetDeviceNames;
                Console.WriteLine("pause ");
            }
            catch (ThreadAbortException exc)
            {
                if ((int)exc.ExceptionState == 0)
                {
                    Console.WriteLine("Прерывание отменено! Код завершения: "
                        + exc.ExceptionState);
                    Thread.ResetAbort();
                }
                else
                    Console.WriteLine("Поток прерван, код завершения "
                        + exc.ExceptionState);
            }
        }
        public static void ChannelListen()
        {
            string ChannelName = myThread.thread.Name;
            int id_calldetails = 0;
            Console.WriteLine(ChannelName);
            string current_FileName = "";
            string FileName = "";
            int priznak_incomin_ring = 0;
            string TimeLine = "";
            string PhoneFrom = "";
            string SubPhoneFrom = "";
            DateTime StartTime;
            int ring_count = 0; 
            bool GetLineState;
            bool GetWriting;
            int WaitMessage;
            int TypeCall = 0;
            string TypeCall_str = "";
            bool IsLineActive;
            object ChannelInfo = "";
            object IsLineActiveObj = "";
            bool incoming_ring;
            object Is_incoming_ring = "";

            SpRecordChannelClientW SPRecordChannel = new spsdksw.SpRecordChannelClientW();
            SPRecordChannel.Connect(ChannelName, 1, "", "");
            current_FileName = "";
            priznak_incomin_ring = 0;
            while (SPRecordChannel.Connected == true)
            {
                if (glo_status_int==1) break;
                //SPRecordChannel.GetLineState(out GetLineState);
                //Console.WriteLine(GetLineState);
                //SPRecordChannel.GetLineState(out GetWriting);
                //Console.WriteLine(GetWriting);
                //export_to_file(FileLogFileName, ChannelInfo.ToString());
                    //SPRecordChannel.GetReadyToCall(out IsLineActive);
                SPRecordChannel.GetLineState(out IsLineActive);
                if (IsLineActive != true) break;
                //Console.WriteLine("IsLineActive1=" + IsLineActive);                
                 IsLineActive = true;
                //while (IsLineActive == true)
                    //{
                        WaitMessage = SPRecordChannel.WaitMessage(-1);
                        if (WaitMessage == SPR_S_OK)
                        {
                            SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONACTIVE, out IsLineActiveObj);
                            IsLineActive = (bool)IsLineActiveObj;
                            SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_RING, out Is_incoming_ring);
                            incoming_ring = (bool)Is_incoming_ring;
                            if (incoming_ring == true)
                            {
                                if (current_FileName == "" & priznak_incomin_ring == 0)
                                {
                                    priznak_incomin_ring = 1;       // идет звонок оператору
                                }
                                //if (current_FileName != FileName)
                                SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_RINGCOUNT, out ChannelInfo);
                                if ((int)ChannelInfo > ring_count)
                                {
                                    ring_count = (int)ChannelInfo;
                                    Console.WriteLine("ring_count=" + ring_count);
                                }
                                if (priznak_incomin_ring == 1)
                                {
                                    ring_count = 0;
                                    priznak_incomin_ring = 2; // статус - снята трубка
                                    SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_RINGFIRSTDATETIME, out ChannelInfo);
                                    StartTime = ((DateTime)ChannelInfo);
                                    //StartTime = StartTime.Date.ToString("yyyy-MM-dd") + " " + StartTime.Hour+":"StartTime.Minute+":"+StartTime.Second;
                                    SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_RECORDTYPE, out ChannelInfo);
                                    TypeCall = (int)ChannelInfo;
                                    //if (TypeCall != 2)
                                    {
                                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_PHONEFROM, out ChannelInfo);
                                        PhoneFrom = (string)ChannelInfo;
                                        SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_SUBPHONEFROM, out ChannelInfo);
                                        SubPhoneFrom = (string)ChannelInfo;
                                    }
                                    TypeCall_str = "входящий, номер: " + PhoneFrom + ", " + SubPhoneFrom;
                                    List<List<string>> arr = namespase_mysql_connection.MySql.mysql_connect_read_status_file(Form1.Srv, Form1.DataBase, Form1.User, Form1.Passwrd, 0, StartTime.Date.ToString("yyyy-MM-dd") + " "+StartTime.Hour+":"+StartTime.Minute+":"+StartTime.Second,"", ChannelName[(ChannelName.Length - 1)], PhoneFrom,0,"",1,0,"");
                                    Console.WriteLine("arr.Count=" + arr.Count);
                                    StringBuilder builder = new StringBuilder();
                                    if (arr.Count == 0)
                                        Console.WriteLine("ошибка получения max(id) из таблицы calldetails");
                                    else
                                    {
                                        for (int i = 0; i <= arr.Count - 1; i++)
                                        {
                                            if (arr[i][0] == "0" | arr[i][0] == "Error")
                                            {
                                                break;
                                            }
                                            else
                                            {
                                                id_calldetails = Int32.Parse(arr[i][0]);
                                                string response = send_id("add_popup", id_calldetails, Int32.Parse((ChannelName[(ChannelName.Length - 1)]).ToString()), PhoneFrom);
                                                Console.WriteLine(response);
                                                Console.WriteLine("id=" + arr[i][0] + " StartTime=" + " " + StartTime + "ChannelName[(ChannelName.Length - 1)]=" + ChannelName[(ChannelName.Length - 1)] + "PhoneFrom=" + PhoneFrom + "SubPhoneFrom=" + SubPhoneFrom);
                                                break;
                                            }
                                        }
                                    }

                                }
                            }
                            else
                            {
                                /*if (current_FileName == "")
                                {
                                    priznak_incomin_ring = 0;
                                    Console.WriteLine("dozvon end");
                                }*/
/*                                if (current_FileName == FileName && priznak_incomin_ring == 2)
                                {
                                    Console.WriteLine("FileName=" + FileName+ "Call end");
                                    priznak_incomin_ring = 0;
                                }*/
                            }
                            if (IsLineActive == false)
                            {
                                if (current_FileName != "")
                                {
                                    if (priznak_incomin_ring == 2) TypeCall = 2;    // out call
                                    if (priznak_incomin_ring == 0) TypeCall = 1; // in call
                                    List<List<string>> arr = namespase_mysql_connection.MySql.mysql_connect_read_status_file(Form1.Srv, Form1.DataBase, Form1.User, Form1.Passwrd, 2, "", DateTime.Now.ToString("yyyy-MM-dd") + " " + DateTime.Now.ToString("HH:mm:ss"), 'c', "", 1, "", TypeCall, id_calldetails,"");
                                    Console.WriteLine("FileName=" + FileName + "Call end");
                                    current_FileName = "";
                                    TypeCall_str = " Ожидание вызова ...";
                                    glo_status1 =  TypeCall_str;
                                }
                                continue;
                            }
                            if (priznak_incomin_ring == 2 & TypeCall != 2)
                            {
                                //сюда вставить продолжительность звонка
                                SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_FILENAME, out ChannelInfo);
                                FileName = ChannelInfo.ToString();
                                List<List<string>> arr = namespase_mysql_connection.MySql.mysql_connect_read_status_file(Form1.Srv, Form1.DataBase, Form1.User, Form1.Passwrd, 1, "", "", 'c', "", ring_count, FileName, TypeCall, id_calldetails,"");
                                Console.WriteLine("FileName=" + FileName + " ring_count=" + ring_count + " priznak_incomin_ring = 2;");
                            }

  /*object Msg;
                            var eee = SPRecordChannel.PeekMessage(out Msg);
                            byte[] bytes = (byte[])Msg;
                            string str = System.Text.Encoding.ASCII.GetString(bytes);
                            export_to_file(FileLogFileName, str);*/
                            SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_FILENAME, out ChannelInfo);
                            FileName = ChannelInfo.ToString();
                            if (current_FileName != FileName)
                            {
                                current_FileName = FileName;
                                SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONLENG, out ChannelInfo);
                                TimeLine = ChannelInfo.ToString();
                                SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONDATETIME, out ChannelInfo);
                                StartTime = (DateTime)ChannelInfo;
                                SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_RECORDTYPE, out ChannelInfo);
                                TypeCall = (int)ChannelInfo;
                                //export_to_file(FileLogFileName, ChannelInfo.ToString());
                                //SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_CONVERSATIONACTIVE, out ChannelInfo);
                                //export_to_file(FileLogFileName, ChannelInfo.ToString());
                                if (priznak_incomin_ring == 0)
                                {
                                    //SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_SUBPHONETO, out ChannelInfo);
                                    //PhoneFrom = ChannelInfo.ToString();
                                    List<List<string>> arr = namespase_mysql_connection.MySql.mysql_connect_read_status_file(Form1.Srv, Form1.DataBase, Form1.User, Form1.Passwrd, 0, DateTime.Now.ToString("yyyy-MM-dd") + " " + DateTime.Now.ToString("HH:mm:ss"), "", ChannelName[(ChannelName.Length - 1)], PhoneFrom, 0, FileName, 2, 0,"");
                                    Console.WriteLine("arr.Count=" + arr.Count);
                                    StringBuilder builder = new StringBuilder();
                                    if (arr.Count == 0)
                                    {
                                        MessageBox.Show("ошибка получения max(id) из таблицы calldetails");
                                    }
                                    else
                                    {
                                        for (int i = 0; i <= arr.Count - 1; i++)
                                        {
                                            if (arr[i][0] == "0" | arr[i][0] == "Error")
                                            {
                                                break;
                                            }
                                            else
                                            {
                                                id_calldetails = Int32.Parse(arr[i][0]);
                                                Console.WriteLine("id=" + arr[i][0] + " StartTime=" + " " + StartTime + "ChannelName[(ChannelName.Length - 1)]=" + ChannelName[(ChannelName.Length - 1)] + "PhoneFrom=" + PhoneFrom + "SubPhoneFrom=" + SubPhoneFrom);
                                                break;
                                            }
                                        }
                                    }
                                }
                                System.Threading.Thread.Sleep(100); // пауза 0.1 сек.
                                //Console.WriteLine("ChannelName1=" + ChannelName + ", StartTime= " + StartTime + ", TimeLine=" + TimeLine + ", FileName=" + FileName + ", TypeCall= " + TypeCall + ", PhoneFrom=" + PhoneFrom + ", SubPhoneFrom=" + SubPhoneFrom + "ChannelName=" + ChannelName[(ChannelName.Length - 1)] + "ring_count=" + ring_count);
                                if (priznak_incomin_ring == 2)
                                {
                                    TypeCall_str = "входящий, номер: " + PhoneFrom + ", " + SubPhoneFrom;
                                }
                                else
                                {
                                    TypeCall_str = "исходящий";
                                }
                                glo_status1 = "Канал " + ChannelName + " , звонок " + TypeCall_str;
                            }
                            else
                            {
                                priznak_incomin_ring = 0;
                            }
                        }
                        else
                        {
                            current_FileName = "";
                            priznak_incomin_ring = 0;
                            ring_count = 0;
                            export_to_file(FileLogFileName, FileName + " " + TimeLine + " " + PhoneFrom);
                            //continue;
                        }
                     //export_to_file(FileLogFileName, WaitMessage.ToString());
                    //SPRecordChannel.GetInfo(SPR_CHANNEL_INFO_PHONEFROM, out ChannelInfo);
                    //Console.WriteLine("Идет разговор ... ");
                    //Console.WriteLine(WaitMessage);
                    System.Threading.Thread.Sleep(300); // пауза 0.1 сек.
                //}
            }
            SPRecordChannel.Disconnect();
        }

        public static string CreateMD5(string input)
        {
            // Use input string to calculate MD5 hash
            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                // Convert the byte array to hexadecimal string
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2"));
                }
                return sb.ToString();
            }
        }
        public class Request_type
        {
            public string type { get; set; }
            public int unicod { get; set; }
            public int chanel { get; set; }
            public string phone { get; set; }

            // public Dictionary<string, string> data { get; set; }
        }
        
        [Serializable]
        public class Response_type
        {
            public Dictionary<string, Object> error { get; set; }

            public Dictionary<string, Object> data { get; set; }
        }
        [Serializable]
        public class ErrorList
            {
                public string id { get; set; }
                public string text { get; set; }
            }
            [Serializable]
            public class DataList
            {
                public string status { get; set; }
                public string unicod { get; set; }
            }
        
        public static string send_id(string type, int unicod, int chanel, string phone)
        {
            // ^id_documment=_iemk_exchenge_log.id
            string response = "";
            //            var SourceFile = "";
            //string urlString = "http://smp.volmed.org.rus/json/server.php";
            var Host = Form1.Service_address;
            string urlString = "http://" + Host;
            var SoapAction = "";
            string id_service = Form1.Service_id ;
            string passwrd = id_service + Form1.Service_pass;
            passwrd = CreateMD5(passwrd);
            urlString = urlString + "?id_service="+id_service+"&auth_key=" + passwrd.ToLower();
            //string[] MyArray = { type, unicod.ToString(), chanel.ToString(), phone };
            Request_type MyArray = new Request_type();
                MyArray.type=type;
                MyArray.unicod = unicod;
                MyArray.chanel = chanel;
                if (phone == null) MyArray.phone = "000000"; else MyArray.phone = phone;
            var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string json = jsonSerializer.Serialize(MyArray);
            export_to_file("12", "json=" + json);
            var response1 = XmlHttpRequest(json, urlString);
            // запись в файл
            if (Int32.Parse(response1.id)>0)
            {
                List<List<string>> arr = namespase_mysql_connection.MySql.mysql_connect_read_status_file(Form1.Srv, Form1.DataBase, Form1.User, Form1.Passwrd, 3, "", DateTime.Now.ToString("yyyy-MM-dd") + " " + DateTime.Now.ToString("HH:mm:ss"), 'c', "", 1, "", 0, Int32.Parse(response1.id), response1.text);
            }
            export_to_file("12", "response error id =" + response1.id + " response text =" + response1.text);
            string request = "";
            var jsonDeSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            Response_type a = jsonDeSerializer.Deserialize<Response_type>(response);
            ErrorList a1 = jsonDeSerializer.Deserialize<ErrorList>(response);
            var DataList = jsonDeSerializer.Deserialize<DataList>(response);
            Console.WriteLine("a =" + a);
            return response;
        }

        public static ErrorList XmlHttpRequest(string Content, string urlString)
        {
            var ContentType = "application/json;";
            // param_return=1 полный ответ, 2 урезаный
                /* Get example *//*

                byte[] bytes;
                bytes = System.Text.Encoding.UTF8.GetBytes(get_s);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(get_s);
                request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                using (HttpWebResponse response1 = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response1.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
                 */
                /* Post */

            byte[] dataBytes = Encoding.UTF8.GetBytes(Content);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlString);
                request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                request.ContentLength = dataBytes.Length;
                request.ContentType = ContentType;
                request.Method = "POST";

                using (Stream requestBody = request.GetRequestStream())
                {
                    requestBody.Write(dataBytes, 0, dataBytes.Length);
                }

                /*using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }*/
                using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
                {

                    using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
                    {
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        var objText = reader.ReadToEnd();
                        //var json44 = JsonConvert.SerializeObject(objText, Formatting.Indented);
                        var myojb = js.DeserializeObject(objText);

                        var jsonData = (Dictionary<string, object>)js.DeserializeObject(objText);
                        ErrorList ErrorValue_class = new ErrorList();
                        foreach (KeyValuePair<string, object> keyValue in jsonData)
                        {
                            Console.WriteLine(keyValue.Key + " - " + keyValue.Value);
                            if (keyValue.Key == "error")
                            {
                                string ErrorValue_string = js.Serialize(keyValue.Value);
                                if (ErrorValue_string == "[]")
                                {
                                    ErrorValue_class.id = "0"; ErrorValue_class.text = "";
                                    break;
                                } 
                                ErrorValue_class = js.Deserialize<ErrorList>(ErrorValue_string);
                                Console.WriteLine("ErrorValue_class=" + ErrorValue_class.id + "ErrorValue_class.text=" + ErrorValue_class.text);
                            }
                            if (keyValue.Key == "data")
                            {
                                var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                                string dataValue_string = jsonSerializer.Serialize(keyValue.Value);
                                if (dataValue_string == "[]") break;
                                DataList Data_class = js.Deserialize<DataList>(dataValue_string);
                                Console.WriteLine("myojb2212.status=" + Data_class.status + "myojb2212.value=" + Data_class.unicod);
                                ErrorValue_class.id = "0"; ErrorValue_class.text = "";
                                return ErrorValue_class;
                            }                              
                        }
                        
/*                    Object obj;
                    bool b = jsonData.TryGetValue("error", out obj);
                        var splashInfo = JsonConvert.DeserializeObject<ErrorList>(objText);
                        ErrorList myojb1 = js.Deserialize<ErrorList>(objText);
                        DataList myojb2 = js.Deserialize<DataList>(objText);
                        return myojb1;*/
                        return ErrorValue_class;
                    }

                }
        }
        public static void export_to_file(string filename, string text)
        {
            FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            Console.WriteLine(text);
            sw.WriteLine(text);
            sw.Close();
        }
/*        public static void Add()
        {
            while (1 == 1)
            {
                Console.WriteLine('1');
                System.Threading.Thread.Sleep(1000); // пауза 0.1 сек.
            }
        }
        public static void Add1()
        {
            while (1 == 1)
            {
                Console.WriteLine('2');
                System.Threading.Thread.Sleep(3000); // пауза 0.1 сек.
            }
        }*/

    }
}

MySql подключение

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql;
using MySql.Data.MySqlClient;
using System.Data.Odbc;
using System.Windows.Forms;
using System.Data;
using System.Collections;
using System.IO;
using sprec;

namespace namespase_mysql_connection
{
    class MySql
    {
        public static MySqlCommand ConnectToMySQL(string MySQL_host, string MySQL_db, string MySQL_uid, string MySQL_pw)
        {
            MySqlConnection Connection = new MySqlConnection("Data Source=" + MySQL_host + ";Database=" + MySQL_db + ";User Id=" + MySQL_uid + ";Password=" + MySQL_pw + ";CharSet = cp1251;Connection Timeout=5;"); // Создаем соединение. Формат строки соединения подробно описан в прилагающейся документации.
            MySqlCommand Query = new MySqlCommand(); // С помощью этого объекта выполняются запросы к БД
            Query.Connection = Connection; // Присвоим объекту только что созданное соединение
            try
            {
                //Console.WriteLine("Соединяюсь с сервером базы данных...");
                Connection.Open();// Соединяемся
                //Console.WriteLine("Соеденено");
            }
            catch (MySqlException SSDB_Exception)
            {
                // Ошибка - выходим
                //Console.WriteLine("Проверьте настройки соединения, не могу соединиться с базой данных!\nОшибка: " + SSDB_Exception.Message);
                MessageBox.Show("Ошибка подключения !");
                return Query;
            }
            return Query;
        }
        public static void mysql_connect_test(string MySQL_host, string MySQL_db, string MySQL_uid, string MySQL_pw)
        {
            MySqlCommand MySQLConnected = ConnectToMySQL(MySQL_host, MySQL_db, MySQL_uid, MySQL_pw);
            Console.WriteLine(MySQLConnected.ToString());
        }
        public static List<List<string>> mysql_connect_read_status_file(string MySQL_host, string MySQL_db, string MySQL_uid, string MySQL_pw, int param_select, string StartTime, string StopTime, char ChannelNumber, string PhoneFrom, int ringCount, string FileName, int type_call, int id,string error_txt)
        {
            // Попытка открыть соединение, таймаут 5 сек.
            //            MySqlConnection con = new MySqlConnection("Server=test;Database=twest;Uid=test;Pwd=test;CharSet = cp1251;Connection Timeout=5;");
            //             List<string> ret_file_path = new List<string>();
            //            ArrayList ret_file_path = new ArrayList();
            ////String str = @"Server="+MySQL_host+";Database="+MySQL_db+";Uid="+MySQL_uid+";Pwd="+MySQL_pw+";CharSet = cp1251;Connection Timeout=5;";
            MySqlCommand MySQLConnected = ConnectToMySQL(MySQL_host, MySQL_db, MySQL_uid, MySQL_pw);
            // путь к документам \\10.*.*.*\iemk
            ////MySqlConnection con = null;
            ////con = new MySqlConnection(str);
            // путь к документам \\10.*.*.*\iemk
            // id_status =34 это пришли документы, но еще не отправлены.
            string var_select = "";
            MySQLConnected.CommandText = @"CREATE TABLE IF NOT EXISTS calldetails (
                      id int(11) NOT NULL AUTO_INCREMENT,
                      date_time datetime DEFAULT NULL,
                      channel varchar(80) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
                      ringCount varchar(80) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
                      numberPhone varchar(80) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
                      recordStart varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
                      recordStop varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
                      date_time_stop datetime DEFAULT NULL,
                      type_call int(11) DEFAULT NULL,
                      PRIMARY KEY (id)
                    )
                    ENGINE = INNODB
                    AUTO_INCREMENT = 1
                    AVG_ROW_LENGTH = 630
                    CHARACTER SET cp1251
                    COLLATE cp1251_general_ci
                    ROW_FORMAT = DYNAMIC;";
            MySQLConnected.ExecuteNonQuery();
            if (param_select == 0)
            {
                var_select = "SELECT IFNULL(MAX(id)+1,1) as ID FROM calldetails";
                //Program.export_to_file("1", "SELECT IFNULL(MAX(id)+1,1) as ID FROM calldetails");
            }
            if (param_select == 1)
            {
                var_select = "update calldetails SET ringCount=" + ringCount + ", recordStart =\"" + Path.GetFileName(FileName) + "\"" + " where id=" + id;
                //Program.export_to_file("1", "update calldetails SET ringCount=" + ringCount + ", recordStart =\"" + Path.GetFileName(FileName) + "\""+ " where id=" + id);
            }
            if (param_select == 2)
            {
                var_select = "update calldetails SET recordStop=1, date_time_stop =\"" + StopTime + "\"" + " where id=" + id;
                //Program.export_to_file("1", "update calldetails SET ringCount=" + ringCount + ", recordStart =\"" + Path.GetFileName(FileName) + "\""+ " where id=" + id);
            }
            if (param_select == 3)
            {
                var_select = @"CREATE TABLE IF NOT EXISTS error_send_http (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `err_id` varchar(8) NOT NULL,
                    `err_date` datetime NOT NULL,
                    `text` int(11) NOT NULL,
                    PRIMARY KEY (`id`)
                    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
                ";
                MySQLConnected.CommandText = var_select;
                MySQLConnected.ExecuteNonQuery();
                MySQLConnected.CommandText = "INSERT INTO error_send_http(err_id,err_date,text) VALUES  (" + id + ",\"" + StopTime + ",\""+",\"" + error_txt + "\"" + ")";
                MySQLConnected.ExecuteNonQuery();
                //Program.export_to_file("1", "update calldetails SET ringCount=" + ringCount + ", recordStart =\"" + Path.GetFileName(FileName) + "\""+ " where id=" + id);
            }
            if (param_select == 4)
            {
                var_select = "select * from error_send_http";
                MySQLConnected.CommandText = var_select;
                //Program.export_to_file("1", "update calldetails SET ringCount=" + ringCount + ", recordStart =\"" + Path.GetFileName(FileName) + "\""+ " where id=" + id);
            }
            MySQLConnected.CommandText = var_select;
            try
            {
                ////con.Open();
                ////sqlCom.ExecuteNonQuery();
                MySQLConnected.ExecuteNonQuery();
                if (param_select == 1 | param_select == 3) return null;
                ////MySqlDataAdapter da = new MySqlDataAdapter(sqlCom);
                MySqlDataAdapter da = new MySqlDataAdapter(MySQLConnected);
                DataTable dt = new DataTable();
                da.Fill(dt);
                var myData = dt.Select();
                //                textbox_fio.Text = result.ResultData.DefaultView.Table.Rows[0]["fio"].ToString(); // пример
                // Console.WriteLine(myData[0]["Codmkb10"].ToString() + "\n");
                var rezult_str = new List<List<string>>();
                if (myData.Length == 0)
                {
                    rezult_str.Add(new List<string> { "Error" });
                }
                else
                {
                    if (param_select == 0)
                    {
                        for (int i = 0; i < myData.Length; i++)
                        {
                            //                        Console.WriteLine(myData[0]["unicod"].ToString() + "\n");
                            Console.WriteLine("myData[i]=" + myData[i]["ID"].ToString());
                            rezult_str.Add(new List<string> { myData[i]["ID"].ToString() });
                            //                        Console.WriteLine(myData[i].ItemArray[j] + "\n");
                        }
                        MySQLConnected.CommandText = "INSERT INTO calldetails(id,date_time,channel,numberPhone,recordStop,type_call,recordstart) VALUES  (" + myData[0]["ID"] + ",\"" + StartTime + "\"" + ",\"" + ChannelNumber + "\"" + ",\"" + PhoneFrom + "\"" + ",0," + type_call + ",\"" + Path.GetFileName(FileName) + "\"" + ")";
                        MySQLConnected.ExecuteNonQuery();
                    }
                    if (param_select == 4)
                    {
                        for (int i = 0; i < myData.Length; i++)
                        {
                            rezult_str.Add(new List<string> { myData[i]["id"].ToString()  ,  myData[i]["err_id"].ToString() , myData[i]["err_date"].ToString() ,  myData[i]["text"].ToString() });
                            Console.WriteLine("myData[i]=" + myData[i]["id"].ToString());
                        }
                    }
                }
                return rezult_str;
            }
            catch (Exception ex)
            {
                var rezult_str = new List<List<string>>();
                rezult_str.Add(new List<string> { "Error" });
                //Console.WriteLine(rezult_str.Count);
                return rezult_str;
            }
            finally
            {
                MySQLConnected.Cancel();
            }
        }
        public static List<List<string>> mysql_connect_read_status_file_for_send()
        {
            MySqlCommand MySQLConnected = ConnectToMySQL("srv", "db", "user", "pass");
            // путь к документам \\10.35.0.66\iemk
            // id_status =35 это подписаны документы, = 37 - отправка с ошибкой завершилась. переотправляем.
            // arr[i][j] i-кол-во файлов, j=0 -исходный файл [j]=1- переподписаный файл j=2 _iemk_exchenge_log.id_iemk_docum документа, j=3 - подписаный файл,j-4 - _iemk_exchenge_log.id
            MySQLConnected.CommandText = "SELECT * FROM statistics._iemk_exchenge_log where (id_status=35 or id_status=37)";
            MySQLConnected.ExecuteNonQuery();
            MySqlDataAdapter da = new MySqlDataAdapter(MySQLConnected);
            DataTable dt = new DataTable();
            da.Fill(dt);
            var myData = dt.Select();
            string full_file_path = "";
            var rezult_str = new List<List<string>>();
            if (myData.Length == 0)
            {
                rezult_str.Add(new List<string> { "Error" });
            }
            else
            {
                for (int i = 0; i < myData.Length; i++)
                {
                    rezult_str.Add(new List<string> { "\\\\10.35.0.66\\iemk\\" + myData[i]["path_to_file"].ToString().Replace("/", "\\") + myData[i]["table_name"].ToString().Replace("/", "\\"), ("\\\\10.35.0.66\\iemk\\" + myData[i]["path_to_file"] + "_pp_" + myData[i]["table_name"]).ToString().Replace("/", "\\"), (myData[i]["id_iemk_docum"].ToString()), ("_pp_" + myData[i]["table_name"]).ToString(), (myData[i]["id"]).ToString() });
                    Console.WriteLine(full_file_path + "\n");
                }
            }
            return rezult_str;

        }
        // поиск статуса , полученного в синхронном ответе в базе. если нет, добавляем, есть -> возвращаем id статуса
        public static void mysql_connect_search_sync_status(string failue, string reason, int sync_unswer_error_count, int id_document)
        {
            {
                MySqlCommand MySQLConnected = ConnectToMySQL("srv", "db", "user", "pass");
                // путь к документам \\10.35.0.66\iemk
                MySQLConnected.CommandText = "SELECT * FROM _iemk_status_doc WHERE service_err_id like \"%" + failue + "%\"";
                MySQLConnected.ExecuteNonQuery();
                MySqlDataAdapter da = new MySqlDataAdapter(MySQLConnected);
                DataTable dt = new DataTable();
                da.Fill(dt);
                var myData = dt.Select();
                if (myData.Length == 0)
                {
                    MySQLConnected.CommandText = "INSERT INTO _iemk_status_doc(service_err_id,name,parent,is_work) VALUES  (\"" + failue + "\",\"" + reason + "\",17,1)";
                    MySQLConnected.ExecuteNonQuery();
                    MySQLConnected.CommandText = "SELECT LAST_INSERT_ID() as last_id FROM _iemk_status_doc LIMIT 1";
                    MySQLConnected.ExecuteNonQuery();
                    MySqlDataAdapter da1 = new MySqlDataAdapter(MySQLConnected);
                    DataTable dt1 = new DataTable();
                    da1.Fill(dt1);
                    var myData1 = dt1.Select();
                    MySQLConnected.CommandText = "update _iemk_exchenge_log set id_status_send_sync=" + myData1[0]["last_id"] + ", sync_unswer_error_count=" + sync_unswer_error_count + " where id=" + id_document;
                    MySQLConnected.ExecuteNonQuery();
                }
                else
                {
                    MySQLConnected.CommandText = "update _iemk_exchenge_log set id_status_send_sync=" + myData[0]["id"] + ", sync_unswer_error_count=" + sync_unswer_error_count + " where id=" + id_document;
                    MySQLConnected.ExecuteNonQuery();
                }

            }
        }

        // втсвляем исходник и результат синхронного запроса в лог
        public static void mysql_connect_insert_sync_result(string request, string response, int id_documment)
        {
            {
                MySqlCommand MySQLConnected = ConnectToMySQL("srv", "db", "u", "pass");
                // путь к документам \\10.35.0.66\iemk
                // id_status =34 это пришли документы, но еще не отправлены.
                // arr[i][j] i-кол-во файлов, j=0 -исходный файл [j]=1- переподписаный файл j=2 id документа, j=3 - подписаный файл,j-4 - id._iemk_list_docum.id
                //                File.WriteAllText("response_error" + DateTime.Now.ToString("yyyy_M_d_HH_mm_ss") + ".xml", "INSERT INTO _iemk_exchange_log_details(id_exchange_log,request_start,response_sync_from_iemk) VALUES (" + id_documment + ",\'(" + request + ")\',\'(" + response + ")\')", Encoding.UTF8);
                MySQLConnected.CommandText = "INSERT INTO _iemk_exchange_log_details(id_exchange_log,request_start,response_sync_from_iemk) VALUES (" + id_documment + ",\'(" + request + ")\',\'(" + response + ")\')";
                MySQLConnected.ExecuteNonQuery();
            }
        }
        public static void mysql_connect_insert_result(List<List<string>> array_for_insert)
        {
            MySqlCommand MySQLConnected = ConnectToMySQL("srv", "db", "u", "pass");
            // путь к документам \\10.35.0.66\iemk
            // id_status =34 это пришли документы, но еще не отправлены.
            // arr[i][j] i-кол-во файлов, j=0 -исходный файл [j]=1- переподписаный файл j=2 id документа, j=3 - подписаный файл,j-4 - id._iemk_list_docum.id
            for (int i = 0; i <= array_for_insert.Count - 1; i++)
            {
                Console.WriteLine("update _iemk_exchenge_log set resign_table_name=\"" + array_for_insert[i][0] + "\", id_status=" + int.Parse((array_for_insert[i][2])) + ", resign_snils=\"" + array_for_insert[i][3] + "\" where id_iemk_docum=" + int.Parse(array_for_insert[i][1]) + " and id=" + int.Parse(array_for_insert[i][4]));
                MySQLConnected.CommandText = "update _iemk_exchenge_log set resign_table_name=\"" + array_for_insert[i][0] + "\", id_status=" + int.Parse((array_for_insert[i][2])) + ", resign_snils=\"" + array_for_insert[i][3] + "\" where id_iemk_docum=" + int.Parse(array_for_insert[i][1]) + " and id=" + int.Parse(array_for_insert[i][4]);
                MySQLConnected.ExecuteNonQuery();
            }
        }
        public static String mysql_connect()
        {
            // Попытка открыть соединение, таймаут 5 сек.
            String str = @"Server=*.*.0*.*;Database=;Uid=;Pwd=;CharSet = cp1251;Connection Timeout=5;";
            MySqlConnection con = null;
            con = new MySqlConnection(str);
            // Здесь хранится в поле Key *официальный* адрес для принятия асинхронных запросов.
            MySqlCommand sqlCom = new MySqlCommand("SELECT * FROM _system_table where id=367", con);
            try
            {
                con.Open();
                sqlCom.ExecuteNonQuery();
                MySqlDataAdapter da = new MySqlDataAdapter(sqlCom);
                DataTable dt = new DataTable();
                da.Fill(dt);
                var myData = dt.Select();
                //                textbox_fio.Text = result.ResultData.DefaultView.Table.Rows[0]["fio"].ToString(); // пример
                //                Console.WriteLine(myData[0]["Codmkb10"].ToString() + "\n");
                /*                for (int i = 0; i < myData.Length; i++)
                                {
                                    for (int j = 0; j < myData[i].ItemArray.Length; j++)
                                    {
                                        Console.WriteLine(myData[0]["unicod"].ToString() + "\n");
                                        Console.WriteLine(myData[i].ItemArray[j] + "\n");
                                    }
                                }
                 */
                return myData[0]["param"].ToString();
            }
            catch (Exception ex)
            {
                //                MessageBox.Show("Ошибка удаления!\n\n" + ex.Message, "ОШИБКА");
                return "Error";
            }
            finally
            {
                con.Close();
            }
        }
    }
}

Форма 1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using Microsoft.Win32;
using System.Data.Odbc;
using System.Collections;
using System.IO;

namespace sprec
{
    public partial class Form1 : Form
    {
        public static string Srv = "";
        public static string DataBase = "";
        public static string User = "";
        public static string Passwrd = "";
        public static string Service_address = "";
        public static string Service_id = "";
        public static string Service_pass = "";
        public static int Autostart = 0;
        public Form1()
        {
            InitializeComponent();
            var start= get_data_from_reestr();
            if (start == 1)
            {
                Program.glo_status1 = " Ожидание звонка ...";
                label1.Text = Program.glo_status1;
                button1.Enabled = false;
                Program.Connect_to_asp();
            }
            if (start == 2)
            {
                Program.glo_status1 = " Необходимо задать первоначальные настроки !";
                label1.Text = Program.glo_status1;
                button1.Enabled = false;
                button2.Enabled = false;
            }
        }

        private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
        {

        }
        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Interval = 1000;
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Start();
            Program.glo_status1 = " Ожидание звонка ...";
            label1.Text = Program.glo_status1;
            get_data_from_reestr();
            Program.Connect_to_asp();
            button1.Enabled = false;
            button2.Enabled = true;
            button4.Enabled = false;
        }

        public int get_data_from_reestr()
        {
            RegistryKey currentUserKey = Registry.CurrentUser;
            RegistryKey SprecordsKey = currentUserKey.OpenSubKey("SpRecords");
            if (SprecordsKey != null)
            {
                if (SprecordsKey.GetValue("AutoStart").ToString() == "false" | ("AutoStart") == null) Autostart = 0;
                if (SprecordsKey.GetValue("AutoStart").ToString() == "true") Autostart = 1;
                Srv = SprecordsKey.GetValue("Server").ToString();
                DataBase = SprecordsKey.GetValue("Database").ToString();
                User = SprecordsKey.GetValue("User").ToString();
                Passwrd = SprecordsKey.GetValue("Password").ToString();
                Service_address = SprecordsKey.GetValue("Service_addr").ToString();
                Service_id = (string)SprecordsKey.GetValue("Service_id");
                Service_pass = (string)SprecordsKey.GetValue("Service_pass");
                SprecordsKey.Close();
            }
            else
            {
                Autostart = 2; //error
            }
            return Autostart;
        }
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            Form2 Forma2 = new Form2();
            Forma2.ShowDialog();
            button1.Enabled = true;
            button2.Enabled = true;
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click_1(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = Program.glo_status1; 
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Program.glo_status1 = " Сервис остановлен ...!";
            label1.Text = " Сервис остановлен ...!";
            Program.Connect_to_stop();
            button1.Enabled = true;
            button2.Enabled = false;
            button4.Enabled = true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            Environment.Exit(0);
            Close();
            Application.Exit();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Form1_Load(null, null);
        }

    }
}

Форма 2

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Odbc;
using System.Collections;
using System.IO;
using namespase_mysql_connection;
using System.Net;
using Microsoft.Win32;

namespace sprec
{

    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            //this.maskedTextBox1.Mask = "990\\.990\\.990\\.990";
            //this.maskedTextBox1.PromptChar = ' ';
            RegistryKey currentUserKey = Registry.CurrentUser;
            RegistryKey SprecordsKey = currentUserKey.OpenSubKey("SpRecords");
            this.maskedTextBox1.ValidatingType = typeof(System.Net.IPAddress);
            if (SprecordsKey != null)
            {
                if (SprecordsKey.GetValue("AutoStart").ToString()=="false") this.checkBox1.Checked = false;
                else this.checkBox1.Checked = true ;
                this.maskedTextBox1.Text = SprecordsKey.GetValue("Server").ToString();
                this.textBox_db.Text = SprecordsKey.GetValue("Database").ToString();
                this.textBox_user.Text = SprecordsKey.GetValue("User").ToString();
                this.textBox_pass.Text = SprecordsKey.GetValue("Password").ToString();
                if (SprecordsKey.GetValue("Service_addr") == null | SprecordsKey.GetValue("Service_addr").ToString()=="")
                {
                    this.service_addr.Text = "smp.volmed.org.rus/json/server.php";
                }
                else
                {
                    this.service_addr.Text = SprecordsKey.GetValue("Service_addr").ToString();
                }
                if (SprecordsKey.GetValue("Service_id") == null | (String)SprecordsKey.GetValue("Service_id") == "")
                {
                    this.service_id.Text = "55";
                }
                else
                {
                    this.service_id.Text = SprecordsKey.GetValue("Service_id").ToString();
                }
                if (SprecordsKey.GetValue("Service_pass") == null | (String)SprecordsKey.GetValue("Service_pass") == "")
                {
                    this.service_pass.Text = "1Nn75tR[]()";
                }
                else
                {
                    this.service_pass.Text = (string)SprecordsKey.GetValue("Service_pass");
                }
                SprecordsKey.Close();
            }
            else
            {
                this.service_addr.Text = "smp.sheksna.local/json/server.php";
                this.service_id.Text = "55";
                this.service_pass.Text = "1Nn75tR[]()";
            }
        }

        private void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
        {
            this.label1.Text = String.Format(
                "Valid: {0}\nMessage: {1}\nReturned value: {2}",
                e.IsValidInput,
                e.Message,
                e.ReturnValue);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            RegistryKey currentUserKey = Registry.CurrentUser;
            foreach (string subkeys in currentUserKey.GetSubKeyNames())
            {
                if (subkeys == "SpRecords")
                {
                    currentUserKey.DeleteSubKey("SpRecords");
                    break;
                }
            }
            RegistryKey helloKey = currentUserKey.CreateSubKey("SpRecords");
            if (checkBox1.Checked == false)
            {
                helloKey.SetValue("AutoStart", "false");
            }
            else
            {
                helloKey.SetValue("AutoStart", "true");
            }
            helloKey.SetValue("Server", maskedTextBox1.Text.Trim());
            helloKey.SetValue("Database", textBox_db.Text.Trim());
            helloKey.SetValue("User", textBox_user.Text.Trim());
            helloKey.SetValue("Password", textBox_pass.Text.Trim());
            helloKey.SetValue("Service_addr", service_addr.Text.Trim());
            helloKey.SetValue("Service_id", service_id.Text.Trim());
            helloKey.SetValue("Service_pass", service_pass.Text.Trim());
            helloKey.Close();
            Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            IPAddress ipAddress;
            maskedTextBox1.Text = maskedTextBox1.Text.Replace(" ", "");
            if (IPAddress.TryParse(maskedTextBox1.Text, out ipAddress))
            {
                MessageBox.Show(maskedTextBox1.Text + " верный");
            }
            else
            {
                MessageBox.Show(maskedTextBox1.Text + " не верный");
            }
            namespase_mysql_connection.MySql.mysql_connect_test(maskedTextBox1.Text, textBox_db.Text, textBox_user.Text, textBox_pass.Text);
        }

        private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void label7_Click(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            Form3 Forma3 = new Form3();
            Forma3.ShowDialog();
        }

    }
}

Форма 3

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace sprec
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
            select();
        }
        public void select()
        {
            List<List<string>> arr = namespase_mysql_connection.MySql.mysql_connect_read_status_file(Form1.Srv, Form1.DataBase, Form1.User, Form1.Passwrd, 4, "", "", 'c', "", 1, "", 0, 0, "");
            if (arr.Count == 0 | (arr[0][0] == "0" || arr[0][0] == "Error"))
            {
                this.dataGridView1.Columns.Add("No errors", "No errors");
                this.dataGridView1.Columns["No errors"].Width = 200;
                dataGridView1.Rows.Add("Нет ошибок !");
            }
            else
            {
                StringBuilder builder = new StringBuilder();
                if (arr.Count == 0)
                    Console.WriteLine("ошибка получения max(id) из таблицы calldetails");
                else
                {
                    this.dataGridView1.Columns.Add("id", "Идентификатор");
                    this.dataGridView1.Columns["id"].Width = 20;
                    this.dataGridView1.Columns.Add("err_id", "id ошибки");
                    this.dataGridView1.Columns["err_id"].Width = 50;
                    this.dataGridView1.Columns.Add("date_err", "Дата ошибки");
                    this.dataGridView1.Columns["date_err"].Width = 150;
                    this.dataGridView1.Columns.Add("text_err", "Описание");
                    this.dataGridView1.Columns["text_err"].Width = 260;
                    this.dataGridView1.AllowUserToAddRows = false; //запрешаем пользователю самому добавлять строки
                    for (int i = 0; i <= arr.Count - 1; i++)
                    {
                        {
                            //Console.WriteLine("id=" + arr[i][0] + "id=" + arr[i][1] + "id=" + arr[i][2] + "id=" + arr[i][3]);
                            //Добавляем строку, указывая значения колонок поочереди слева направо
                            dataGridView1.Rows.Add(arr[i][0], arr[i][1], arr[i][2], arr[i][3]);
                        }
                    }
                }
            }
        }
        }
}