Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,030

HOME > .NET Framework > Forum > ให้ user กรอกที่อยู่แล้วให้โปรแกรมมันสามารถแยกว่าอันไหนเป็น จังหวัด อำเภอ ตำบล



 

ให้ user กรอกที่อยู่แล้วให้โปรแกรมมันสามารถแยกว่าอันไหนเป็น จังหวัด อำเภอ ตำบล

 



Topic : 042823



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์




เรื่องมีอยู่ว่าต้องการให้ user กรอกช่องที่อยู่ ซึ่งประกอบด้วย จังหวัด อำเภอ ตำบล

โดยให้ dependent dropdownlist ก็คือเลือกจังหวัด ใน dropdownlist แรก

dropdownlist ที่สองก็แสดงอำเภอในจังหวัด พอเลือกอำเภอ dropdownlist ที่สาม

ก็แสดงตำบลมาให้เลือก ปรากฎว่า user บ่นอุบเลยครับ เรื่องมากจริงๆ แค่กรอกข้อมูล

ไม่มีพันเรคคอร์ดเอง -_-" ใช้เวลากรอกข้อมูลเรคคอร์ดละ 2-3 นาทีแค่ก็บอกไม่ไหวแล้ว

จะขอกรอกใส่ excel แล้วให้โปรแกรมอ่านข้อมูลเก็บลงฐานข้อมูล จะทำมันก็ทำได้อยู่หรอกนะ

แต่มันก็ติดปัญหาอีกนั้นแหละ คือ กรณี user พิมพ์ผิดอ่ะ แล้วโปรแกรมมันจะเอาอะไรไปแมพ

กับโค้ดเพื่อเอาไปเก็บลงฐานข้อมูลละครับ คอมมันไม่ได้ฉลาดขนาดแยกแยะได้นะครับว่า

อันไหนคืออะไร ชื่ออำเภอ ตำบลก็ซ้ำกันตั้งแยะ มันจะรู้ได้อย่างไรว่าจะเอาโค้ดไหนไปใช้

พอโดนบ่นเยอะๆ ก็เริ่มรำคาญ ก็เลยเริ่มคิดวิธีแก้ไขนั้นคือ

สอนให้โปรแกรมมันรู้จักอ่านและเข้าใจที่อยู่ที่ป้อนมันซะเลย ก็เอไอดีๆ นี่แหละ



Tag : - - - -







Move To Hilight (Stock) 
Send To Friend.Bookmark.
Date : 2010-05-13 11:48:38 By : tungman View : 3899 Reply : 8
 

 

No. 1



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


สิ่งที่ต้องการอย่างแรกเลยคือ ฐานข้อมูลตาราง จังหวัด อำเภอ ตำบล

ซึ่งของผมมีอยู่แล้วโดยเรียกจาก webservice ของบริษัท แต่ถ้าไม่มีล่ะ

อิอิ เขาว่าถ้าเราเริ่มรู้อะไรเยอะๆ เนี่ยถ้าเอาความรู้ไปใช้ในทางที่เป็นประโยชน์

มันก็เกิดประโยชน์ แต่ถ้าเอาไปใช้ในทางที่ผิดนี่มันก็เป็นอันตรายมากๆ ซึ่งผมเห็นเหยื่อแล้ว

คือ http://www.thaitambon.com/tambon/default.htm อิอิ ขอดูดข้อมูลหน่อยนะ จะเอาไปเก็บลงฐานข้อมูล

ไว้สำหรับตรวจสอบชื่อว่าถูกต้องหรือเปล่า และใช้เก็บโค้ดด้วย (มีความสุขจริงๆ ที่ได้ละเมินสิทธิ์ของผู้อื่น อิอิ)

เริ่มเขียนเลยแล้วกัน

1. ไป config ที่ web.config เพิ่ม connection string เพื่อติดต่อฐานข้อมูล ลืมบอกไป ผมเขียนเป็น web app แต่ดัดแปลงหน่อยก็เอาไปใช้ใน win app ได้แล้ว เพราะเขียนเป็น class

web.config
  //ตัวอย่างใน web.config
  //<connectionStrings>
  //    <add name="SqlConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SqlDatabase;Integrated Security=True;" providerName="System.Data.SqlClient"/>
  //</connectionStrings>


2. คลิกขวาที่ชื่อ project ใน project solution เลือก add new item เป็น class ตั้งชื่อว่า SqlDatabaseManager ถ้าเรายังไม่มี folder app_code มันจะถามว่าจะสร้างไหมและจะเอา class ไปเก็บด้วย ให้ตอบ Yesssss แล้วก็อบโค้ดด้านล่างไปใส่ เป็น abstract base class สำหรับติดต่อและจัดการฐานข้อมูล

SqlDatabaseManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.Configuration;

#region ========== Class SqlDatabaseManager ==========
/// <summary>
/// Summary description for SqlDatabase
/// </summary>
public abstract class SqlDatabaseManager
{
    #region ========== Field ==========
    private SqlConnection sqlConnection;
    private SqlCommand sqlCommand;
    private SqlTransaction sqlTransaction;
    private List<string> errorCommand;

    private string sqlConnectionString = string.Empty;
    private string sqlConnectionKeyName = string.Empty;
    private string sqlCommandString = string.Empty;
    private string commandMessage = "You must execute command.";
    private bool commandSuccess = false;
    private bool transaction = false;
    private int rowsAffected = 0;
    #endregion

    #region ========= Constructor ==========
    /// <summary>
    /// Use sql connection string from web.config configulation.
    /// </summary>
    public SqlDatabaseManager()
    {
        if (WebConfigurationManager.ConnectionStrings["SqlConnectionString"] != null)
        {
            //สำหรับ web.config ที่มีการ add connection string ชื่อ SqlConnectionString เอาไว้
            //
            //ตัวอย่างใน web.config
            //<connectionStrings>
            //    <add name="SqlConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SqlDatabase;Integrated Security=True;" providerName="System.Data.SqlClient"/>
            //</connectionStrings>

            sqlConnectionKeyName = "SqlConnectionString";
            sqlConnectionString = WebConfigurationManager.ConnectionStrings["SqlConnectionString"].ToString();
            sqlConnection = new SqlConnection(sqlConnectionString);
        }
        else
        {
            sqlConnection = new SqlConnection();        
        }
    }

    /// <summary>
    /// Use sql connection string from web.config configulation by key name.
    /// </summary>
    public SqlDatabaseManager(string SqlConnectionKeyName)
    {
        sqlConnectionKeyName = SqlConnectionKeyName;
        sqlConnectionString = WebConfigurationManager.ConnectionStrings[sqlConnectionKeyName].ToString();
        sqlConnection = new SqlConnection(sqlConnectionString);
    }

    /// <summary>
    /// Use sql connection string by user define.
    /// </summary>
    public SqlDatabaseManager(string SqlConnectionKeyName, string SqlConnectionString)
    {
        sqlConnectionKeyName = SqlConnectionKeyName;
        sqlConnectionString = SqlConnectionString;
        sqlConnection = new SqlConnection(sqlConnectionString);
    }    
    #endregion

    #region ========== Property ==========
    /// <summary>
    /// Gets or sets Sql connection key name from web.config.
    /// </summary>
    protected virtual string ConnectionKeyName
    {
        get { return sqlConnectionKeyName; }
        set
        {
            sqlConnectionKeyName = value;
            sqlConnectionString = WebConfigurationManager.ConnectionStrings[sqlConnectionKeyName].ToString();
            sqlConnection = new SqlConnection(sqlConnectionString);   
        }
    }

