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

ตัวอย่าง 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#

การ Get Client IP Address บน ASP.NET Core 3

สร้างโปรเจ็กส์ทดสอบแบบ WebApplication แล้วเลือก API ตั้งชื่อ WebApi

ทำการ inject HttpContextAccessor ในไฟล์ Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace WebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

เพิ่ม API Controller ชื่อ ValuesController.cs

ประกาศตัวแปร httpContextAccessor และกำหนดค่าให้ตัวแปรใน Constructor

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        public ValuesController(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        // GET: api/<ValuesController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            string clientIpAddress = this.httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
            return new string[] { "clientIpAddress ", clientIpAddress };
        }
    }
}

รันโปรแกรมแล้วลองเรียกไปที่ http://localhost:58691/api/values

จะได้

["clientIpAddress ","::1"]

ถ้าจะจัดเก็บค่า IP Address ลง database ก็กำหนด ขนาด field ไว้ที่ 45 characters

Link

HTML เบื้องต้น

ไฟล์ html

<!DOCTYPE html>
<html>

<head>
    <title>Page Title</title>
</head>

<body>

    <h1>This is a Heading</h1>
    <p>This is a paragraph.</p>

</body>

</html>

ไฟล์ html + Bootstrap 4

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
        integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <title>Hello, world!</title>
</head>

<body>
    <h1>Hello, world!</h1>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
        integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
        integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
        crossorigin="anonymous"></script>
</body>

</html>

bootstrap 4 มี header ตรงกลาง และมี 3 คอลัมน์

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
        integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <title>Hello, world!</title>
</head>

<body>
    <div class="jumbotron text-center">
        <h1>Hello, world!</h1>
        <p>Resize this responsive page to see the effect!</p>
    </div>

    <div class="container">
        <div class="row">
            <div class="col-sm-4">
                <h3>Column 1</h3>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
                <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
            </div>
            <div class="col-sm-4">
                <h3>Column 2</h3>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
                <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
            </div>
            <div class="col-sm-4">
                <h3>Column 3</h3>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
                <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
            </div>
        </div>
    </div>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
        integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
        integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
        crossorigin="anonymous"></script>
</body>

</html>