ตรวจสอบเลขบัตรประชาชน

ตัวอย่าง 1-2345-67890-12-1

  1. นำไปคูณเลขประจำตำแหน่ง : (1*13)+(2*12)+(3*11)+(4*10)+(5*9)+(6*8)+(7*7)+(8*6)+(9*5)+(0*4)+(1*3)+(2*2) = 352
  2. หารเอาเศษด้วย : 11 352%11= 0
  3. นำ 11 ตั้งแล้วลบเศษที่ได้จากการหารในข้อ 2 : 11 – 0 = 11 (เอาเลขหลักหน่วย) ดังนั้น Check Digit คือ 1
  4. จะได้ : 1-2345-67890-12-1
private static bool validateIDCard(string idcardno)
{
    if (string.IsNullOrEmpty(idcardno))
    {
        log.Info(string.Format("idcardno IsNullOrEmpty '{0}'", idcardno));
        return false;
    }

    if (idcardno.Length != 13)
    {
        log.Info(string.Format("idcardno Length != 13 '{0}'", idcardno));
        return false;
    }

    bool isDigit = Regex.IsMatch(idcardno, @"^[0-9]*$");
    if (!isDigit)
    {
        log.Info(string.Format("idcardno is not only digit '{0}'", idcardno));
        return false;
    }


    int sum = 0;
    for (int i = 0; i < 12; i++)
    {
        sum += Convert.ToInt32(idcardno.Substring(i, 1)) * (13 - i);
    }

    int checksum = (11 - (sum % 11)) % 10;
    if (checksum != Convert.ToInt32(idcardno.Substring(12)))
    {
        log.Info(string.Format("idcardno checksum error '{0}', sum = '{1}', checksum = '{2}'", idcardno, sum, checksum));
        return false;
    }

    return true;
}
Posted in C#

Console เชื่อมต่อ MySQL

  1. ติดตั้ง MySql.Data ผ่าน NuGet
  2. สร้างโฟลเดอร์ mysql
  3. สร้างคลาส mysql/sql.cs
  4. สร้างคลาส mysql/qry.cs
  5. แก้ไขไฟล์ App.config
  6. แก้ไขไฟล์ Program.cs

1.ติดตั้ง MySql.Data ผ่าน NuGet

PM> Install-Package MySql.Data -Version 6.9.12

2.สร้างโฟลเดอร์ mysql

3.สร้างคลาส mysql/sql.cs

using MySql.Data.MySqlClient;
using System;
using System.Configuration;
using System.Data;
using System.Reflection;
using System.Text.RegularExpressions;

namespace ConsoleApp1.mysql
{
    class sql
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static string connMySql = ConfigurationManager.AppSettings.Get("connMySql");


        public static DataTable ExecuteQuery(string query)
        {
            query = Regex.Replace(query, @"\s+", " ");
            log.Debug(query);

            try
            {
                using (MySqlConnection conn = new MySqlConnection(connMySql))
                {
                    conn.Open();
                    MySqlDataAdapter da = new MySqlDataAdapter(query, conn);
                    System.Data.DataSet ds = new System.Data.DataSet("Names");
                    da.Fill(ds);
                    DataTable dt = ds.Tables[0];

                    conn.Close();

                    log.Debug(string.Format("  found {0} record.", dt.Rows.Count));
                    return dt;
                }
            }
            catch (MySqlException ex)
            {
                log.Error(ex.Message);
                return null;
            }
        }

        public static DataTable ExecuteReader(string query)
        {
            //log.Info(string.Format("  '{0}'", connIIA.Split(';')[0]));

            query = Regex.Replace(query, @"\s+", " ");
            log.Debug(query);

            DataSet ds;
            try
            {
                // Open a connection
                using (MySqlConnection conn = new MySqlConnection(connMySql))
                {
                    conn.Open();
                    using (MySqlTransaction trans = conn.BeginTransaction(IsolationLevel.ReadUncommitted))
                    {
                        // Create an SQL command
                        using (MySqlCommand cmd = new MySqlCommand(query, conn))
                        {
                            cmd.Transaction = trans;
                            //log.Debug(string.Format("cmd.CommandTimeout='{0}'", cmd.CommandTimeout));
                            cmd.CommandTimeout = 5000;
                            //log.Debug(string.Format("cmd.CommandTimeout='{0}'", cmd.CommandTimeout));

                            using (MySqlDataReader dr = cmd.ExecuteReader())
                            {
                                // Write the data to the console
                                //while (dr.Read())
                                //{
                                //    Console.WriteLine(dr["lotno"].ToString());
                                //}
                                ds = new System.Data.DataSet("Names");
                                while (!dr.IsClosed)
                                    ds.Tables.Add().Load(dr);
                                dr.Close();

                                DataTable dt = ds.Tables[0];

                                // Close the connection
                                conn.Close();

                                log.Debug(string.Format("  found {0} record.", dt.Rows.Count));
                                return dt;
                            }
                        }
                    }
                }
            }
            catch (MySqlException ex)
            {
                log.Error(ex.Message);
                return null;
            }
        }