    /// <summary>
    /// Gets or sets Sql connection.
    /// </summary>
    protected virtual string ConnectionString
    {
        get { return sqlConnectionString; }
        set 
        {
            sqlConnectionString = value;
            sqlConnection = new SqlConnection(sqlConnectionString);
        }
    }

    /// <summary>
    /// Gets or sets Sql command.
    /// </summary>
    protected virtual string CommandString
    {
        get { return sqlCommandString; }
        set
        {
            sqlCommandString = ConvertDateCommand(value);
            sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);

            commandMessage = "You must execute command.";
            commandSuccess = false;
            rowsAffected = 0;

            if (transaction)
                sqlCommand.Transaction = sqlTransaction;
        }
    }

    /// <summary>
    /// Check for Sql command.
    /// </summary>
    protected virtual bool IsSuccess
    {
        get { return commandSuccess; }
    }

    /// <summary>
    /// Gets message from Sql command.
    /// </summary>
    protected virtual string Message
    {
        get { return commandMessage; }
    }

    /// <summary>
    /// Gets Number of rows affected.
    /// </summary>
    protected virtual int RowsAffected
    {
        get { return rowsAffected; }
    }
    #endregion

    #region ========== Method ==========
    /// <summary>
    /// Add the parameter value to the sql command.
    /// </summary>
    /// <param name="ParameterName">The name of Parameter.</param>
    /// <param name="ParameterValue">The value to be added.</param>
    protected virtual void AddParameter(string ParameterName, object ParameterValue)
    {
        sqlCommand.Parameters.AddWithValue(ParameterName, ParameterValue);
    }

    /// <summary>
    /// Add the parameter value to the sql command.
    /// </summary>
    ///<param name="ParameterName">The name of the parameter.</param>
    ///<param name="SqlDataType">One of the SqlDbType  values.</param>
    ///<param name="Size">The column length.</param>
    ///<param name="ColumnName">The name of the source column.</param>
    protected virtual void AddParameter(string ParameterName, SqlDbType SqlDataType, int Size, string ColumnName)
    {
        sqlCommand.Parameters.Add(ParameterName, SqlDataType, Size, ColumnName);
    }

    /// <summary>
    /// Start Sql Transaction.
    /// </summary>
    protected virtual void TransactionStart()
    {
        transaction = true;
        errorCommand = new List<string>();

        if (sqlConnection.State != ConnectionState.Open)
            sqlConnection.Open();

        sqlTransaction = sqlConnection.BeginTransaction(IsolationLevel.ReadCommitted);    
    }

    /// <summary>
    /// Insert the DataTable to database.
    /// </summary>
    /// <param name="DataSource">The name of the DataTable. </param>
    /// <returns>Result of command.</returns>
    protected virtual bool Insert(DataTable DataSource)
    {
        bool result = false;

        try
        {
            SqlDataAdapter sqlAdapter = new SqlDataAdapter();
            sqlAdapter.InsertCommand = sqlCommand;
            rowsAffected = sqlAdapter.Update(DataSource);

            commandMessage = "Command is successfully.";
            commandSuccess = true;
            result = true;
        }
        catch (Exception ex)
        {
            commandMessage = ErrorMessage(ex.Message);
            commandSuccess = false;
        }

        return result;
    }

    /// <summary>
    /// Update the database by DataTeble.
    /// </summary>
    /// <param name="DataSource">The name of the DataTable. </param>
    /// <returns>Result of command.</returns>
    protected virtual bool Update(DataTable DataSource)
    {
        bool result = false;

        try
        {
            SqlDataAdapter sqlAdapter = new SqlDataAdapter();
            sqlAdapter.UpdateCommand = sqlCommand;
            rowsAffected = sqlAdapter.Update(DataSource);

            commandMessage = "Command is successfully.";
            commandSuccess = true;
            result = true;
        }
        catch (Exception ex)
        {
            commandMessage = ErrorMessage(ex.Message);
            commandSuccess = false;
        }

        return result;
    }

    /// <summary>
    /// Delete the database by DataTeble.
    /// </summary>
    /// <param name="DataSource">The name of the DataTable. </param>
    /// <returns>Result of command.</returns>
    protected virtual bool Delete(DataTable DataSource)
    {
        bool result = false;

        try
        {
            SqlDataAdapter sqlAdapter = new SqlDataAdapter();
            sqlAdapter.DeleteCommand = sqlCommand;
            rowsAffected = sqlAdapter.Update(DataSource);

            commandMessage = "Command is successfully.";
            commandSuccess = true;
            result = true;
        }
        catch (Exception ex)
        {
            commandMessage = ErrorMessage(ex.Message);
            commandSuccess = false;
        }

        return result;
    }
    
    /// <summary>
    /// Execute Sql Transaction.
    /// </summary>
    /// <returns>Result of transaction.</returns>
    protected virtual bool ExecuteTransaction()
    {
        transaction = false;

        if (errorCommand.Count == 0)
        {
            sqlTransaction.Commit();

            commandMessage = "All command is successfully. <font color=\"darkgreen\">Transaction Commited.</font>";
            commandSuccess = true;
        }
        else
        {
            sqlTransaction.Rollback();

            string ErrorText = "Some command has error. <font color=\"red\">Transaction Rollback.</font><br />Error in: <br />";

            foreach (string aErrorSqlCommand in errorCommand)
            {
                ErrorText += aErrorSqlCommand + "<br />";
            }

            commandMessage = ErrorText;
            commandSuccess = false;
        }

        errorCommand.Clear();

        if (sqlConnection.State == ConnectionState.Open)
            sqlConnection.Close();

        return commandSuccess;
    }

    /// <summary>
    /// Execute Query Sql command.
    /// </summary>
    /// <returns>Query data in DataTable.</returns>
    protected virtual DataTable ExecuteQuery()
    {
        DataTable dataTable = new DataTable();

        try
        {
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
            sqlDataAdapter.Fill(dataTable);
            sqlDataAdapter.Dispose();

            commandMessage = "Command is successfully.";
            commandSuccess = true;
        }
        catch (Exception ex)
        {
            commandMessage = ErrorMessage(ex.Message);
            commandSuccess = false;
        }

        rowsAffected = dataTable.Rows.Count;

        return dataTable;
    }

    /// <summary>
    /// Execute Scalar Sql command.
    /// </summary>
    /// <returns>Object of value.</returns>
    protected virtual object ExecuteScalar()
    {
        object Result = 0;

        try
        {
            if (transaction)
            {
                Result = sqlCommand.ExecuteScalar();
            }
            else
            {
                if (sqlConnection.State != ConnectionState.Open)
                    sqlConnection.Open();

                Result = sqlCommand.ExecuteScalar();
                sqlConnection.Close();
            }

            commandMessage = "Command is successfully.";
            commandSuccess = true;
        }
        catch (Exception ex)
        {
            commandMessage = ErrorMessage(ex.Message);
            commandSuccess = false;
            if (transaction) AddErrorCommand(sqlCommandString, ex.Message);
        }

        return Result;
    }

    /// <summary>
    /// Execute Non Query Sql command.
    /// </summary>
    /// <returns>Result of execute command.</returns>
    protected virtual bool ExecuteNonQuery()
    {
        rowsAffected = 0;

        try
        {
            if (transaction)
            {
                rowsAffected = sqlCommand.ExecuteNonQuery();
            }
            else
            {
                if (sqlConnection.State != ConnectionState.Open)
                    sqlConnection.Open();

                rowsAffected = sqlCommand.ExecuteNonQuery();
                sqlConnection.Close();
            }

            commandMessage = "Command is successfully.";
            commandSuccess = true;
        }
        catch (Exception ex)
        {
            commandMessage = ErrorMessage(ex.Message);
            commandSuccess = false;
            if (transaction) AddErrorCommand(sqlCommandString, ex.Message);
        }

        return commandSuccess;
    }

    /// <summary>
    /// Build error message.
    /// </summary>
    /// <param name="Message">Message string.</param>
    /// <returns>Error message string.</returns>
    protected virtual string ErrorMessage(string MessageString)
    {
        return "<font color=\"red\">Command error.</font> " + MessageString;
    }

    /// <summary>
    /// Add error sql command to string collections.
    /// </summary>
    /// <param name="commandString">The sql command.</param>
    /// <param name="errorMessage">The error message.</param>
    protected virtual void AddErrorCommand(string commandString, string errorMessage)
    {
        errorCommand.Add(commandString + " <font color=\"red\">[Error message: " + errorMessage + "]</font>");
    }

    /// <summary>
    /// Convert native command to sql command.
    /// </summary>
    /// <param name="commandString">The native sql command.</param>
    /// <returns>The standard sql command.</returns>
    protected virtual string ConvertDateCommand(string commandString)
    {
        string SmallDateTimePattern = "[sS][mM][aA][lL][lL][dD][aA][tT][eE][tT][iI][mM][eE]\\([@][0-9a-zA-Z\\s]{1,}\\)";
        Regex SmallDateTimeRgx = new Regex(SmallDateTimePattern);

        foreach (Match SmallDateTimeMatchCase in SmallDateTimeRgx.Matches(commandString))
        {
            string MatchCasePattern = "^[sS][mM][aA][lL][lL][dD][aA][tT][eE][tT][iI][mM][eE]";
            Regex MatchCaseRgx = new Regex(MatchCasePattern);
            Match RemoveMatch = MatchCaseRgx.Match(SmallDateTimeMatchCase.Value);
            string TempMatchCase = SmallDateTimeMatchCase.Value.Replace(RemoveMatch.Value, "");

            commandString = commandString.Replace(SmallDateTimeMatchCase.Value, TempMatchCase.Replace("(", "Convert(SmallDateTime, ").Replace(")", ", 103)"));
        }

        string DateTimePattern = "[dD][aA][tT][eE][tT][iI][mM][eE]\\([@][0-9a-zA-Z\\s]{1,}\\)";
        Regex DateTimeRgx = new Regex(DateTimePattern);

        foreach (Match DateTimeMatchCase in DateTimeRgx.Matches(commandString))
        {
            string MatchCasePattern = "^[dD][aA][tT][eE][tT][iI][mM][eE]";
            Regex MatchCaseRgx = new Regex(MatchCasePattern);
            Match RemoveMatch = MatchCaseRgx.Match(DateTimeMatchCase.Value);
            string TempMatchCase = DateTimeMatchCase.Value.Replace(RemoveMatch.Value, "");

            commandString = commandString.Replace(DateTimeMatchCase.Value, TempMatchCase.Replace("(", "Convert(DateTime, ").Replace(")", ", 103)"));
        }

        return commandString;
    }
    #endregion
}
#endregion

