using System;
using System.Windows.Forms;
using System.IO;
using MySql.Data.MySqlClient;
using System.Diagnostics;
using System.Device.Location;
using System.Net;
using System.Globalization;

// Uyod4SQL.exe
// ทำงานแบบ Windows Application 

namespace MySQL
{
    class  Program
    {
        private static MySqlConnection Uyod4Connect;
        public static bool insource=false ;
        public static bool inharddisk = false;
        private static string cpHost,cpPort,cpUser, cpPassword, cpDatabase, cpConnect;
        private static string cpFlag, cSQL,flCustomerID;
        private static string cTemp,cWord ;
        private static string MyApp = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
        private static string MyFolderApp = System.IO.Directory.GetCurrentDirectory();  // โพลเดอร์ทำงาน
        public static string MyProg = "Uyod4SQL".ToLower() ;
        // ใช้ร่วมกัน 
        private static string mPublic_IP, mUsername,mSoftwareID;
        // สำหรับสมาชิก
        private static string mDomainname, mComputername, mFoldername, mSysname, mCustomerID, mForUsed;
        // สำหรับลงทะเบียน        
        private static string mLatitude, mLongtitude, mMaccaddress, mCompanyname, mAddress, mTelephone;
        /*
        uyod_member (CustomerID varchar(15),SoftwareID varchar(9),Public_IP varchar(15),Latitude varchar(25)
        ,Longtitude varchar(25),Domainname varchar(25),Computername varchar(25),Sysname varchar(2),Username varchar(25)
        ,Foldername varchar(50),DT4Create varchar(25),DT4Connect varchar(25),ForUsed varchar(1))
        */
        /*
        uyod_register(CustomerID varchar(15),SoftwareID varchar(9),Public_IP varchar(15),Latitude varchar(25),Longtitude varchar(25)
        ,maccaddress varchar(25),Companyname varchar(50),Username varchar(50),Address varchar(50)
        ,Telephone varchar(25),DT4Create varchar(25)) 
        */