        public static string ExecuteNonQuery(string query)
        {
            query = Regex.Replace(query, @"\s+", " ");
            log.Debug(query);

            try
            {
                string result = "";
                using (var conn = new MySqlConnection(connMySql))
                {
                    conn.Open();

                    using (MySqlTransaction myTrans = conn.BeginTransaction(IsolationLevel.ReadCommitted))
                    {
                        // Assign transaction object for a pending local transaction
                        using (MySqlCommand myCommand = new MySqlCommand())
                        {
                            myCommand.Connection = conn;
                            myCommand.Transaction = myTrans;

                            try
                            {
                                myCommand.CommandText = query;
                                myCommand.ExecuteNonQuery();

                                myTrans.Commit();
                                result = "success";
                                log.Info(result);
                            }
                            catch (Exception ex)
                            {
                                myTrans.Rollback();
                                result = ex.Message;
                                log.Error(ex.Message);
                            }
                        }
                    }
                }
                return result;
            }
            catch (MySqlException ex)
            {
                log.Error(ex.Message);
                return null;
            }
        }

    } // end class
}

4.สร้างคลาส mysql/qry.cs

using System.Reflection;

namespace ConsoleApp1.mysql
{
    public class qry
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public static string QuerySelectData(string param1)
        {
            log.Info(string.Format("Parameter ({0})", param1));

            string query = string.Format(@"", param1);
            return query;
        }

        public static string QuerySelectData(string param1, string param2)
        {
            log.Info(string.Format("Parameter ({0}, {1})", param1, param2));

            string query = string.Format(@"", param1, param2);
            return query;
        }

    } // end class
}

5.แก้ไขไฟล์ App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>

  <appSettings>
    <add key="connMySql" value="server=xxx.xxx.xxx.xxx;database=[dbname];uid=[userid];pwd=[userpass];" />
  </appSettings>

  <system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.12.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>
</configuration>

6.แก้ไขไฟล์ Program.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        static void Main(string[] args)
        {
            try
            {
                log.Info("*********************************");
                log.Info("************* BEGIN *************");
                log.Info(AppDomain.CurrentDomain.FriendlyName);


                // Check AppSettings in App.config
                if (!checkConfig())
                {
                    log.Error("Missing some config");
                    return;
                }


                string connMySql = ConfigurationManager.AppSettings.Get("connMySql");
                log.Info(string.Format("  '{0}'", connMySql.Split(';')[0]));

                mysql.sql.ExecuteReader(mysql.qry.QuerySelectData(""));


                log.Info("************** END **************");
                log.Info("");
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                log.Error(ex.ToString());
            }
        } // end main

        private static bool checkConfig()
        {
            string connMySql = ConfigurationManager.AppSettings.Get("connMySql");
            if (string.IsNullOrEmpty(connMySql))
            {
                log.Error("'connMySql' not found in App.config");
                return false;
            }

            return true;
        }
    } // end class
}

ส่งอีเมลจาก gmail ด้วย C#

ทำการ อนุญาตแอปที่มีความปลอดภัยน้อย ใน gmail ก่อน

สร้างโปรเจ็กส์แบบ WindowsForm

เพิ่ม button1

using System;
using System.Net.Mail;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string displayName = "Phaisarn Sutheebanjard";
            string userName = "xxxxx@gmail.com";
            string password = "yyyyy";
            string mailto = "mr.phaisarn@gmail.com";

            using (SmtpClient smtp = new SmtpClient())
            {
                // email
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(userName, displayName);
                mail.To.Add(mailto);
                mail.Subject = "Greeting";
                mail.Body = string.Format("Hello World!");

                // smtp
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.UseDefaultCredentials = false;
                smtp.EnableSsl = true;
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.Credentials = new System.Net.NetworkCredential(userName, password);
                smtp.Send(mail);
                MessageBox.Show("Mail Sent");
            }
        }
    }
}

Link

Posted in C#

C# Base64

นำสตริง 111 มาทำเป็น Base64 แล้ว ถอดกลับออกมา

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string plainText1 = "111";
            byte[] byteData1 = System.Text.ASCIIEncoding.ASCII.GetBytes(plainText1);
            string encodeText = System.Convert.ToBase64String(byteData1);
            Console.WriteLine(encodeText);

            byte[] byteData2 = System.Convert.FromBase64String(encodeText);
            string plainText2 = System.Text.ASCIIEncoding.ASCII.GetString(byteData2);
            Console.WriteLine(plainText2);
        }
    }
}

// MTEx
// 111