#region ========== Class SqlConvert ==========
/// <summary>
/// Summary description for SqlConvert
/// </summary>
public sealed class SqlConvert
{
    /// <summary>
    /// Convert to byte[].
    /// </summary>
    /// <param name="BinaryStream">File upload binary stream.</param>
    /// <param name="StreamLength">Lenght of File upload binary stream.</param>
    /// <returns>Byte[] of binary stream.</returns>
    public static byte[] ToVarBinary(Stream BinaryStream, int StreamLength)
    {
        BinaryReader BinaryRead = new BinaryReader(BinaryStream);
        byte[] binaryData = BinaryRead.ReadBytes(StreamLength);

        return binaryData;
    }

    /// <summary>
    /// Convert to DataTime DataType with d/M/yyyy format.
    /// </summary>
    /// <param name="DateString">DateTime sring.</param>
    /// <returns>Datetime Type.</returns>
    public static DateTime ToDateTime(string DateString)
    {
        //ควรกำหนด culture ใน web.config เป็น th
        //
        //ตัวอย่างใน web.config
        //<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="th-TH" uiCulture="th-TH"/>

        return DateTime.ParseExact(DateString, "d/M/yyyy", CultureInfo.InvariantCulture);
    }

    /// <summary>
    /// Convert to DataTime DataType with user define format.
    /// </summary>
    /// <param name="DateString">DateTime sring.</param>
    /// <param name="DateFormat">DateTime Format</param>
    /// <returns>Datetime Type.</returns>
    public static DateTime ToDateTime(string DateString, string DateFormat)
    {
        //ควรกำหนด culture ใน web.config เป็น th
        //
        //ตัวอย่างใน web.config
        //<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="th-TH" uiCulture="th-TH"/>

        return DateTime.ParseExact(DateString, DateFormat, CultureInfo.InvariantCulture);
    }
}
#endregion







Date : 2010-05-13 12:03:57 By : tungman
 


 

No. 2



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


3. สร้าง class ชื่อ AddressData เพื่อขโมยข้อมูลจาก http://www.thaitambon.com/ อย่าตกใจครับ เราดูดข้อมูลแค่ครั้งเดียว พอมีข้อมูลแล้วเราก็ไม่ไปโหลดข้อมูลจากเขาแล้ว

AddressData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Configuration;

/// <summary>
/// Summary description for AddressData
/// </summary>
public class AddressData : SqlDatabaseManager
{
	public AddressData()
	{
		//
		// TODO: Add constructor logic here
		//
    }

    public void CreateAddressTable()
    {
        DataTable ProvinceTable = new DataTable();
        DataTable DistrictTable = new DataTable();
        DataTable SubDistrictTable = new DataTable();

        if (!TableExist("ProvinceTable"))
        {
            string RequestedProvince = RequestHtmlData("http://www.thaitambon.com/tambon/default.htm");
            ProvinceTable = GetProvinceData(RequestedProvince);

            CreateProvinceTable("ProvinceTable");
            FillProvinceData(ProvinceTable);
        }

        if (!TableExist("DistrictTable"))
        {
            foreach (DataRow ProvinceRow in ProvinceTable.Rows)
            {
                DataTable DisrtictTemp = new DataTable();
                DataTable SubDistrictTemp = new DataTable();

                string RequestDistrict = RequestHtmlData(string.Format("http://www.thaitambon.com/tambon/tamplist.asp?ID={0}", ProvinceRow["ProvinceCode"].ToString()));
                DisrtictTemp = GetDistrictData(RequestDistrict, ProvinceRow["ProvinceCode"].ToString());
                SubDistrictTemp = GetSubDistrictData(RequestDistrict);

                DistrictTable.Merge(DisrtictTemp);
                SubDistrictTable.Merge(SubDistrictTemp);

                DisrtictTemp.Dispose();
                SubDistrictTemp.Dispose();
            }

            CreateDistrictTable("DistrictTable");
            FillDistrictData(DistrictTable);
        }

        if (!TableExist("SubDistrictTable"))
        {
            CreateSubDistrictTable("SubDistrictTable");
            FillSubDistrictData(SubDistrictTable);
        }

        ProvinceTable.Dispose();
        DistrictTable.Dispose();
        SubDistrictTable.Dispose();
    }

    public void DeleteProvinceTable()
    {
        if (TableExist("ProvinceTable"))
            DropTable("ProvinceTable");
    }

    public void DeleteDistrictTable()
    {
        if (TableExist("DistrictTable"))
            DropTable("DistrictTable");  
    }

    public void DeleteSubDistrictTable()
    {
        if (TableExist("SubDistrictTable"))
            DropTable("SubDistrictTable");
    }
    