        static void Readme()  
        {
            string Fle4Readme = "Uyod4SQLReadme.txt";
            TextWriter Logtxt = new StreamWriter(Fle4Readme);
            // การใช้งาน
            Logtxt.WriteLine(MyApp);
            Logtxt.WriteLine("");
            Logtxt.WriteLine("ชุดคำสั่ง ");
            Logtxt.WriteLine("-" + MyProg + " " + "1 --> uyod_member-ดูข้อมูลเรียงตามวัน");
            Logtxt.WriteLine("-" + MyProg + " " + "2 IP DOM COM USER FOLD SYS RAN ---> uyod_member-เพิ่มหรือปรับปรุงตามตัวแปร");
            Logtxt.WriteLine("-" + MyProg + " " + "11   ---> uyod_register-ดูข้อมูลเรียงตามวัน");
            Logtxt.WriteLine("-" + MyProg + " " + "12 IP LA LO MAC COM USER ADDR TEL ---> uyod_register-เพิ่มหรือปรับปรุงตามตัวแปร");
            Logtxt.WriteLine("-" + MyProg + " " + "3 IP X ---> ค่าที่จะใช้ใน ForUse");
            Logtxt.WriteLine("-" + MyProg + " " + "B ---> เสริมระบบBACKUPระบบเก่า");
            Logtxt.WriteLine("-" + MyProg + " " + "C ---> ทำงานตามคำสั่ง mysqlcommand.txt");
            Logtxt.WriteLine("-" + MyProg + " " + "U CustomerID X ---> ค่าที่จะใช้ใน ForUse");
            Logtxt.WriteLine("-" + MyProg + " " + "M ---> เพื่อสร้างหรือลบไฟล์ Quit CustomerID มาจากเครื่อง");
            Logtxt.WriteLine("-" + MyProg + " " + "W CustomerID ---> เพื่อสร้างหรือลบไฟล์ Quit");
            Logtxt.WriteLine(""); Logtxt.WriteLine("");

            string[] readText;
            cTemp = "host.txt";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("host.txt ,DT:" + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                // Logtxt.WriteLine(cTemp);
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }
            cTemp = "hostforyou.txt";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("hostforyou.txt ,DT:" + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }
            cTemp = "login.txt";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("login.txt ,DT:" + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            cTemp = "UserLogin.txt";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("UserLogin.txt ,DT:" + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            cTemp = "CustomerID.txt";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("CustomerID.txt ,DT:" + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            cTemp = "Customer4backup2c.txt";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("Customer4backup2c.txt ,DT:" + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            cTemp = "mysqlcommand.txt ใช้กับ uyod4sql C";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("mysqlcommand.txt ,DT:" + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            cTemp = "xxxx.txt";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("xxxx.txt ,DT:" + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                Logtxt.WriteLine(cTemp);
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            Logtxt.Close(); Logtxt.Dispose();
            if (Layout.Program.Password.Input_Password("Open Readme.txt"))  
            { Util.Program.OpenWebSite(Environment.CurrentDirectory + "\\" + Fle4Readme); } 

            /*
            MessageBox.Show("Uyod4SQL 1   ---> uyod_member-ดูข้อมูลเรียงตามวัน" + System.Environment.NewLine
            + "Uyod4SQL 2 IP DOM COM USER FOLD SYS RAN ---> uyod_member-เพิ่มหรือปรับปรุงตามตัวแปร" + System.Environment.NewLine + System.Environment.NewLine
            + "Uyod4SQL 11   ---> uyod_register-ดูข้อมูลเรียงตามวัน" + System.Environment.NewLine
            + "Uyod4SQL 12 IP LA LO MAC COM USER ADDR TEL ---> uyod_register-เพิ่มหรือปรับปรุงตามตัวแปร" + System.Environment.NewLine + System.Environment.NewLine
            + "Uyod4SQL 3 IP X ---> ค่าที่จะใช้ใน ForUse" + System.Environment.NewLine
            + "Uyod4SQL B ---> เสริมระบบBACKUPระบบเก่า" + System.Environment.NewLine
            + "Uyod4SQL C ---> ทำงานตามคำสั่ง mysqlcommand.txt" + System.Environment.NewLine
            + "Uyod4SQL U CustomerID X ---> ค่าที่จะใช้ใน ForUse" + System.Environment.NewLine
            + "Uyod4SQL M ---> เพื่อสร้างหรือลบไฟล์ Quit CustomerID มาจากเครื่อง " + System.Environment.NewLine
            + "Uyod4SQL W CustomerID ---> เพื่อสร้างหรือลบไฟล์ Quit" + System.Environment.NewLine
            + "" + System.Environment.NewLine
            + "" + System.Environment.NewLine+"** ShowMessage.hav เพื่อแสดงข้อความ "
            , "", MessageBoxButtons.OK, MessageBoxIcon.Error); */
        }


        static void Pok_Show(string cfWord)
        {
            if (!insource) { return; }
            Util.Program.Pok_Mess(cfWord);
        }


        static void MySQLchkForUsed() 
        {
            cSQL = "SELECT ForUsed,Public_IP,CustomerID,Computername FROM uyod_member ";
            cSQL = cSQL + " WHERE CustomerID='" + mCustomerID + "'";
            MySqlCommand cmd = new MySqlCommand(cSQL, Uyod4Connect);
            MySqlDataReader reader = cmd.ExecuteReader() ;
            while (reader.Read())
            {
                cWord = "5 9s2uTS8ibhTC4dNpJEmM6FM3Qh7HKUGRcxpYi7CvkZn" + " ";
                cTemp = "*ID : " + reader[1].ToString().Trim();
                cTemp = cTemp + "*CUSTOMER ID :" + reader[2].ToString().Trim();
                cTemp = cTemp + "*COMPUTER NAME :" + reader[3].ToString().Trim();
                if (reader[0].ToString().Trim() == "X") // ห้ามใช้โปรแกรม
                {  
                    if (!File.Exists("SoftwareFor.Quit"))
                    { File.Copy("login.txt", "SoftwareFor.Quit");
                      cTemp = "*สร้างไฟล์ SoftwareFor.Quit"+cTemp;
                      Util.Program.Pok_Process("Util_Pok",cWord+cTemp); // Util.Program.Pok_Process("
                    }
                    Pok_Show("สร้าง SoftwareFor.Quit");
                }
                else // ใช้โปรแกรมได้ 
                {
                    if (File.Exists("SoftwareFor.Quit"))
                    {
                        File.Delete("SoftwareFor.Quit");
                        cTemp = "*SoftwareFor.Quit ลบแล้ว" + cTemp;
                        Util.Program.Pok_Process("Util_Pok", cWord + cTemp);
                    }
                    Pok_Show("ไม่มี SoftwareFor.Quit");
                }
            } 
        }


        static void MySQL4List() // แสดงรายการ
        {
            cSQL = "SELECT CustomerID,SoftwareID,Public_IP,Latitude,Longtitude,Computername,Username,Foldername,DT4Connect,ForUsed";
            cSQL = cSQL +" FROM uyod_member ORDER BY DT4Connect DESC";
            MySqlCommand cmd = new MySqlCommand(cSQL, Uyod4Connect);
            MySqlDataReader reader = cmd.ExecuteReader();
            // แสดงเป็น HTML
            string FlText =  "MySQL4List.html";  
            int iCount=0;
            TextWriter List2Txt = new StreamWriter(FlText);
            List2Txt.WriteLine("<html>");
            List2Txt.WriteLine("<head>");
            List2Txt.WriteLine("<title>สมาชิก Uyodteam</title>");
            List2Txt.WriteLine("<meta http-equiv=Content-Type content='text/html; charset=utf-8'>");    
            List2Txt.WriteLine("<link rel='icon' href='http://uyod.net/ico.png' type='image/x-icon'>");
            List2Txt.WriteLine("</head>");
            List2Txt.WriteLine("<body width='100%' text='FFFFFF' link=yellow vlink=yellow background='http://uyod.net/wallpaper.jpg'>");
            List2Txt.WriteLine("<table border='2' width='100%'>");
            List2Txt.WriteLine("<tr><td colspan='9' align='middle'><img src='http://uyod.net/uyod_w2.png' width='150' height='150'></td></tr>");
            List2Txt.WriteLine("<tr><td>.</td> <td>รหัสสมาชิก</td> <td>Software ID.</td> <td>เลข IP</td> <td>ตำแหน่ง</td> <td>ชื่อคอมพิวเตอร์</td> <td>ชื่อลูกค้า</td> <td>วันที่ปรับปรุง</td> <td>.</td></tr>");
            // START    
            while (reader.Read())
            {
                iCount++;
                List2Txt.WriteLine("<tr>");
                List2Txt.Write("<td>" + iCount.ToString().Trim() + ".</td>"); // iCount
                List2Txt.WriteLine("<td>"+reader[0].ToString().Trim()+ "</td>"); // Customer ID
                List2Txt.Write("<td>" + reader[1].ToString().Trim() + "</td>"); // Software ID
                List2Txt.Write("<td>" + reader[2].ToString().Trim() + "</td>"); // IP Address
                List2Txt.Write("<td><a href='https://www.google.co.th/maps/@"+reader[3].ToString().Trim()+ ","+ reader[4].ToString().Trim()+",15z?hl=th' target='_blank'>");
                List2Txt.Write(reader[3].ToString().Trim()+","+ reader[4].ToString().Trim()+"</ a ></ td >"); // Location
                List2Txt.Write("<td>"+ reader[5].ToString().Trim() + "</td>"); // Computer Name 
                List2Txt.Write("<td>"+ reader[6].ToString().Trim() + "</td>"); // User Name
                List2Txt.Write("<td>"+ reader[8].ToString().Trim() + "</td>"); 
                List2Txt.Write("<td>"+ reader[9].ToString().Trim() + "</td>");
                List2Txt.Write("</tr>");
            }
            // END    
            List2Txt.WriteLine("</table>");
            List2Txt.WriteLine("<br>*** File : " + Environment.CurrentDirectory + "\\" + FlText);
            List2Txt.WriteLine("<br>*** WEB  : uyod.net/uyod_member/"+FlText);
            List2Txt.WriteLine("</body>");
            List2Txt.WriteLine("</html>");
            List2Txt.Close();
            // /* 
            FTPupload(Environment.CurrentDirectory + "\\" + FlText, FlText);
            Util.Program.OpenWebSite(Environment.CurrentDirectory + "\\" + FlText);
        }


        static void Regis4List() // แสดงรายการ ลงทะเบียน
        {
            cSQL = "SELECT CustomerID,SoftwareID,Public_IP,Latitude,Longtitude,Companyname,Username,Address,Telephone,DT4Create";
            cSQL = cSQL + " FROM uyod_register ORDER BY DT4Create DESC";
            MySqlCommand cmd = new MySqlCommand(cSQL, Uyod4Connect);
            MySqlDataReader reader = cmd.ExecuteReader();
            int iCount=0;
            string FlText = "Regis4List.html";
            TextWriter List2Txt = new StreamWriter(FlText);
            List2Txt.WriteLine("<html>");
            List2Txt.WriteLine("<head>");
            List2Txt.WriteLine("<title>ลงทะเบียนสำหรับ Uyodteam</title>");
            List2Txt.WriteLine("<meta http-equiv=Content-Type content='text/html; charset=utf-8'>");
            List2Txt.WriteLine("<link rel='icon' href='http://uyod.net/ico.png' type='image/x-icon'>");
            List2Txt.WriteLine("</head>");
            List2Txt.WriteLine("<body width='100%' text='FFFFFF' link=yellow vlink=yellow background='http://uyod.net/wallpaper.jpg'>");
            List2Txt.WriteLine("<table border='2' width='100%'>");
            List2Txt.WriteLine("<tr><td colspan='10' align='middle'><img src='http://uyod.net/uyod_w2.png' width='150' height='150'></td></tr>");
            List2Txt.WriteLine("<tr><td>.</td> <td>รหัสสมาชิก</td> <td>Software ID.</td> <td>เลข IP</td> <td>ตำแหน่ง</td> <td>บริษัท</td> <td>ลูกค้า</td> <td>ที่อยู่</td> <td>เบอร์โทร</td><td>วันที่สร้าง</td></tr>");
            while (reader.Read())
            {
                iCount++;
                List2Txt.WriteLine("<tr>");
                List2Txt.Write("<td>" + iCount.ToString().Trim() + ".</td>"); // iCount
                List2Txt.Write("<td>" + reader[0].ToString().Trim() + "</td>"); // Customer ID
                List2Txt.Write("<td>" + reader[1].ToString().Trim() + "</td>"); // Software ID
                List2Txt.Write("<td>" + reader[2].ToString().Trim() + "</td>"); // IP Address
                List2Txt.Write("<td><a href='https://www.google.co.th/maps/@" + reader[3].ToString().Trim() + "," + reader[4].ToString().Trim() + ",15z?hl=th' target='_blank'>");
                List2Txt.Write(reader[3].ToString().Trim() + "," + reader[4].ToString().Trim() + "</ a ></ td >"); // Location
                List2Txt.Write("<td>" + reader[5].ToString().Trim() + "</td>"); // Company
                List2Txt.Write("<td>" + reader[6].ToString().Trim() + "</td>"); // User
                List2Txt.Write("<td>" + reader[7].ToString().Trim() + "</td>"); // Address
                List2Txt.Write("<td>" + reader[8].ToString().Trim() + "</td>"); // โทร
                List2Txt.Write("<td>" + reader[9].ToString().Trim() + "</td>"); // วันที่สร้าง
                List2Txt.Write("</tr>");
            }
            List2Txt.WriteLine("</table>");
            List2Txt.WriteLine("<br>*** File : "+Environment.CurrentDirectory + "\\" + FlText);
            List2Txt.WriteLine("<br>*** WEB  : uyod.net/uyod_member/" + FlText);
            List2Txt.WriteLine("</body>");
            List2Txt.WriteLine("</html>");
            List2Txt.Close();
            FTPupload(Environment.CurrentDirectory + "\\" + FlText, FlText);
            Util.Program.OpenWebSite(Environment.CurrentDirectory + "\\" + FlText);
        }


        static void MySQL4Update()  // เพิ่มหรือแก้ข้อมูล สมาชิก  
        {
            if (mCustomerID == "") { return; }
            mLatitude = "?"; mLongtitude = "?";
            // หาค่า Location 
            GeoCoordinateWatcher watcher;
            watcher = new GeoCoordinateWatcher();
            watcher.PositionChanged += (sender, e) =>
            {
                var coordinate = e.Position.Location;
                mLatitude = coordinate.Latitude.ToString();
                mLongtitude = coordinate.Longitude.ToString();
            };
            watcher.Start();
            System.Threading.Thread.Sleep(1000); // n*1000 = 1วินาที

            cSQL = "SELECT Count(*) FROM uyod_member WHERE CustomerID='" + mCustomerID + "'";
            MySqlCommand cmd = new MySqlCommand(cSQL, Uyod4Connect);
            int nCount;
            nCount = int.Parse(cmd.ExecuteScalar() + "");
            CultureInfo Region4GB = new CultureInfo("en-GB");
            string mDateTime = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss",Region4GB);
            string MessageText = "ชุดคำสั่ง" + System.Environment.NewLine;
            if (nCount == 0) // เพิ่ม  
            {
                cSQL = "INSERT INTO uyod_member (CustomerID,Public_IP,Domainname,Computername,Username,Foldername,Sysname,DT4Create,DT4Connect,ForUsed,Latitude,Longtitude,SoftwareID)";
                cSQL = cSQL + " VALUES(";
                cSQL = cSQL + "'" + mCustomerID + "'";
                cSQL = cSQL + ",'" + mPublic_IP + "'";
                cSQL = cSQL + ",'" + mDomainname + "'";
                cSQL = cSQL + ",'" + mComputername + "'";
                cSQL = cSQL + ",'" + mUsername + "'";
                cSQL = cSQL + ",'" + mFoldername + "'";
                cSQL = cSQL + ",'" + mSysname + "'";
                cSQL = cSQL + ",'" + mDateTime + "'";
                cSQL = cSQL + ",'" + mDateTime + "'";
                cSQL = cSQL + ",'1'";
                cSQL = cSQL + ",'" + mLatitude + "'";
                cSQL = cSQL + ",'" + mLongtitude + "'";
                cSQL = cSQL + ",'" + mSoftwareID + "'";
                cSQL = cSQL + ")";
                MessageText = cSQL + System.Environment.NewLine;
            }
            else // แก้ไข
            {
                cSQL = "UPDATE uyod_member SET Domainname='" + mDomainname + "'";
                cSQL = cSQL + ",Computername='" + mComputername + "'";
                cSQL = cSQL + ",Username='" + mUsername + "'";
                cSQL = cSQL + ",Foldername='" + mFoldername + "'";
                cSQL = cSQL + ",Sysname='" + mSysname + "'";
                cSQL = cSQL + ",DT4Connect='" + mDateTime + "'";
                cSQL = cSQL + ",Public_IP='" + mPublic_IP + "'";
                cSQL = cSQL + ",Latitude='" + mLatitude + "'";
                cSQL = cSQL + ",Longtitude='" + mLongtitude + "'";
                cSQL = cSQL + ",SoftwareID='" + mSoftwareID + "'";
                cSQL = cSQL + " WHERE CustomerID='" + mCustomerID + "'";
                MessageText = cSQL + System.Environment.NewLine;
            }
            cmd = new MySqlCommand(cSQL, Uyod4Connect);
            try
            {
                cmd.ExecuteNonQuery();
                MessageText = MessageText + "ทำงานสำเร็จ ";
            }
            catch (MySqlException ex)
            {
                MessageText = MessageText + "ทำงานไม่สำเร็จ" + System.Environment.NewLine;
                MessageText = MessageText + "Error :" + System.Environment.NewLine;
                MessageText = MessageText + ex.Message;
            }
            Pok_Show(MessageText);
        }


        static void UTF82AsCII(string FleUTF8,string FleAscII) // แปลงจากไทยจาก UTF-8 เป็น   ASCII
        {
            if (!File.Exists(FleUTF8)) { return; }
        }
        
        static void Regis4Update()  // เพิ่มหรือแก้ข้อมูล ลงทะเบียน
        {
            if (mPublic_IP == "") { return; }
            cSQL = "SELECT Count(*) FROM uyod_register WHERE Public_IP='" + mPublic_IP + "'";
            MySqlCommand cmd = new MySqlCommand(cSQL, Uyod4Connect);
            int nCount;
            nCount = int.Parse(cmd.ExecuteScalar() + "");
            CultureInfo Region4GB = new CultureInfo("en-GB");
            string mDateTime = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss",Region4GB);
            string MessageText = "ชุดคำสั่ง" + System.Environment.NewLine;
            if (nCount == 0) // เพิ่ม  
            {
                cSQL = "INSERT INTO uyod_register (CustomerID,Public_IP,Latitude,Longtitude,Maccaddress,Companyname,Username,Address,Telephone,DT4Create,SoftwareID)";
                cSQL = cSQL + " VALUES(";
                cSQL = cSQL + "'" + mCustomerID + "'";
                cSQL = cSQL + ",'" + mPublic_IP + "'";
                cSQL = cSQL + ",'" + mLatitude + "'";
                cSQL = cSQL + ",'" + mLongtitude + "'";
                cSQL = cSQL + ",'" + mMaccaddress + "'";
                cSQL = cSQL + ",'" + mCompanyname + "'";
                cSQL = cSQL + ",'" + mUsername + "'";
                cSQL = cSQL + ",'" + mAddress + "'";
                cSQL = cSQL + ",'" + mTelephone + "'";
                cSQL = cSQL + ",'" + mDateTime + "'";
                cSQL = cSQL + ",'" + mSoftwareID + "'";
                cSQL = cSQL + ")";
                MessageText = cSQL + System.Environment.NewLine;
            }
            else // แก้ไข 
            {
                cSQL = "UPDATE uyod_register SET ";
                cSQL = cSQL + "Latitude='" + mLatitude + "'";
                cSQL = cSQL + ",Longtitude='" + mLongtitude + "'";
                cSQL = cSQL + ",Maccaddress='" + mMaccaddress + "'";
                cSQL = cSQL + ",Companyname='" + mCompanyname + "'";
                cSQL = cSQL + ",Username='" + mUsername + "'";
                cSQL = cSQL + ",Address='" + mAddress + "'";
                cSQL = cSQL + ",Telephone='" + mTelephone + "'";
                cSQL = cSQL + ",Public_IP='" + mPublic_IP + "'";
                cSQL = cSQL + ",SoftwareID='" + mSoftwareID + "'";
                cSQL = cSQL + " WHERE CustomerID='" + mCustomerID + "'";
                MessageText = cSQL + System.Environment.NewLine;
            }
            cmd = new MySqlCommand(cSQL, Uyod4Connect);
            try
            {
                cmd.ExecuteNonQuery();
                MessageText = MessageText + System.Environment.NewLine + "ทำงานสำเร็จ ";
            }
            catch (MySqlException ex)
            {
                MessageText = MessageText + "ทำงานไม่สำเร็จ" + System.Environment.NewLine;
                MessageText = MessageText + "Error :" + System.Environment.NewLine;
                MessageText = MessageText + ex.Message;
            }
            Pok_Show(MessageText);
        }


        static void MySQL4Close()
        {
            try
            {
                Uyod4Connect.Close();
            }
            catch (MySqlException ex)
            {
                Pok_Show("Close Database not Complete " + ex.Message);
            }
        }


        private static bool CheckServer(int nYesNo)  // ตรวจสอบว่า เข้าได้หรือไม่ 
        {
            bool lyesorno;
            string MessageText = "Host : " + cpHost + System.Environment.NewLine;
            MessageText = MessageText + "Database : " + cpDatabase + System.Environment.NewLine;
            MessageText = MessageText + "User : " + cpUser + System.Environment.NewLine ;
            if (cpPort!="") { MessageText = MessageText + cpPort + System.Environment.NewLine; }
            MessageText=MessageText + System.Environment.NewLine;
            try
            {
                Uyod4Connect.Open();  // เปิดครั้งแรกครั้งเดียว ค้างไว้เลย 
                lyesorno = true;
                MessageText = MessageText + "ติดต่อสำเร็จ";
            }
            catch (MySqlException ex)
            {
                MessageText = MessageText + "เกิดข้อผิดพลาด "+ System.Environment.NewLine;
                MessageText = MessageText + "Error No. " + ex.Number.ToString() + System.Environment.NewLine;
                MessageText = MessageText + ":" +ex.Message;
                switch (ex.Number)
                {
                    case 0:
                        MessageText = MessageText + System.Environment.NewLine + ":Cannot connect to server.Contact administrator";
                        break;
                    case 1040:
                        MessageText = MessageText + System.Environment.NewLine + ":Too Many connections";
                        break;
					case 1042:
                        MessageText = MessageText + System.Environment.NewLine + ":Server No Found";
                        break;
                    case 1045:
                        MessageText = MessageText + System.Environment.NewLine + ",Invalid username/password, please try again";
                        break;
					default:
                        break;
                }
                lyesorno = false;
            }
            if (nYesNo==0) { Util.Program.Pok_Mess(MessageText); } // เรียก uyod4sql แบบไม่มี Option
			else {Pok_Show(MessageText);}
            return lyesorno;
        }


        static void MySQL4ForUsed(int nOption)
        {
            // nOption=1 หาตาม IP  2=หาตาม Random 
            if (nOption == 2) // หาตาม Random 
            { cSQL = "SELECT Count(*) FROM uyod_member WHERE CustomerID='" + mCustomerID + "'"; }
            else // หาตาม IP
            { cSQL = "SELECT Count(*) FROM uyod_member WHERE Public_IP='" + mPublic_IP + "'"; }
            MySqlCommand cmd = new MySqlCommand(cSQL, Uyod4Connect);
            int nCount;
            nCount = int.Parse(cmd.ExecuteScalar() + "");
            if (nCount>0) // พบและทำงานต่อได้ 
            {
                cSQL = "UPDATE uyod_member SET ForUsed='" + mForUsed + "'";
                if (nOption == 2) // หาตาม Random 
                { cSQL = cSQL + " WHERE CustomerID='" + mCustomerID + "'"; }
                else
                { cSQL = cSQL + " WHERE Public_IP='" + mPublic_IP + "'"; }
                cmd = new MySqlCommand(cSQL, Uyod4Connect);
                try
                {
                    cmd.ExecuteNonQuery();
                    Util.Program.Pok_Mess(cSQL+ System.Environment.NewLine +"สำเร็จ");
                }
                catch (MySqlException ex)
                {
                    Pok_Show(cSQL + System.Environment.NewLine + "ไม่สำเร็จ"+System.Environment.NewLine+"Error : "+ex.Message);
                }
            } else { Util.Program.Pok_Mess(cSQL + System.Environment.NewLine + "ค่าเป็น 0 ไม่พบข้อมูล"); }
        }

        static void MySQL4Command() 
        {
            string textfile = "mysqlcommand.txt";
            if (!File.Exists(textfile))
            {
                TextWriter Uyod2Txt = new StreamWriter(textfile);
                Uyod2Txt.WriteLine("");
                Uyod2Txt.WriteLine("");
                Uyod2Txt.Close();
            }
            string[] lines = File.ReadAllLines(textfile);
            cSQL = lines[0].Trim()+ lines[1].Trim();

            if (cSQL == "") { Pok_Show("แก้ไขไฟล์ชื่อ "+textfile);return; }
            MySqlCommand cmd = new MySqlCommand(cSQL, Uyod4Connect);
            cmd = new MySqlCommand(cSQL, Uyod4Connect);
            string MessageText = "คำสั่ง : " + System.Environment.NewLine + System.Environment.NewLine;
            MessageText = MessageText + cSQL + System.Environment.NewLine;
            try
            {
                cmd.ExecuteNonQuery();
                MessageText = MessageText + "ทำงานสำเร็จ ยินดีด้วย" + System.Environment.NewLine;
            }
            catch (MySqlException ex)
            {
                MessageText = MessageText + "ทำงานไม่สำเร็จ" + System.Environment.NewLine;
                MessageText = MessageText + "แก้ไขไฟล์ชื่อ " + textfile + System.Environment.NewLine + System.Environment.NewLine;
                MessageText = MessageText + " ,Error :" + System.Environment.NewLine;
                MessageText = MessageText + ex.Message;
            }
            Pok_Show(MessageText);
        }


        static void SetupVAR()
        {
            string textfile = "hostforyou.tx_";
            TextWriter Uyod2Txt;
            if (!File.Exists(textfile))
            {
                Uyod2Txt = new StreamWriter(textfile);
                Uyod2Txt.WriteLine("host"); // Host 
                Uyod2Txt.WriteLine("user"); // User
                Uyod2Txt.WriteLine("password"); // Password
                Uyod2Txt.WriteLine("database"); // Databse
                Uyod2Txt.WriteLine("port"); // Port
                Uyod2Txt.Close();
            }
            textfile = "login.txt";
            if (!File.Exists(textfile))
            {
                Uyod2Txt = new StreamWriter(textfile);
                Uyod2Txt.WriteLine("uyod2SQL"); // Host 
                Uyod2Txt.Close();
            }
            if (Directory.Exists("C:")) { cTemp = "C:"; } else { cTemp = ""; }
            cTemp = cTemp + "\\TempVFP";
            if (!Directory.Exists(cTemp)) { Directory.CreateDirectory(cTemp); }
            flCustomerID = cTemp + "\\CustomerID.txt";
        }


        static void MySQL4CustomerID()  
        {
            if (!File.Exists(flCustomerID))
            {
                if (mCustomerID == "" || mCustomerID.Trim().Length < 10) // เป็นช่องว่างหรือน้อยกว่า 10 ให้ Gen ใหม่ 
                {
                    Random rnd = new Random();
                    int numRandom = rnd.Next(101,999);
                    CultureInfo Region4GB = new CultureInfo("en-GB");
                    mCustomerID = DateTime.Now.ToString("ddMMyyHHmmss",Region4GB)+numRandom.ToString().Trim();
                    Pok_Show("New mCustomerID : " + mCustomerID);
                }
                TextWriter Uyod2Txt = new StreamWriter(flCustomerID);
                Uyod2Txt.WriteLine(mCustomerID);
                Uyod2Txt.WriteLine(mPublic_IP);
                Uyod2Txt.Close();
            }
            cTemp = "";
            if (File.Exists("UserLogin.txt"))
            {
                string[] lines = File.ReadAllLines("UserLogin.txt");
                mSoftwareID = lines[4];
            }
        }


        static void FTPupload(string uFullFileName, string uFileName) 
        {
            //Create FTP request
            string ftpAdd = "ftp://ftp.uyod.net/public_html/uyod_member";
            string username = "pipop@uyod.net"; string password = "u13421342";

            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftpAdd + "/" + uFileName);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(username, password);
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = true;
            //Load the file
            FileStream stream = File.OpenRead(uFullFileName);
            byte[] buffer = new byte[stream.Length];
            try
            {
                stream.Read(buffer, 0, buffer.Length);
                stream.Close();
                //Upload file
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();
                request = null;
                Pok_Show("Upload : " + uFullFileName + System.Environment.NewLine
                    + "To : " + ftpAdd + "/" + uFileName + System.Environment.NewLine
                    + "สำเร็จ");
            }
            catch (Exception e)
            {
                stream.Close();
                Pok_Show("Upload ไม่สำเร็จ พบปัญหา " + e.ToString().Trim());
            }
        }

        private static bool FTPdownload(string cFileOnweb, string cFileOnC) 
        {
            bool lDownload = false;
            cFileOnweb = cFileOnweb.Trim();
            cFileOnC = cFileOnC.Trim();
            if (File.Exists(cFileOnC)) { File.Delete(cFileOnC); }
            try
            {
                WebClient WebDownload = new WebClient();
                WebDownload.DownloadFile(cFileOnweb, cFileOnC);
                WebDownload.Dispose();
                Pok_Show("Download จาก " +Environment.NewLine+ cFileOnweb + Environment.NewLine
                    +"ไป " + Environment.NewLine + Environment.CurrentDirectory + "\\"+cFileOnC 
                    +Environment.NewLine + Environment.NewLine + "### สำเร็จ ขอบคุณครับ ####");
                lDownload = true;
            }
            catch (Exception ex)
            { Pok_Show("Download จาก " + Environment.NewLine + cFileOnweb + Environment.NewLine 
                + "ไป " + Environment.NewLine+Environment.CurrentDirectory+"\\"+cFileOnC + Environment.NewLine + "###  ไม่สำเร็จ ###"
                +Environment.NewLine + Environment.NewLine + ex.ToString() ); }
            return lDownload;
        }


        static void LockPassword()  // เฉพาะรหัสผ่านบาง Host หรือ user
        {
            switch (cpUser)
            {
                case ("uyodsoftware"): cpPassword = "d13421342"; break;  // www.db4free.net                    
                case ("sql6413841"): cpPassword = "87WdrWliIe"; break;   // www.freemysqlhosting.net                 
                case ("WoQmnhvlm0"): cpPassword = "rrMv38hJzD"; break;   // remotemysql.com          
            }
        }

        // สร้างไฟล์ Customer4backup2c.txt เพื่อเพิ่มข้อมูล
        static void Customer4backup2c() 
        {
            string textfile = "Customer4backup2c.txt";
            if (!File.Exists(textfile))
            {
                TextWriter Uyod2Txt = new StreamWriter(textfile);
                Uyod2Txt.WriteLine("mPublic_IP");
                Uyod2Txt.WriteLine("mDomainname");
                Uyod2Txt.WriteLine("mComputername");
                Uyod2Txt.WriteLine("mUsername");
                Uyod2Txt.WriteLine("mFoldername");
                Uyod2Txt.WriteLine("BD");
                Uyod2Txt.WriteLine("SoftID");
                // จะเป็นส่วนหมายเหตุ
                Uyod2Txt.WriteLine("");
                Uyod2Txt.WriteLine("Remark");
                Uyod2Txt.WriteLine("mPublic_IP C(15)");
                Uyod2Txt.WriteLine("mDomainname C(25)");
                Uyod2Txt.WriteLine("mComputername C(25)");
                Uyod2Txt.WriteLine("mUsername C(25)");
                Uyod2Txt.WriteLine("mFoldername C(50)");
                Uyod2Txt.WriteLine("mSysName C(2)");
                Uyod2Txt.WriteLine("mSoftwareID C(9)");
                Uyod2Txt.Close();
            }
            string[] Customerline = File.ReadAllLines(textfile);
            mPublic_IP = Customerline[0].Trim();
            mDomainname = Customerline[1].Trim();
            mComputername = Customerline[2].Trim();
            mUsername = Customerline[3].Trim();
            mFoldername = Customerline[4].Trim();
            mSysname = Customerline[5].Trim();
            mSoftwareID = Customerline[6].Trim();
        }


        static void Test_Prog()
        {
                //
        }


        static void Main(string[] args)
        {
            if (MyApp.Substring(0, 2) == "V:") { insource = true; } // Run กับ Source
            if (Directory.Exists(@"R:\Temp")) { inharddisk = true; }  // Run กับ Harddisk   

            SetupVAR();
            if (args.Length == 0) { if (insource) { cpFlag = "?"; } else { return; }  }  // สำหรับทดสอบหัวข้อต่างๆ Pipop
            else { cpFlag = args[0].Trim().ToUpper(); }

            // ตรวจสอบและเชื่อมต่อ MySQL
            if (!File.Exists("host.txt")) { if (!FTPdownload("http://uyod.net/uyod_member/host.txt", "host.txt")) { return; } }
            string[] lines;
            if (File.Exists("hostforyou.txt")) { lines = File.ReadAllLines("hostforyou.txt"); } // อ่านไฟล์ hostforyou.txt
            else { lines = File.ReadAllLines("host.txt"); }  // อ่านไฟล์ host.txt
            // หา Server แล้วตั้งรหัสผ่านใหม่ 
            cpHost = lines[0].Trim(); cpUser = lines[1].Trim(); cpPassword = lines[2].Trim(); cpDatabase = lines[3].Trim();
            cpPort = lines[4].Trim(); if (cpPort != "") { cpPort = ";port=" + cpPort; }  // สำหรับกรณีกำหนดค่า Port 
            LockPassword(); // เปลี่ยนรหัสผ่านอัตโนมัติ 
            cpConnect = "host="+cpHost+cpPort+";user="+cpUser+";password="+cpPassword+";database="+cpDatabase;
            Uyod4Connect = new MySqlConnection(cpConnect);
            if (!CheckServer(args.Length)) { MySQL4Close(); return; } // ติดต่อ Serverไม่ได้ ให้ออกไป 
            // จบเชื่อมต่อ MySQL

            switch (cpFlag)
            {
                case ("?"): Readme(); break;  // OK
                case ("T"): Test_Prog(); break;
                case ("C"): MySQL4Command(); break; // OK
                case ("1"): MySQL4List(); break; // OK
                case ("B"): // สำหรับ Backup ระบบเก่า เสริมใน backup2c.bat Uyod4SQL  
                    mPublic_IP = "?";
                    mDomainname = "?";
                    mComputername = "?";
                    mUsername = "?";
                    mFoldername = "?";
                    mSysname = "?";
                    mCustomerID = "?";
                    mSoftwareID = "?";
                    MySQL4CustomerID(); // mCustomerID จะเปลี่ยนค่าจาก CustomerID.txt
                    lines = File.ReadAllLines(flCustomerID);
                    mCustomerID = lines[0];
                    Customer4backup2c(); // สร้างไฟล์ customer4backup2c.txt เพื่อเพิ่มข้อมูล 
                    MySQL4Update(); 
                    break;
                case ("2"):
                    // mPublic_IP,mDomainname,mComputername,mUsername,mFoldername,mSysname
                    // อ่านเพิ่มเติมจาก  args[]
                     mPublic_IP = "?";
                     mDomainname = "?";
                     mComputername = "?";
                     mUsername = "?";
                     mFoldername = "?";
                     mSysname = "?";
                     mCustomerID = "?";
                     mSoftwareID = "?";
                    for (int iArg = 1; iArg < args.Length; iArg++)
                    {
                        switch (iArg)
                        {
                            case 1: mPublic_IP = args[iArg];  break;
                            case 2: mDomainname = args[iArg];  break;
                            case 3: mComputername = args[iArg];  break;
                            case 4: mUsername = args[iArg];  break;
                            case 5: mFoldername = args[iArg];  break;
                            case 6: mSysname = args[iArg];  break;
                            case 7: mCustomerID = args[iArg]; break;  // ค่าที่ส่งมาครั้งแรก 
                        }
                    }
                    MySQL4CustomerID(); // mCustomerID จะเปลี่ยนค่าจาก CustomerID.txt
                    lines = File.ReadAllLines(flCustomerID);
                    mCustomerID = lines[0];
                    Pok_Show("CustomerID : " + mCustomerID);
                    ///
                    MySQL4Update();
                    MySQLchkForUsed();
                    break;
                case ("3"): // เปลี่ยนค่า ForUsed ตาม IP
                    mPublic_IP = args[1].Trim();
                    mForUsed= args[2].Trim();
                    MySQL4ForUsed(1);
                    break;
                case ("U"): // เปลี่ยนค่า ForUsed ตาม CustomerID
                    mCustomerID = args[1].Trim();
                    mForUsed = args[2].Trim();
                    MySQL4ForUsed(2);
                    break;
                case ("11"): Regis4List(); break;
                case ("12"):
                    // อ่านเพิ่มเติมจาก  args[]
                    mPublic_IP = "?";
                    mLatitude = "?";
                    mLongtitude = "?";
                    mMaccaddress = "?";
                    mCompanyname = "?";
                    mUsername = "?";
                    mAddress = "?";
                    mTelephone = "?";
                    mSoftwareID = "?";
                    for (int iArg = 1; iArg < args.Length; iArg++)
                    {
                        switch (iArg)
                        {
                            case 1: mPublic_IP = args[iArg]; break;
                            case 2: mLatitude = args[iArg]; break;
                            case 3: mLongtitude = args[iArg]; break;
                            case 4: mMaccaddress = args[iArg]; break;
                            case 5: mCompanyname = args[iArg]; break;
                            case 6: mUsername = args[iArg]; break;
                            case 7: mAddress = args[iArg]; break;
                            case 8: mTelephone = args[iArg]; break;
                        }
                    }
                    MySQL4CustomerID(); // mCustomerID จะเปลี่ยนค่าจาก CustomerID.txt
                    lines = File.ReadAllLines(flCustomerID);
                    mCustomerID = lines[0];
                    Pok_Show("CustomerID : " + mCustomerID);
                    //
                    Regis4Update();
                    break;
                case ("W"): // เพื่อสร้างหรือลบ SoftwareFor.Quit 
                    // ดึง Customer ID จากตัวแปร 
                    mCustomerID = args[1];
                    Pok_Show("CustomerID : " + mCustomerID);
                    MySQLchkForUsed();
                    break;
                case ("M"): // เพื่อลบ SoftwareFor.Quit ประจำที่เครื่องนั้น
                   // ดึง Customer ID ประจำเครื่อง
                    if (File.Exists(flCustomerID))
                    {
                        lines = File.ReadAllLines(flCustomerID);
                        mCustomerID = lines[0];
                        Pok_Show("CustomerID : " + mCustomerID);
                        MySQLchkForUsed();
                    }
                    break;
            }
            /// เลิกใช้งาน ปิดDatabase        
            MySQL4Close();
            if (cpFlag=="12") // Register Update ตรวจสอบอีกครั้งเพื่อส่งไฟล์ใน Line 
            {
                if (File.Exists(@"C:\TempVFP\FirstLogin.jpg"))
                {
                    FTPupload(@"C:\TempVFP\FirstLogin.jpg", "FirstLogin.jpg");
                    cTemp = "2 9s2uTS8ibhTC4dNpJEmM6FM3Qh7HKUGRcxpYi7CvkZn ";
                    if (File.Exists("FirstUserLogin.txt"))
                    {
                        lines = File.ReadAllLines("FirstUserLogin.txt");
                        cTemp = cTemp + lines[1].Trim();
                    }
                    else { cTemp = cTemp + "Register_OK"; }
                    cTemp = cTemp + "+0+0+http://uyod.net/uyod_member/FirstLogin.jpg";
                    Util.Program.Pok_Process("Util_Pok2", cTemp);
                }
            }
            Pok_Show("จบการทำงาน uYod4SQL.exe");
        }
    }
}