    private string RequestHtmlData(string Url)
    {
        WebClient objWebClient = new WebClient();

        byte[] byteRequestedHtml = Encoding.Convert(Encoding.GetEncoding("TIS-620"), Encoding.GetEncoding("UTF-8"), objWebClient.DownloadData(Url));
        UTF8Encoding objUtf8 = new UTF8Encoding();

        return objUtf8.GetString(byteRequestedHtml);
    }

    private bool TableExist(string TableName)
    {
        base.CommandString = string.Format("If Object_ID('{0}', 'U') Is Not Null Select 'true' Else Select 'false'", TableName);

        return Convert.ToBoolean(base.ExecuteScalar());
    }

    private bool DropTable(string TableName)
    {
        base.CommandString = string.Format("Drop Table [{0}]", TableName);

        return base.ExecuteNonQuery();
    }

    private bool CreateProvinceTable(string TableName)
    {
        base.CommandString = string.Format("Create Table [{0}] ([ProvinceID] int Identity(1,1) Primary Key Clustered, [ProvinceCode] nvarchar(50), [ProvincePrefix] nvarchar(50), [ProvinceName] nvarchar(50))", TableName);

        return base.ExecuteNonQuery();
    }

    private bool CreateDistrictTable(string TableName)
    {
        base.CommandString = string.Format("Create Table [{0}] ([DistrictID] int Identity(1,1) Primary Key Clustered, [ProvinceCode] nvarchar(50), [DistrictCode] nvarchar(50), [DistrictPrefix] nvarchar(50), [DistrictName] nvarchar(50))", TableName);

        return base.ExecuteNonQuery();
    }

    private bool CreateSubDistrictTable(string TableName)
    {
        base.CommandString = string.Format("Create Table [{0}] ([SubDistrictID] int Identity(1,1) Primary Key Clustered, [DistrictCode] nvarchar(50), [SubDistrictCode] nvarchar(50), [SubDistrictPrefix] nvarchar(50), [SubDistrictName] nvarchar(50))", TableName);

        return base.ExecuteNonQuery();
    }

    private bool FillProvinceData(DataTable ProvinceData)
    {
        base.CommandString = "Insert Into [ProvinceTable] ([ProvinceCode], [ProvincePrefix], [ProvinceName]) Values (@ProvinceCode, @ProvincePrefix, @ProvinceName)";
        base.AddParameter("@ProvinceCode", SqlDbType.NVarChar, 50, "ProvinceCode");
        base.AddParameter("@ProvincePrefix", SqlDbType.NVarChar, 50, "ProvincePrefix");
        base.AddParameter("@ProvinceName", SqlDbType.NVarChar, 50, "ProvinceName");

        return base.Insert(ProvinceData);
    }

    private bool FillDistrictData(DataTable DistrictData)
    {
        base.CommandString = "Insert Into [DistrictTable] ([ProvinceCode], [DistrictCode], [DistrictPrefix], [DistrictName]) Values (@ProvinceCode, @DistrictCode, @DistrictPrefix, @DistrictName)";
        base.AddParameter("@ProvinceCode", SqlDbType.NVarChar, 50, "ProvinceCode");
        base.AddParameter("@DistrictCode", SqlDbType.NVarChar, 50, "DistrictCode");
        base.AddParameter("@DistrictPrefix", SqlDbType.NVarChar, 50, "DistrictPrefix");
        base.AddParameter("@DistrictName", SqlDbType.NVarChar, 50, "DistrictName");

        return base.Insert(DistrictData);
    }

    private bool FillSubDistrictData(DataTable SubDistrictData)
    {
        base.CommandString = "Insert Into [SubDistrictTable] ([DistrictCode], [SubDistrictCode], [SubDistrictPrefix], [SubDistrictName]) Values (@DistrictCode, @SubDistrictCode, @SubDistrictPrefix, @SubDistrictName)";
        base.AddParameter("@DistrictCode", SqlDbType.NVarChar, 50, "DistrictCode");
        base.AddParameter("@SubDistrictCode", SqlDbType.NVarChar, 50, "SubDistrictCode");
        base.AddParameter("@SubDistrictPrefix", SqlDbType.NVarChar, 50, "SubDistrictPrefix");
        base.AddParameter("@SubDistrictName", SqlDbType.NVarChar, 50, "SubDistrictName");

        return base.Insert(SubDistrictData);
    }

    private DataTable GetProvinceData(string RequestHtml)
    {
        string[] TextArray = RequestHtml.Split(new char[] { '\n' });

        DataTable ProvinceTable = new DataTable();
        ProvinceTable.Columns.Add(new DataColumn("ProvinceCode", System.Type.GetType("System.String")));
        ProvinceTable.Columns.Add(new DataColumn("ProvincePrefix", System.Type.GetType("System.String")));
        ProvinceTable.Columns.Add(new DataColumn("ProvinceName", System.Type.GetType("System.String")));

        foreach (string aString in TextArray)
        {
            string ProvincePattern = "<ahref=\"tamplist.asp\\?ID=[0-9]{2}\">[\\D]{1,}</a>";
            Regex ProvinceRgx = new Regex(ProvincePattern);

            foreach (Match ProvinceMatchCase in ProvinceRgx.Matches(aString.Trim().Replace(" ", string.Empty)))
            {
                string[] ProvinceData = ProvinceMatchCase.Value.Replace("<ahref=\"tamplist.asp?ID=", string.Empty).Replace("\">", " ").Replace("</a>", string.Empty).Split(new char[] { ' ' }); ;

                DataRow ProvinceRow = ProvinceTable.NewRow();
                ProvinceRow["ProvinceCode"] = ProvinceData[0];
                if (ProvinceData[0] != "10") ProvinceRow["ProvincePrefix"] = "จังหวัด";
                ProvinceRow["ProvinceName"] = ProvinceData[1];
                ProvinceTable.Rows.Add(ProvinceRow);
            }
        }

        DataView ProvinceTableView = ProvinceTable.DefaultView;
        ProvinceTableView.Sort = "ProvinceCode ASC";

        return ProvinceTableView.ToTable();
    }

    private DataTable GetDistrictData(string RequestHtml, string ProvinceCode)
    {
        string[] TextArray = RequestHtml.Split(new char[] { '\n' });

        DataTable DistrictTable = new DataTable();
        DistrictTable.Columns.Add(new DataColumn("ProvinceCode", System.Type.GetType("System.String")));
        DistrictTable.Columns.Add(new DataColumn("DistrictCode", System.Type.GetType("System.String")));
        DistrictTable.Columns.Add(new DataColumn("DistrictPrefix", System.Type.GetType("System.String")));
        DistrictTable.Columns.Add(new DataColumn("DistrictName", System.Type.GetType("System.String")));

        foreach (string aString in TextArray)
        {
            string DistrictPattern = ">[0-9]{2}-[\\D]{1,}</td>";
            Regex DistrictRgx = new Regex(DistrictPattern);

            Regex Prefix1 = new Regex("^เขต");
            Regex Prefix2 = new Regex("^อำเภอ");
            Regex Prefix3 = new Regex("^กิ่งอำเภอ");

            foreach (Match DistrictMatchCase in DistrictRgx.Matches(aString.Trim().Replace(" ", string.Empty)))
            {
                string[] DistrictData = DistrictMatchCase.Value.Replace("</td>", string.Empty).Replace(">", string.Empty).Split(new char[] { '-' }); ;

                if (int.Parse(DistrictData[0]) < 80)
                {
                    string prifix = string.Empty;
                    string district = string.Empty;

                    if (Prefix1.Match(DistrictData[1]).Value == "เขต")
                    {
                        prifix = "เขต";
                        district = DistrictData[1].Replace("เขต", string.Empty);
                    }
                    else if (Prefix3.Match(DistrictData[1]).Value == "กิ่งอำเภอ")
                    {
                        prifix = "กิ่งอำเภอ";
                        district = DistrictData[1].Replace("กิ่งอำเภอ", string.Empty);
                    }
                    else if (Prefix2.Match(DistrictData[1]).Value == "อำเภอ")
                    {
                        prifix = "อำเภอ";
                        district = DistrictData[1].Replace("อำเภอ", string.Empty);
                    }
                    else
                    {
                        prifix = "อำเภอ";
                        district = DistrictData[1];
                    }

                    DataRow DistrictRow = DistrictTable.NewRow();
                    DistrictRow["ProvinceCode"] = ProvinceCode;
                    DistrictRow["DistrictCode"] = ProvinceCode + DistrictData[0];
                    DistrictRow["DistrictPrefix"] = prifix;
                    DistrictRow["DistrictName"] = district;
                    DistrictTable.Rows.Add(DistrictRow);
                }
            }
        }

        DataView DistrictTableView = DistrictTable.DefaultView;
        DistrictTableView.Sort = "DistrictCode ASC";

        return DistrictTableView.ToTable();
    }

    private DataTable GetSubDistrictData(string RequestHtml)
    {
        string[] TextArray = RequestHtml.Split(new char[] { '\n' });

        DataTable SubDistrictTable = new DataTable();
        SubDistrictTable.Columns.Add(new DataColumn("DistrictCode", System.Type.GetType("System.String")));
        SubDistrictTable.Columns.Add(new DataColumn("SubDistrictCode", System.Type.GetType("System.String")));
        SubDistrictTable.Columns.Add(new DataColumn("SubDistrictPrefix", System.Type.GetType("System.String")));
        SubDistrictTable.Columns.Add(new DataColumn("SubDistrictName", System.Type.GetType("System.String")));

        foreach (string aString in TextArray)
        {
            string SubDistrictPattern = "<b>[0-9]{6}-[\\D]{1,}</b>";
            Regex SubDistrictRgx = new Regex(SubDistrictPattern);

            Regex Prefix1 = new Regex("^แขวง");
            Regex Prefix2 = new Regex("^ตำบล");
            Regex Prefix3 = new Regex("^เทศบาลตำบล");
            Regex Prefix4 = new Regex("^เทศบาลเมือง");
            Regex Prefix5 = new Regex("^เทศบาลนคร");

            foreach (Match SubDistrictMatchCase in SubDistrictRgx.Matches(aString.Trim().Replace(" ", string.Empty)))
            {
                string[] SubDistrictData = SubDistrictMatchCase.Value.Replace("<b>", string.Empty).Replace("</b>", string.Empty).Split(new char[] { '-' }); ;

                if (int.Parse(SubDistrictData[0].Substring(4, 2)) < 50 && int.Parse(SubDistrictData[0].Substring(2, 2)) < 80)
                {
                    string prifix = string.Empty;
                    string subDistrict = string.Empty;

                    if (Prefix1.Match(SubDistrictData[1]).Value == "แขวง")
                    {
                        prifix = "แขวง";
                        subDistrict = SubDistrictData[1].Replace("แขวง", string.Empty);
                    }
                    else if (Prefix3.Match(SubDistrictData[1]).Value == "เทศบาลตำบล")
                    {
                        prifix = "เทศบาลตำบล";
                        subDistrict = SubDistrictData[1].Replace("เทศบาลตำบล", string.Empty);
                    }
                    else if (Prefix2.Match(SubDistrictData[1]).Value == "ตำบล")
                    {
                        prifix = "ตำบล";
                        subDistrict = SubDistrictData[1].Replace("ตำบล", string.Empty);
                    }
                    else if (Prefix4.Match(SubDistrictData[1]).Value == "เทศบาลเมือง")
                    {
                        prifix = "เทศบาลเมือง";
                        subDistrict = SubDistrictData[1].Replace("เทศบาลเมือง", string.Empty);
                    }
                    else if (Prefix5.Match(SubDistrictData[1]).Value == "เทศบาลนคร")
                    {
                        prifix = "เทศบาลนคร";
                        subDistrict = SubDistrictData[1].Replace("เทศบาลนคร", string.Empty);
                    }
                    else
                    {
                        prifix = "ตำบล";
                        subDistrict = SubDistrictData[1];
                    }
                    
                    DataRow SubDistrictRow = SubDistrictTable.NewRow();
                    SubDistrictRow["DistrictCode"] = SubDistrictData[0].Substring(0, 4);
                    SubDistrictRow["SubDistrictCode"] = SubDistrictData[0];
                    SubDistrictRow["SubDistrictPrefix"] = prifix;
                    SubDistrictRow["SubDistrictName"] = subDistrict;
                    SubDistrictTable.Rows.Add(SubDistrictRow);
                }
            }
        }

        DataView SubDistrictTableView = SubDistrictTable.DefaultView;
        SubDistrictTableView.Sort = "SubDistrictCode ASC";

        return SubDistrictTableView.ToTable();
    }
}

Date : 2010-05-13 12:07:46 By : tungman
 

 

No. 3



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


4. สร้าง class ชื่อ AddressTable เพื่อใช้สำหรับจัดการตารางฐานข้อมูล ProvinceTable DistrictTable และ SubDistrictTable ในฐานข้อมูลที่สร้างตะกี้

AddressTable.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data;

/// <summary>
/// Summary description for Address
/// </summary>
public class AddressTable : SqlDatabaseManager
{
	public AddressTable()
	{
		//
		// TODO: Add constructor logic here
		//
        AddressData address = new AddressData();
        address.CreateAddressTable();
	}

    public DataTable GetAllProvince()
    {
        base.CommandString = "Select [ProvinceID], [ProvinceCode], [ProvincePrefix], [ProvinceName] From [ProvinceTable]";

        return base.ExecuteQuery();
    }

    public DataTable GetDistrictByProvince(string ProvinceCode)
    {
        base.CommandString = "Select [ProvinceCode], [DistrictCode], [DistrictPrefix], [DistrictName] From [DistrictTable] Where [ProvinceCode]=@ProvinceCode";
        base.AddParameter("@ProvinceCode", ProvinceCode);

        return base.ExecuteQuery();
    }

    public DataTable GetSubDistrictByDistrict(string DistrictCode)
    {
        base.CommandString = "Select [DistrictCode], [SubDistrictCode], [SubDistrictPrefix], [SubDistrictName] From [SubDistrictTable] Where [DistrictCode]=@DistrictCode";
        base.AddParameter("@DistrictCode", DistrictCode);

        return base.ExecuteQuery(); ;
    }
}

Date : 2010-05-13 12:10:05 By : tungman
 


 

No. 4



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


5. สร้าง class ชื่อ AddressManager ซึ่งก็คือ ai ของเรา

AddressManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data;
using System.Text.RegularExpressions;

/// <summary>
/// Summary description for AddressManager
/// </summary>
public class AddressManager
{
    private AddressTable address;
    private string oldProvince;
    private string oldDistrict;
    private string oldSubDistrict;

    public AddressManager()
    {
        //
        // TODO: Add constructor logic here
        //
        address = new AddressTable();
        oldProvince = string.Empty;
        oldDistrict = string.Empty;
        oldSubDistrict = string.Empty;
    }

    public DataTable Extract(string AddressString)
    {
        string theAddress = string.Empty;

        string provinceUnCheck = string.Empty;
        string districtUnCheck = string.Empty;
        string subDistrictUnCheck = string.Empty;

        DataRow province = null;
        DataRow district = null;
        DataRow subDistrict = null;

        DataTable Dt = new DataTable();
        Dt.Columns.Add(new DataColumn("ProvinceCode", System.Type.GetType("System.String")));
        Dt.Columns.Add(new DataColumn("ProvinceRaw", System.Type.GetType("System.String")));
        Dt.Columns.Add(new DataColumn("ProvinceName", System.Type.GetType("System.String")));
        Dt.Columns.Add(new DataColumn("DistrictCode", System.Type.GetType("System.String")));
        Dt.Columns.Add(new DataColumn("DistrictRaw", System.Type.GetType("System.String")));
        Dt.Columns.Add(new DataColumn("DistrictName", System.Type.GetType("System.String")));
        Dt.Columns.Add(new DataColumn("SubDistrictCode", System.Type.GetType("System.String")));
        Dt.Columns.Add(new DataColumn("SubDistrictRaw", System.Type.GetType("System.String")));
        Dt.Columns.Add(new DataColumn("SubDistrictName", System.Type.GetType("System.String")));

        theAddress = AddressString.Replace(". ", ".");

        try
        {
            /* หาตำแหน่งจังหวัดด้วย regular expression */
            provinceUnCheck = ReadProvince(theAddress);

            /* ถ้าไม่เจอตำแหน่งจังหวัดให้ค้นด้วยฐานข้อมูล หรือถ้าเจอให้ตรวจสอบชื่อที่ถูกต้องด้วยฐานข้อมูล */
            province = (provinceUnCheck != string.Empty) ? ReadProvinceDatabase(provinceUnCheck) : ReadProvinceDatabaseFromRaw(theAddress);

            /* ถ้าพบชื่อจังหวัด */
            if (province != null)
            {
                /* ให้หาตำแหน่งอำเภอด้วย regular expression */
                districtUnCheck = ReadDistrict(theAddress);

                /* ถ้าไม่เจอตำแหน่งอำเภอให้ค้นด้วยฐานข้อมูล หรือถ้าเจอให้ตรวจสอบชื่อที่ถูกต้องด้วยฐานข้อมูล */
                district = (districtUnCheck != string.Empty) ? ReadDistrictDatabase(districtUnCheck, province["ProvinceCode"].ToString()) : ReadDistrictDatabaseFromRaw(theAddress, province["ProvinceCode"].ToString());

                /* ถ้าพบชื่ออำเภอ */
                if (district != null)
                {
                    /* ให้หาตำแหน่งตำบลด้วย regular expression */
                    subDistrictUnCheck = ReadSubDistrict(theAddress);

                    /* ถ้าไม่เจอตำแหน่งตำบลให้ค้นด้วยฐานข้อมูล หรือถ้าเจอให้ตรวจสอบชื่อที่ถูกต้องด้วยฐานข้อมูล */
                    subDistrict = (subDistrictUnCheck != string.Empty) ? ReadSubDistrictDatabase(subDistrictUnCheck, district["DistrictCode"].ToString()) : ReadSubDistrictDatabaseFromRaw(theAddress, district["DistrictCode"].ToString());
                }
            }
        }
        catch { }

        string strProvinceName = (province != null) ? province["ProvinceName"].ToString() : string.Empty;
        string strDistrictName = (district != null) ? district["DistrictName"].ToString() : string.Empty;
        string strSubDistrictName = (subDistrict != null) ? subDistrict["SubDistrictName"].ToString() : string.Empty;

        string ProvinceCode = (province != null) ? province["ProvinceCode"].ToString() : string.Empty;
        string DistrictCode = (district != null) ? district["DistrictCode"].ToString() : string.Empty;
        string SubDistrictCode = (subDistrict != null) ? subDistrict["SubDistrictCode"].ToString() : string.Empty;

        if (strProvinceName != string.Empty || strDistrictName != string.Empty || strSubDistrictName != string.Empty)
        {
            DataRow DrNew = Dt.NewRow();
            DrNew["ProvinceCode"] = ProvinceCode;
            DrNew["DistrictCode"] = DistrictCode;
            DrNew["SubDistrictCode"] = SubDistrictCode;
            DrNew["ProvinceName"] = strProvinceName;
            DrNew["DistrictName"] = strDistrictName;
            DrNew["SubDistrictName"] = strSubDistrictName;
            DrNew["ProvinceRaw"] = RemoveProvincePrefix(oldProvince);
            DrNew["DistrictRaw"] = RemoveDistrictPrefix(oldDistrict);
            DrNew["SubDistrictRaw"] = RemoveSubDistrictPrefix(oldSubDistrict);
            Dt.Rows.Add(DrNew);
        }

        return Dt;
    }

    public DataTable Extract(DataTable AddressTable, string ColumnName)
    { 
        DataTable Dt = new DataTable();
        int count = 0;

        foreach (DataRow Dr in AddressTable.Rows)
        {
            if (count == 0)
            {
                Dt = Extract(Dr[ColumnName].ToString()).Clone();
            }

            Dt.Merge(Extract(Dr[ColumnName].ToString()));
            count++;
        }

        return Dt;
    }

    private string ReadProvince(string AddressString)
    {
        string result = string.Empty;

        string ProvincePattern = "(กรุงเทพมหานคร|กรุงเทพฯ?|กทม\\.?)|((จังหวัด|จ\\.)[\\S]{1,})";
        Regex ProvinceCaseRegex = new Regex(ProvincePattern);
        Match ProvinceMatch = ProvinceCaseRegex.Match(AddressString);

        if (ProvinceMatch.Value != string.Empty)
        {
            string BangkokPattern = "กรุงเทพมหานคร|กรุงเทพฯ?|กทม\\.?";
            Regex BangkokCaseRegex = new Regex(BangkokPattern);
            Match BangkokMatch = BangkokCaseRegex.Match(ProvinceMatch.Value);

            oldProvince = (oldProvince == string.Empty) ? ProvinceMatch.Value : oldProvince;
            result = (BangkokMatch.Value != string.Empty) ? "กรุงเทพมหานคร" : ProvinceMatch.Value.Replace("จังหวัด", string.Empty).Replace("จ.", string.Empty);
        }

        return result;
    }

    private DataRow ReadProvinceDatabase(string ProvinceName)
    {
        DataRow Dr = null;
        DataTable Dt = new DataTable();
        Dt = address.GetAllProvince();

        for (int i = 0; i < ProvinceName.Length; i++)
        {
            string strSearch = string.Format("ProvinceName LIKE '{0}%'", ProvinceName.Substring(0, i));

            if (Dt.Select(strSearch).Length == 1)
            {
                Dr = Dt.Select(strSearch)[0]; ;
            }
        }

        return Dr;
    }

    private DataRow ReadProvinceDatabaseFromRaw(string AddressString)
    {
        DataRow Dr = null;
        DataTable Dt = new DataTable();
        Dt = address.GetAllProvince();

        string[] stringArray = AddressString.Split(new char[] { ' ' });

        foreach (string aString in stringArray)
        {
            for (int i = 0; i < aString.Length; i++)
            {
                string strSearch = string.Format("ProvinceName LIKE '{0}%'", aString.Substring(0, i));

                if (Dt.Select(strSearch).Length == 1)
                {
                    oldProvince = aString;
                    Dr = Dt.Select(strSearch)[0];
                    break;
                }
            }
        }

        return Dr;
    }

    private string ReadDistrict(string AddressString)
    {
        string result = string.Empty;

        string DistrictPattern = "(เขต|อำเภอ|อ\\.)[\\S]{1,}";
        Regex DistrictCaseRegex = new Regex(DistrictPattern);
        Match DistrictMatch = DistrictCaseRegex.Match(AddressString);

        if (DistrictMatch.Value != string.Empty)
        {
            string BangkokPattern = "^เขต";
            Regex BangkokCaseRegex = new Regex(BangkokPattern);
            Match BangkokMatch = BangkokCaseRegex.Match(DistrictMatch.Value);

            oldDistrict = (oldDistrict == string.Empty) ? DistrictMatch.Value : oldDistrict;

            result = (BangkokMatch.Value != string.Empty) ? DistrictMatch.Value.Replace("เขต", string.Empty) : DistrictMatch.Value.Replace("อำเภอ", string.Empty).Replace("อ.", string.Empty);
        }

        return result;
    }

    private DataRow ReadDistrictDatabase(string DistrictName, string ProvinceCode)
    {
        DataRow Dr = null;
        DataTable Dt = new DataTable();
        Dt = address.GetDistrictByProvince(ProvinceCode);

        for (int i = 0; i < DistrictName.Length; i++)
        {
            string strSearch = string.Format("DistrictName LIKE '{0}%'", DistrictName.Substring(0, i));

            if (Dt.Select(strSearch).Length == 1)
            {
                Dr = Dt.Select(strSearch)[0]; ;
            }
        }

        return Dr;
    }

    private DataRow ReadDistrictDatabaseFromRaw(string AddressString, string ProvinceCode)
    {
        DataTable Dt = new DataTable();
        Dt = address.GetDistrictByProvince(ProvinceCode);
        List<DataRow> rowArray = new List<DataRow>();
        List<int> matchArray = new List<int>();
        List<string> oldString = new List<string>(); 
        int match = 99;
        int index = 0;
        int count = 0;

        string[] stringArray = AddressString.Split(new char[] { ' ' });

        foreach (string aString in stringArray)
        {
            for (int i = 0; i < aString.Length; i++)
            {
                string strSearch = string.Format("DistrictName LIKE '{0}%'", aString.Substring(0, i));

                if (Dt.Select(strSearch).Length == 1)
                {
                    oldString.Add(aString);
                    rowArray.Add(Dt.Select(strSearch)[0]);
                    matchArray.Add(Math.Abs(Dt.Select(strSearch)[0]["DistrictName"].ToString().Length - aString.Length));
                }
            }
        }

        foreach (int m in matchArray)
        {
            if (m < match)
            {
                match = m;
                index = count;
            }

            count++;
        }

        oldDistrict = (oldDistrict == string.Empty) ? oldString[index] : oldDistrict;

        return (rowArray.Count > 0) ? rowArray[index] : null;
    }

    private string ReadSubDistrict(string AddressString)
    {
        string result = string.Empty;

        string SubDistrictPattern = "(แขวง|ตำบล|ต\\.)[\\S]{1,}";
        Regex SubDistrictCaseRegex = new Regex(SubDistrictPattern);
        Match SubDistrictMatch = SubDistrictCaseRegex.Match(AddressString);

        if (SubDistrictMatch.Value != string.Empty)
        {
            string BangkokPattern = "^แขวง";
            Regex BangkokCaseRegex = new Regex(BangkokPattern);
            Match BangkokMatch = BangkokCaseRegex.Match(SubDistrictMatch.Value);

            oldSubDistrict = (oldSubDistrict == string.Empty) ? SubDistrictMatch.Value : oldSubDistrict;

            result = (BangkokMatch.Value != string.Empty) ? SubDistrictMatch.Value.Replace("แขวง", string.Empty) : SubDistrictMatch.Value.Replace("ตำบล", string.Empty).Replace("ต.", string.Empty);
        }

        return result;
    }

    private DataRow ReadSubDistrictDatabase(string SubDistrictName, string DistrictCode)
    {
        DataRow Dr = null;
        DataTable Dt = new DataTable();
        Dt = address.GetSubDistrictByDistrict(DistrictCode);

        for (int i = 0; i < SubDistrictName.Length; i++)
        {
            string strSearch = string.Format("SubDistrictName LIKE '{0}%'", SubDistrictName.Substring(0, i));

            if (Dt.Select(strSearch).Length == 1)
            {
                Dr = Dt.Select(strSearch)[0]; ;
            }
        }

        return Dr;
    }

    private DataRow ReadSubDistrictDatabaseFromRaw(string AddressString, string DistrictCode)
    {
        DataTable Dt = new DataTable();
        Dt = address.GetSubDistrictByDistrict(DistrictCode);
        List<DataRow> rowArray = new List<DataRow>();
        List<int> matchArray = new List<int>();
        List<string> oldString = new List<string>();
        int match = 99;
        int index = 0;
        int count = 0;

        string[] stringArray = AddressString.Split(new char[] { ' ' });

        foreach (string aString in stringArray)
        {
            for (int i = 0; i < aString.Length; i++)
            {
                string strSearch = string.Format("SubDistrictName LIKE '{0}%'", aString.Substring(0, i));

                if (Dt.Select(strSearch).Length == 1)
                {
                    oldString.Add(aString);
                    rowArray.Add(Dt.Select(strSearch)[0]);
                    matchArray.Add(Math.Abs(Dt.Select(strSearch)[0]["SubDistrictName"].ToString().Length - aString.Length));
                }
            }
        }

        foreach (int m in matchArray)
        {
            if (m < match)
            {
                match = m;
                index = count;
            }

            count++;
        }

        oldSubDistrict = (oldSubDistrict == string.Empty) ? oldString[index] : oldSubDistrict;

        return (rowArray.Count > 0) ? rowArray[index] : null;
    }

    private string RemoveProvincePrefix(string StringName)
    {
        return StringName.Replace("จังหวัด", string.Empty).Replace("จ.", string.Empty);
    }

    private string RemoveDistrictPrefix(string StringName)
    {
        string BangkokPattern = "^เขต";
        Regex BangkokCaseRegex = new Regex(BangkokPattern);
        Match BangkokMatch = BangkokCaseRegex.Match(StringName);

        return (BangkokMatch.Value != string.Empty) ? StringName.Replace("เขต", string.Empty) : StringName.Replace("อำเภอ", string.Empty).Replace("อ.", string.Empty);
    }

    private string RemoveSubDistrictPrefix(string StringName)
    {
        string BangkokPattern = "^แขวง";
        Regex BangkokCaseRegex = new Regex(BangkokPattern);
        Match BangkokMatch = BangkokCaseRegex.Match(StringName);

        return (BangkokMatch.Value != string.Empty) ? StringName.Replace("แขวง", string.Empty) : StringName.Replace("ตำบล", string.Empty).Replace("ต.", string.Empty);
    }
}

Date : 2010-05-13 12:11:29 By : tungman
 


 

No. 5



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


เสร็จแล้วครับ คราวนี้เรามาลองใช้งานกัน โดยสร้าง page ขึ้นมา

ReadAddress.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReadAddress.aspx.cs" Inherits="ReadAddress" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Read Address</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="AddressTextBox" runat="server" Width="400" AutoCompleteType="None"></asp:TextBox>
        <asp:Button ID="ExtractButton" runat="server" Text="Extract" />
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

ReadAddress.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ReadAddress : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ExtractButton.Click += new EventHandler(ExtractButton_Click);
    }

    protected void ExtractButton_Click(object sender, EventArgs e)
    {
        AddressManager address = new AddressManager();
        GridView1.DataSource = address.Extract(AddressTextBox.Text.Trim());
        GridView1.DataBind();
    }
}


ลองรันและป้อนที่อยู่ดู (ครั้งแรกจะนานหน่อยนะ เพราะมันกำลังดูดข้อมูลเพื่อสร้างฐานข้อมูลอยู่)

1
Date : 2010-05-13 12:15:59 By : tungman
 


 

No. 6



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


ถ้าใครอยากเอาไปพัฒนาต่อก็ได้นะ ไม่ว่าเพราะผมยังอยากทำให้มันฉลาดกว่านี้เลย

อยากปรับ algorith นิดหน่อยให้มันใส่ค่า ตำแหน่ง ด้วย เช่น

อ่างทอง เกาะสมุย สุราธานี ==> เป็น อ่างทอง[0] เกาะสมุย[1] สุราธานี[2]

เพื่อให้มันพิจาราณาว่า อ่างทอง มีค่าตำแหน่งน้อยกว่า สุราธานี ควรจะเป็นอะไรที่ level ต่ำกว่า

สารารถลองป้อนที่อยู่หลายๆ แบบดูได้นะครับ เช่น ใส่ คำนำหน้า (ต. อ. จ. หรือ ตำบล อำเภอ จังหวัด เขต แขวง)

หรือไม่ใส่คำนำหน้า (วิธีนี้ลูปเยอะ และผิดพลาดสูงถ้ายังไม่แก้ algorith ให้มีค่าตำแหน่ง)

หรือแกล้งพิมพ์ชื่อผิดดูก็ได้ครับ


ไว้ว่างๆ และขยันๆ จะเอาตัว update มาลงใหม่นะ
Date : 2010-05-13 12:22:37 By : tungman
 


 

No. 7



โพสกระทู้ ( 1,603 )
บทความ ( 1 )



สถานะออฟไลน์


งั้นรบกวนขอตัว data ได้ปะคะ
มีทำไว้เหมือนกันแต่ใช้ข้อมุลของกระทรวงมหาดไทย มีที่ผิดเยอะและก็มีเขตปกครองแปลกๆติดมาน่ะค่ะ
เคยเจอปัญหา overload แบบเดียวกับที่พี่ตึ๋งศรีนี่แหละค่ะ แต่แก้ปัญหาด้วยการจับ address ทั้งหมด
ลงเป็นข้อมูลโครงสร้างแบบ tree (adjacency list model)
แล้ว load on demand แบบ ajax callback เอาค่ะ
web service มันแปลกๆไงไม่รุเลยงดใช้ชั่วคราวจนกว่าจะเข้าใจให้มากกว่านี้
แต่ตอน user เลือกเลยต้องใช้ treeview ใน combobox เอา ไม่ได้ key อะไรเลยค่ะ
ตอนใช้งาน เวลาที่ใช้ก็ในช่วงที่รับได้ เพราะมันจะ load เฉพาะส่วนที่ user selected เท่านั้น
.net จะเสียเปรียบ PHP ตรงนี้แหละเนอะคะ

อยากถามอีกนิดนึง ในระดับอำเภอจะมีระดับย่อยคือ อำเภอ กับ กิ่งอำเภอพี่ตึ๋งศรีแยกไว้ปะคะ
Date : 2010-05-13 13:47:14 By : blurEyes
 


 

No. 8



โพสกระทู้ ( 3,144 )
บทความ ( 1 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์


ก็อบโค้ดแล้วลองรันเลยครับ เดี๋ยว data มันจะมาเอง (เข้าไปดูได้ที่ database ของตัวเอง จะมี table เพิ่มมา 3 อัน)

รับรองว่ามีแบบที่ต้องการเลย ละเอียดกว่าที่ต้องการอีก ดูได้ที่ field DistrictPrefix แยกไว้เป็น เขต อำเภอ กิ่งอำเภอ

SubDistrictPrefix แยกเป็น แขวง เทศบาลตำบล เทศบาลเมือง เทศบาลนคร และตำบล

ให้รู้ว่าทั้งหมดคือ ตำบล แต่ปกครองต่างกันก็ถ้าไม่ใช่เทศบาล ก็เป็น อบต. ปกครอง

อ่านโค้ดของ class AddressData.cs ก็รู้ อีกอย่างชอบทำงานแล้วให้มันพ้นตัวก็เลย

ให้มัน create data ด้วยเลยในกรณีไม่มี data คนมาหลังๆ จะได้ไม่ต้องขอ

ปล. มันไม่ใช่ webservice เป็นการอ่าน html แล้วดึงส่วนที่ต้องการมาเก็บลง database โดยใช้ regular expression อ่านออกมา

ฉะนั้นสิ่งสำคัญคือต้อง add connection string ที่ web.config ด้วยชื่อ SqlConnectionString แบบในตัวอย่าง

แต่อย่าลืม set sql server ในส่วนของ user ที่ security ให้ check ที่ db_datareader กับ db_datawriter

ใน owner schemas กับ role member ด้วย ถ้าไม่ check จำไม่ได้ว่า error หรือเปล่าเพราะทำนานแล้ว
Date : 2010-05-13 13:54:46 By : tungman
 

   

ค้นหาข้อมูล


   
 

แสดงความคิดเห็น
Re : ให้ user กรอกที่อยู่แล้วให้โปรแกรมมันสามารถแยกว่าอันไหนเป็น จังหวัด อำเภอ ตำบล
 
 
รายละเอียด
 
ตัวหนา ตัวเอียง ตัวขีดเส้นใต้ ตัวมีขีดกลาง| ตัวเรืองแสง ตัวมีเงา ตัวอักษรวิ่ง| จัดย่อหน้าอิสระ จัดย่อหน้าชิดซ้าย จัดย่อหน้ากึ่งกลาง จัดย่อหน้าชิดขวา| เส้นขวาง| ขนาดตัวอักษร แบบตัวอักษร
ใส่แฟลช ใส่รูป ใส่ไฮเปอร์ลิ้งค์ ใส่อีเมล์ ใส่ลิ้งค์ FTP| ใส่แถวของตาราง ใส่คอลัมน์ตาราง| ตัวยก ตัวห้อย ตัวพิมพ์ดีด| ใส่โค้ด ใส่การอ้างถึงคำพูด| ใส่ลีสต์
smiley for :lol: smiley for :ken: smiley for :D smiley for :) smiley for ;) smiley for :eek: smiley for :geek: smiley for :roll: smiley for :erm: smiley for :cool: smiley for :blank: smiley for :idea: smiley for :ehh: smiley for :aargh: smiley for :evil:
Insert PHP Code
Insert ASP Code
Insert VB.NET Code Insert C#.NET Code Insert JavaScript Code Insert C#.NET Code
Insert Java Code
Insert Android Code
Insert Objective-C Code
Insert XML Code
Insert SQL Code
Insert Code
เพื่อความเรียบร้อยของข้อความ ควรจัดรูปแบบให้พอดีกับขนาดของหน้าจอ เพื่อง่ายต่อการอ่านและสบายตา และตรวจสอบภาษาไทยให้ถูกต้อง

อัพโหลดแทรกรูปภาพ

Notice

เพื่อความปลอดภัยของเว็บบอร์ด ไม่อนุญาติให้แทรก แท็ก [img]....[/img] โดยการอัพโหลดไฟล์รูปจากที่อื่น เช่นเว็บไซต์ ฟรีอัพโหลดต่าง ๆ
อัพโหลดแทรกรูปภาพ ให้ใช้บริการอัพโหลดไฟล์ของไทยครีเอท และตัดรูปภาพให้พอดีกับสกรีน เพื่อความโหลดเร็วและไฟล์ไม่ถูกลบทิ้ง

   
  เพื่อความปลอดภัยและการตรวจสอบ กระทู้ที่แทรกไฟล์อัพโหลดไฟล์จากที่อื่น อาจจะถูกลบทิ้ง
 
โดย
อีเมล์
บวกค่าให้ถูก
<= ตัวเลขฮินดูอารบิก เช่น 123 (หรือล็อกอินเข้าระบบสมาชิกเพื่อไม่ต้องกรอก)







Exchange: นำเข้าสินค้าจากจีน, Taobao, เฟอร์นิเจอร์, ของพรีเมี่ยม, ร่ม, ปากกา, power bank, แฟลชไดร์ฟ, กระบอกน้ำ

Load balance : Server 02
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่