//#define TESTTEST 폼디자인에 컬럼을 미리 추가했을때 사용.
//TODO::
//인코딩관련 RECV BYTE[] 처리 - OK
//접수일련번호 DB 쿼리후 부여
//결과 DB INSERT
//검색조건 DB 쿼리
//EXCEL 아웃풋
//FTP & 상세조회요청 DB INSERT


//checkbox 는 상세조회만
//조건 : 성명,주민번호,상태5가지
//그리드 소트
/*
http://aaa.com
12 System;
*/
/*
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
*/
using System.Windows.Forms;
using Office.Framework.Excel;
using System.Reflection;
using System.Collections;
using System.Net;

using System.Data.SqlClient;
using System.Net.Sockets; //socket programing을 위한 네임스페이스.
using System.IO;
using System.Threading;
using System.Diagnostics;
using PSSIDRefer.Properties;
using System.Data.OleDb;

using TCPClientService;
using FTPClientService;

namespace PSSIDRefer
{
    public partial class frmMainRefer : Form
    {
        public bool bViewMode = false;
        private const  string SHEETNAME = "통합";
        static Socket client;
        static StreamReader m_reader;
        static StreamWriter m_writer;
        static Thread thRequest;
        static Thread thSecuReq;
        public SqlConnection dbcon = null;
        public SqlConnection dbcon2 = null;
        private SqlCommand cmdIns = null;//for transaction rollback
        private SqlTransaction transIns = null;
        private string searchName;
        private string searchResNo;

        private bool bSearchAll = false;
        private bool bSearchName = false;//thread safe
        private bool bSearchResNo = false;//thread safe
        private bool bSearchCONT = false;//thread safe
        private bool bSearchCONT1 = false;//thread safe
        private bool bSearchCONT2 = false;
        private bool bSearchCONT3 = false;
        private bool bSearchCONT4 = false;
        private bool bSearchCONT5 = false;
        private string secuReqMemo = "";//보안조회 메모사항(전달메세지)
        public Boolean fLoaded = false;
        private popupReqDetailRefer m_ProgSecuRefDlg = null;
        private frmMainReqPop m_ProgMainRefDlg = null;
        public bool bAbort = false;
        public bool sockerr = false;
        public int masterIDX = -1;//검색위한 마스터키 - 로드버튼 누르면 reset됨
        private int detailIDX = -1;//검색위한 디테일키
        private int bSendingReq = 0;//신원조회요청 처리중인지 flag
        private int bSentReq = 0;//신원조회요청 건수( = 마스터건수)
        private TCPClient tcc;
        private int nappType = 0;
        private string myIP;
        private string appTitle;

        private int m_CheckCount = 0;
        private int m_TotalCount = 0;
        private bool m_bRefresh = true;
        private static Encoding enkor = Encoding.GetEncoding(949); //(DOS) Greek code page

        public delegate void myDele(int nReqNo,int nRowIndex,Byte [] recvstr,int len);
        public delegate void TestCompleteDelegate(string strMessage);
        public delegate void SearchDelegate(bool enable);
        public delegate void MainReqDelegate(int flag);
        public delegate void SecuReqDelegate(int flag);
        public delegate void CountDelegate(int flag);


        public string m_UserID = "";
        public string m_Password = "";
        public string m_AuthKind = "";
        public string m_DeptName = "";
        public string m_SSID = "";
        public string m_UserName = "";

        public frmMainRefer()
        {
            InitializeComponent();
        }

        public void DBConnect()
        {
            string connString = Settings.Default.PSSDBConnectionString;
            try
            {
                dbcon = new SqlConnection(connString);
                dbcon.Open();

                dbcon2 = new SqlConnection(connString);
                dbcon2.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error in connection : " + ex.Message);
            }
            
        }

        private void frmMainRefer_Load(object sender, EventArgs e)
        {
            

            //아래) 외부에서 공유기통해서 들올때 포워딩한 포트번호를 dns 이후에 부여.
            //공유기 포트포워딩에 sql server port 1433이 등록되지않아 외부접속불가하여 등록함
            //string connString = "server=2bcomnet.goanygate.com,1433;database=PSSDB;Uid=sa;Pwd=bankon";

            m_UserID = ((frmMDIMain)this.ParentForm).m_UserID;
            m_AuthKind = ((frmMDIMain)this.ParentForm).m_AuthKind;
            m_DeptName = ((frmMDIMain)this.ParentForm).m_DeptName;
            m_SSID = ((frmMDIMain)this.ParentForm).m_SSID;
            m_UserName = ((frmMDIMain)this.ParentForm).m_UserName;

            DBConnect();

            //string name = Dns.GetHostName();

            tbIP.Text = Settings.Default.TerminalIP;

            DateTime dt = System.DateTime.Now;
            tbDate.Text = dt.ToShortDateString();
            tbUser.Text = m_UserID + "(" + m_UserName + ")";
            tbSubject.Text = "정보통신 신원조회 "  + dt.ToShortDateString();
            tbSearchName.Text = "";


            cbType.SelectedIndex = 0;
            cbCONT1.SelectedIndex = 0;
            cbCONT2.SelectedIndex = 0;
            cbCONT3.SelectedIndex = 0;
            cbCONT4.SelectedIndex = 0;

            cbCONT1.Enabled = false;
            cbCONT2.Enabled = false;
            cbCONT3.Enabled = false;
            cbCONT4.Enabled = false;

            tbFileName.Text = "";

            if (bViewMode)
            {
                SetViewMode(sender, e);
            }
            fLoaded = true;

            m_CheckCount = 0;
            m_TotalCount = 0;
            lbSecuCount.Text = getSECUCount();
            dgvIDRefer.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;

            dgvIDRefer.Columns[12].DisplayIndex = 10;
            cbSIDColCnt.SelectedIndex = 0;
        }

        public void SetViewMode(object sender, EventArgs e)
        {
            this.Text = "신원조회 내용 보기";
            groupBox1.Enabled = false;
            groupBox2.Enabled = false;
            if (dbcon == null)
                DBConnect();
            lbSecuCount.Text = getSECUCount();
            btnSearch_Click(this,null);
            
        }

        public bool IsViewMode()
        {
            return bViewMode;
        }

        private void frmMainRefer_FormClosed(object sender, FormClosedEventArgs e)
        {
            if(dbcon != null)
                dbcon.Close();
            dbcon = null;
            if (dbcon2 != null)
                dbcon2.Close();
            dbcon2 = null;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                tbFileName.Text = openFileDialog.FileName;
            }

        }

        private void test()
        {
            string excelfile = "";
            string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
                                       "Data Source=" + excelfile + ";" +
                                       "Extended Properties=Excel 8.0;";


            OleDbConnection objConn = new OleDbConnection();
            OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]",objConn);
            OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
            objAdapter1.SelectCommand = objCmdSelect;
           // DataSet objDataset1 = new DataSet();
            DataTable objDataTable = new DataTable();

            objAdapter1.Fill(objDataTable);

            objCmdSelect.Dispose();
            objDataTable.Dispose();
            objConn.Close();

            if(objConn != null)
                objConn.Close();
            objConn = null;


        }

        private void btnLoad_Click(object sender, EventArgs e)//신규요청건 로드
        {
            ExcelAdapter ea = null;
            if (tbFileName.Text.Trim() == "")
            {
                MessageBox.Show("Invalid Excel Data Source.");
                return;
            }

            try
            {
                dgvIDRefer.AllowUserToAddRows = false;

                //새 요청건을 로드하였으므로 누적요청건수(bSentReq)를 clear하여 요청버튼기능을 활성화하고 검색버튼을 새로운 요청건으로 하기위해
                //마스터,디테일 키값을 리셋한다.
                //
                bSentReq = 0;//신원조회요청건수:문서를 다시 로드하면 신원조회요청을 enable 하기위해 리셋한다.
                masterIDX = -1;//검색
                detailIDX = -1;
#if FALSE
                ea = new ExcelAdapter();
                ea.FirstRowHeader = true;
                ea.Load(tbFileName.Text);

                DataSet ds = ea.DataSource;
                DataTable ExcelDT = ds.Tables[0];

#else
            string excelfile = tbFileName.Text;
            string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
                                       "Data Source=" + excelfile + ";" +
                                       "Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";


            OleDbConnection objConn = null;
            OleDbCommand objCmdSelect = null;
            OleDbDataAdapter objAdapter1 = null;
            DataTable objDataTable = null;
            DataTable objDataTableSheet = null;
            string sheetname = SHEETNAME;
            bool bFound = false;
            try{
                objConn = new OleDbConnection(sConnectionString);

                objConn.Open();
                objDataTableSheet = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                String[] excelSheets = null;
                if (objDataTableSheet != null && objDataTableSheet.Rows.Count > 0)
                {
                    excelSheets = new String[objDataTableSheet.Rows.Count];
                    string tempname = "";
                    int j = 0;
                    //for(j = 0; j < objDataTableSheet.Rows.Count;j++)
                    foreach (DataRow row in objDataTableSheet.Rows)
                    {
                        tempname = row["TABLE_NAME"].ToString();
                        tempname = tempname.Replace("$", "");
                        if(tempname == SHEETNAME){
                            bFound = true;
                            break;
                        }
                        j++;
                    }
                    //sheetname = objDataTableSheet.Rows[0]["TABLE_NAME"].ToString();
                }
                objDataTableSheet.Dispose();

                if(bFound == false){

                    MessageBox.Show("요청자료에 '" + SHEETNAME + "' 시트이름이 없습니다.엑셀파일을 열어 확인후 재시도 하세요.",
                        "요청자료 확인",MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    
                    if (objConn != null)
                        objConn.Close();
                    objConn = null;
                    return;
                }

                string strquery = "SELECT * FROM [" + sheetname + "$]";
                objCmdSelect = new OleDbCommand(strquery, objConn);
                objAdapter1 = new OleDbDataAdapter();
                objAdapter1.SelectCommand = objCmdSelect;
                // DataSet objDataset1 = new DataSet();
                objDataTable = new DataTable();

                objAdapter1.Fill(objDataTable);

                objCmdSelect.Dispose();
                objDataTable.Dispose();
                if (objConn != null)
                    objConn.Close();
                objConn = null;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("error: " + ex.Message);
            }

            DataTable ExcelDT = objDataTable;

    
#endif

                DataTable mainDT = new DataTable();

#if !TESTTEST

                mainDT.Columns.Add("선택", System.Type.GetType("System.Boolean"));//체크박스
                
                mainDT.Columns.Add("접수 일련번호", typeof(string));
                mainDT.Columns.Add("신청자 성명", typeof(string));
                mainDT.Columns.Add("신청자 주민번호", typeof(string));
                //mainDT.Columns.Add("접수구분", typeof(string));
                //mainDT.Columns.Add("접수년도", typeof(string));
                mainDT.Columns.Add("신원 적합여부", typeof(string));

                mainDT.Columns.Add("주민", typeof(string));
                mainDT.Columns.Add("범죄경력", typeof(string));
                mainDT.Columns.Add("수배", typeof(string));
                mainDT.Columns.Add("공안", typeof(string));
                mainDT.Columns.Add("보안", typeof(string));

                mainDT.Columns.Add("신원작업상태", typeof(string));
                mainDT.Columns.Add("에러 메시지", typeof(string));
                mainDT.Columns.Add("경호처자료", typeof(string));

                mainDT.Columns.Add("호스트 통신상태", typeof(string));

                //DataGridViewColumn col;
                //col.ValueType = System.Type.GetType("System.Boolean");
                //dgvIDRefer.Columns.Add("선택", "선택");
                //dgvIDRefer.Columns.Add("선택", "일련번호");
                //dgvIDRefer.Columns.Add("선택", "성명");
                //dgvIDRefer.Columns.Add("선택", "주민번호");
                //dgvIDRefer.Columns.Add("선택", "적합여부");
                //dgvIDRefer.Columns.Add("선택", "주민");
                //dgvIDRefer.Columns.Add("선택", "범죄경력");
                //dgvIDRefer.Columns.Add("선택", "수배");
                //dgvIDRefer.Columns.Add("선택", "공안");
                //dgvIDRefer.Columns.Add("선택", "보안");
                //dgvIDRefer.Columns.Add("선택", "보안");


#endif
                DataRowCollection dsRows = ExcelDT.Rows;

                IEnumerator ExcelRowEnum = dsRows.GetEnumerator();

                DateTime date = DateTime.Now;

                DataRow eachRow;

                int nRow = 0;
                while (ExcelRowEnum.MoveNext())
                {
                    int nCol = 0;
                    eachRow = (DataRow)ExcelRowEnum.Current;
                    object[] str11 = eachRow.ItemArray;
                    if (eachRow.IsNull(0))
                        break;
                    
#if TESTTEST
                    DataGridViewRowCollection dsRows2 = dgvIDRefer.Rows;
                    DataGridViewRow row = new DataGridViewRow();
                    DataGridViewTextBoxCell col = new DataGridViewTextBoxCell();

                    for (int ii = 0; ii < nCol; ii++)
                    {

                        col.Value = "11111111";// newRow[ii];
                        row.Cells.Add(col);
                    }
                    dsRows2.Add(row);
#else

                    if(nRow == 0)
                        emptyGrid();

                    string appname = "";
                    string resno = "";

                    if (!eachRow.IsNull(0))
                        appname = (string)str11[0];

                    if (!eachRow.IsNull(1))
                    {
                        if (cbSIDColCnt.SelectedIndex == 0) // 주민번호가 두번째 컬럼에 13자리 존재시
                            resno = (string)str11[1];
                        else     // 주민번호가 두번째 컬럼과 세번째 컬럼에 각각 6자리, 7자리 존재 시
                        {
                            resno = (string)str11[1];
                            if(str11[2] != null)
                                resno += (string)str11[2];
                        }

                    }

                    DataGridViewRowCollection dsRows2 = dgvIDRefer.Rows;
                    dsRows2.Add(1);

                    int i = nRow;


                    string strOnlyInteger = "";
                    try
                    {
                        int result;
                        for (int j = 0; j < resno.Length; j++)
                        {
                            if (int.TryParse(resno[j].ToString(), out result))
                            {
                                strOnlyInteger += resno[j];
                            }
                        }
                    }
                    catch
                    {

                    }




                    if (appname.Length > 0)
                        appname = appname.Replace(" ", "");

                    dgvIDRefer[0, i].Value = false;//선택
                    dgvIDRefer[1, i].Value = "";  // 접수일련번호
                    dgvIDRefer[2, i].Value = appname;
                    dgvIDRefer[3, i].Value = strOnlyInteger;  // 신청자주민번호
                    dgvIDRefer[4, i].Value = "";  // 신원적합여부
                    dgvIDRefer[5, i].Value = ""; // 주민
                    dgvIDRefer[6, i].Value = "";  // 범죄경력
                    dgvIDRefer[7, i].Value = ""; // 수배
                    dgvIDRefer[8, i].Value = "";  // 공안
                    dgvIDRefer[9, i].Value = ""; // 보안
                    dgvIDRefer[10, i].Value = "";  // 신원작업상태
                    dgvIDRefer[11, i].Value = "";  // 에러메세지
                    dgvIDRefer[12, i].Value = ""; // 경호처자료
                    dgvIDRefer[13, i].Value = "처리전";
                    dgvIDRefer[7, i].Style.ForeColor = Color.Black;

                    nRow++;
#if FALSE
                    DataRow newRow = mainDT.NewRow();

                    //폼에 하나만 표현
                    /*
                     * "SHOC";                     // 업무코드
                     * date.ToString("yyyyMMdd");  // 접수일자 (시스템날짜)
                     * date.ToString("HH/MM/ss");    // 접수일자 (접수시간)
                     * Get_MyIP();                 // 접수단말기
                     * 
                     */
                    
                    //newRow[0] = "1234567890123";            // 접수자 주민번호
                    newRow[nCol++] = true;                     // 선택여부
                    newRow[nCol++] = 000001;                     // 접수번호 일련번호
                    newRow[nCol++] = (string)str11[0];           // 신청자 성명
                    newRow[nCol++] = (string)str11[1];            // 신청자 주민번호

//                    newRow[3] = "1";                        // 접수번호 구분 : 개방 1, 행사 2 
//                    newRow[4] = date.ToString("yyyy");      // 접수번호 접수년도
                    newRow[nCol++] = "";//신원적합여부
                    newRow[nCol++] = "";//주민
                    newRow[nCol++] = "";//범죄경력
                    newRow[nCol++] = "";//수배
                    newRow[nCol++] = "";//공안
                    newRow[nCol++] = "";//보안
                    newRow[nCol++] = "";//신원작업상태
                    newRow[nCol++] = "에러메세지";//에러 메시지
                    newRow[nCol++] = "경호처자료";//경호처자료
                    newRow[nCol++] = "처리전";//호스트 appc 상태

                    mainDT.Rows.Add(newRow);
                    nRow++;
#endif
#endif
                }
                m_TotalCount = nRow;
                m_CheckCount = 0;
                lbTotal.Text = m_TotalCount.ToString();
                lbSecu.Text = m_CheckCount.ToString();
                lbTotal.Invalidate();
                lbSecu.Invalidate();

                /*///////////////////////////////////////////////////////////////
                DataRowCollection dsRows = ds.Tables[0].Rows;
                
                IEnumerator RowEnum =  dsRows.GetEnumerator();
                string[] str = new string[11];
                
                DataRow eachRow;

                while(RowEnum.MoveNext())
                {
                    eachRow = (DataRow) RowEnum.Current;
                    object[] str11 = eachRow.ItemArray;
                    int j=0;
                    for (j = 0; j < str11.Length; j++)
                    {
                        string strCol = (string)str11[j];
                        
                    }
                }
                ///////////////////////////////////////////////////////////////
                 */
#if !TESTTEST
                //dgvIDRefer.DataSource = mainDT;
#endif
                //exportToExcel(ds, "c:\\1.xls");

                /*dgvCustomer.DataSource = ds.Tables["Customers"];
                dgvOrder.DataSource = ds.Tables["Orders"];
                dgvOrderDetail.DataSource = ds.Tables["OrderDetails"];
                dgvShipper.DataSource = ds.Tables["Shippers"];
                dgvProduct.DataSource = ds.Tables["Products"]; 
                 */
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (ea != null)
                    ea.Dispose();
            }
        }

        private void CallSecuReq(int flag)
        {
            if (!this.InvokeRequired)
            {
                m_ProgSecuRefDlg.Close();
                m_ProgSecuRefDlg.Dispose();
                m_ProgSecuRefDlg = null;
                lbSecuCount.Text = getSECUCount();//보안조회 누적 카운트 표시

                MessageBox.Show("보안조회요청이 완료되었습니다.", "보안조회 요청완료",
                                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                SecuReqDelegate del = new SecuReqDelegate(CallSecuReq);
                this.BeginInvoke(del, flag);
            }
        }

        private void CallRefreshCount(int flag)
        {
            if (!this.InvokeRequired || flag == 1)
            {
                lbTotal.Text = m_TotalCount.ToString();
                lbSecu.Text = m_CheckCount.ToString();
                lbTotal.Invalidate();
                lbSecu.Invalidate();
            }
            else
            {
                CountDelegate del = new CountDelegate(CallRefreshCount);
                this.BeginInvoke(del, flag);
            }
        }

        private void CallMainReq(int flag)
        {
            if (!this.InvokeRequired)
            {
                m_ProgMainRefDlg.Close();
                m_ProgMainRefDlg.Dispose();
                m_ProgMainRefDlg = null;

                if(sockerr)
                    MessageBox.Show("정보통신 신원조회중 네트워크 연결이 끊겼습니다.네트워크 상태를 확인후 재시도 하세요.", "정보통신 신원조회 실패", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                else if(bAbort)
                    MessageBox.Show("정보통신 신원조회가 취소되었습니다.", "정보통신 신원조회 취소",MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                else
                    MessageBox.Show("정보통신 신원조회가 완료되었습니다.", "정보통신 신원조회 완료", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

            }
            else
            {
                MainReqDelegate del = new MainReqDelegate(CallMainReq);
                this.BeginInvoke(del, flag);
            }
        }

        private void btnDetailRefer_Click(object sender, EventArgs e)
        {
            if (masterIDX == -1)//신원조회요청이 수행되었을때 값이 들어온다.문서를 새로 로드하면 요청을 다시해야하기 때문에 reset되어 여기에서 걸린다.
            {
                MessageBox.Show("신원조회요청이 이전에 수행되지 않았습니다.먼저 신원조회요청을 완료한 후 검색하세요", "검색불가",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                return;
            }
#if FLASE
            frmSecuRefPop dlg = new frmSecuRefPop();

            dlg.m_Date = tbDate.Text;
            dlg.m_IP = tbIP.Text;
            dlg.m_Title = tbSubject.Text;
            dlg.m_Type = cbType.SelectedIndex;
            dlg.m_User = tbUser.Text;

            dlg.ShowDialog();

            this.Enabled = false;
            username = tbUser.Text;

            DateTime date = System.DateTime.Now;

            string secuno = getSECUSeqNo();//unique idx
            string year = date.ToString("yyyy");
            string month = date.ToString("MM");

            string filename = date.ToString("yyyyMMdd") + "_" + secuno + ".xls";

            string filepath = Application.StartupPath + "\\" + filename;
            DataTable dt = MakeDataTable();

            Tools.ExportToExcel.ExportToExcel exp = new Tools.ExportToExcel.ExportToExcel();
            exp.dataTable2Excel(dt, null, filepath, "Sheet1");

            string FtpServer = Settings.Default.FtpServerIP;
            string FtpUserName = Settings.Default.FTPUser;
            string FtpPassword = Settings.Default.FtpPassword;
            int FtpPort = Settings.Default.FtpServerPort;

            try
            {
                FtpClient ftp = new FtpClient(FtpServer, FtpUserName, FtpPassword, 20, FtpPort);
                ftp.Login();
                try
                {
                    ftp.MakeDir(year);
                    ftp.ChangeDir(year);
                    ftp.MakeDir(month);
                    ftp.ChangeDir(month);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("ftp.MakeDir: error, file already exists" + ex.Message);
                }

                ftp.BinaryMode = true;
                ftp.Upload(filename);
                ftp.Close();

                InsertSECUMaster(filename);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("btnDetailRefer_Click: error " + ex.Message);
            }

            this.Enabled = true;
            dlg.Close();

#else
            frmSecuRefPop dlg = new frmSecuRefPop();

            dlg.m_Date = tbDate.Text;
            dlg.m_IP = tbIP.Text;
            dlg.m_Title = tbSubject.Text;
            dlg.m_Type = cbType.SelectedIndex;
            dlg.m_User = tbUser.Text;

            secuReqMemo = "";
            if(dlg.ShowDialog() != DialogResult.OK)
                return;

            secuReqMemo = dlg.m_Memo;

            if (thSecuReq != null && thSecuReq.IsAlive)
            {
                thSecuReq.Abort();
                thSecuReq.Join(3000);
                thSecuReq = null;
            }

            ThreadStart ts = new ThreadStart(SecuRefProc);
            thSecuReq = new Thread(ts);
            thSecuReq.Start();

            m_ProgSecuRefDlg = new popupReqDetailRefer();
            m_ProgSecuRefDlg.ShowDialog();
#endif
        }
        private string convstring(string unicodeString)
        {
            // Create two different encodings.
            Encoding ascii = Encoding.ASCII;
            Encoding unicode = Encoding.Unicode;
            Encoding enkor = Encoding.GetEncoding(949); //(DOS) Greek code page

            Byte[] encodedBytes = enkor.GetBytes(unicodeString);
            String decodedString = enkor.GetString(encodedBytes);


            return decodedString;
#if FALSE
            // Convert the string into a byte[].
            byte[] unicodeBytes = unicode.GetBytes(unicodeString);

            // Perform the conversion from one encoding to the other.
            byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

            // Convert the new byte[] into a char[] and then into a string.
            // This is a slightly different approach to converting to illustrate
            // the use of GetCharCount/GetChars.
            char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
            ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
            string asciiString = new string(asciiChars);


            // Display the strings created before and after the conversion.
            //Console.WriteLine("Original string: {0}", unicodeString);
            //Console.WriteLine("Ascii converted string: {0}", asciiString);
            return asciiString;
#endif
        }

        private int IsRowChecked(int nRowIndex)
        {
            DataGridViewRowCollection dsRows = dgvIDRefer.Rows;
            int nRows = dsRows.GetRowCount(DataGridViewElementStates.Visible);//AddRow 모드 enable 이면 마지막은 빈줄
            int bCheck = 0;
            if (nRowIndex >= nRows)
                return -1;

            if (dgvIDRefer[2, nRowIndex].Value != null)
                bCheck = Convert.ToInt16(dgvIDRefer[0, nRowIndex].Value);
            return bCheck;
        }

        private int sendPacket(int nRowIndex)
        {
            DataGridViewRowCollection dsRows = dgvIDRefer.Rows;

            int nRows = dsRows.GetRowCount(DataGridViewElementStates.Visible);//AddRow 모드 enable 이면 마지막은 빈줄
            //int nrows = dsRows.Count;
            
            if (nRowIndex >= nRows)
                return -1;

            string sendcmd = "";
            string appname = "";
            string appresno ="";
            try
            {
                if(dgvIDRefer[2, nRowIndex].Value != null)
                    appname = dgvIDRefer[2, nRowIndex].Value.ToString();
                if (dgvIDRefer[3, nRowIndex].Value != null)
                    appresno = dgvIDRefer[3, nRowIndex].Value.ToString();

            }
            catch (Exception ex)
            {
                Debug.WriteLine("sendPacket error: " + ex.Message);
            }

            if (appname.Trim().Length < 1)
                return -1;

            Byte[] data = new Byte[140];

            for (int i = 0; i < data.Length; i++)
                data[i] = 0x20;

            string tempstr;

            DateTime date = DateTime.Now;
                        
            //data[0] = (Byte)'S';
            //data[1] = (Byte)'H';
            //data[2] = (Byte)'O';
            //data[3] = (Byte)'C';

            //Format을 쓰면 안됨.encoding이 제대로 안된다.
            string appyear = date.ToString("yyyy");//접수년도
            string appdate = date.ToString("yyyyMMdd");//접수일자
            string apptime = date.ToString("HH/MM/ss");//접수시간

            string appseqno = getAppSeqNo();  //접수일련번호
            string appattch = dgvIDRefer[12, nRowIndex].Value.ToString();

            string myip = myIP;
            string resno = m_SSID;//"9912051122345";//접수자주민번호 -from 폼,엑셀
            string apptype = (nappType == 0) ? "1" : "2";//접수번호 개방,행사

            Encoding.ASCII.GetBytes("SHOC", 0,4, data,0);
            Encoding.ASCII.GetBytes(appdate, 0, appdate.Length, data, 4);
            Encoding.ASCII.GetBytes(apptime, 0, apptime.Length ,data, 12);
            Encoding.ASCII.GetBytes(myip, 0, myip.Length, data, 20);
            Encoding.ASCII.GetBytes(resno, 0, resno.Length, data, 35);
            enkor.GetBytes(appname, 0, appname.Length, data, 48);
            Encoding.ASCII.GetBytes(appresno, 0, appresno.Length, data, 64);
            Encoding.ASCII.GetBytes(apptype, 0, apptype.Length, data, 77);
            Encoding.ASCII.GetBytes(appyear, 0, appyear.Length, data, 78);
            Encoding.ASCII.GetBytes(appseqno, 0, appseqno.Length, data, 82);
            enkor.GetBytes(appattch, 0, appattch.Length, data, 88);

            tcc.sendPacket(data,data.Length);
            return 0;
        }

        private void CreateTransctionInsert()
        {
            try
            {
                if (cmdIns == null)
                    cmdIns = new SqlCommand();
                if (transIns == null)
                    //transIns = new SqlTransaction();
                    transIns = dbcon.BeginTransaction("MyInsertTransaction");

                cmdIns.Connection = dbcon;
                cmdIns.Transaction = transIns;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("CreateTransctionInsert error:" + ex.Message);

            }
        }

        private void DestroyTransctionInsert()
        {
            try
            {
                if (cmdIns != null)
                {
                    cmdIns.Dispose();
                    cmdIns = null;
                }
                if (transIns != null)
                {
                    transIns.Dispose();
                    transIns = null;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("DestroyTransctionInsert error:" + ex.Message);
            }

        }

        private void CommitTransctionInsert()
        {
            try
            {
                if (transIns != null)
                    transIns.Commit();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("CommitTransctionInsert error:" + ex.Message);
            }
        }

        private void CancelTransctionInsert()
        {
            try
            {
                if (transIns != null)
                    transIns.Rollback();

            }
            catch (Exception ex)
            {
                Debug.WriteLine("CancelTransctionInsert error:" + ex.Message);
            }
        }

        private int InsertMaster()
        {
            DateTime date = DateTime.Now;
            int masteridx = -1;

            string sqlIns = "INSERT INTO PSS_MASTER(REF_DATE,REF_ACCOUNT,REF_TITLE,REF_TYPE) VALUES(@date,@account,@title,@type);SELECT SCOPE_IDENTITY()";
            try
            {
                string apptype = (nappType == 0) ? "1" : "2";//접수번호 개방,행사
                cmdIns.CommandText = sqlIns;
                cmdIns.Parameters.Clear();
                cmdIns.Parameters.Add("@date", date);
                cmdIns.Parameters.Add("@account", m_UserID);
                cmdIns.Parameters.Add("@title", appTitle.Trim());
                cmdIns.Parameters.Add("@type", apptype.Trim());

                //cmdIns.ExecuteNonQuery();
                //cmdIns.Parameters.Clear();
                //cmdIns.CommandText = "SELECT SCOPE_IDENTITY()";

                object count = (object)cmdIns.ExecuteScalar();
                masteridx = Convert.ToInt32(count);// Get the last inserted id.   
            }
            catch (Exception ex)
            {
                Debug.WriteLine("InsertMaster error:" + ex.Message);
            }
            masterIDX = masteridx;
            return masteridx;
        }

        private int InsertDetail(Byte[] recvstr)
        {
            int detailidx = -1;
            DateTime date = DateTime.Now;
            SqlCommand cmd = new SqlCommand();
            try
            {

                string appdate = Encoding.ASCII.GetString(recvstr, 4, 8);//접수일자
                string apptime = Encoding.ASCII.GetString(recvstr, 12, 8);//접수시간
                string appip = Encoding.ASCII.GetString(recvstr, 20, 15);//접수IP
                string resno = Encoding.ASCII.GetString(recvstr, 35, 13);//접수자 주민번호
                string appname = enkor.GetString(recvstr, 48, 16);//신청자성명
                string appresno = Encoding.ASCII.GetString(recvstr, 64, 13);//신청자주번
                string apptype = Encoding.ASCII.GetString(recvstr, 77, 1);//접수구분
                string appyear = Encoding.ASCII.GetString(recvstr, 78, 4);//접수년도
                string appseqno = Encoding.ASCII.GetString(recvstr, 82, 6);//접수일련번호
                string proper = Encoding.ASCII.GetString(recvstr, 88, 1);//신원적합여부
                string detail_res = Encoding.ASCII.GetString(recvstr, 89, 1);//주민
                string detail_cri = Encoding.ASCII.GetString(recvstr, 90, 1);//범죄경력
                string detail_wan = Encoding.ASCII.GetString(recvstr, 91, 1);//수배
                string detail_pol = Encoding.ASCII.GetString(recvstr, 92, 1);//공안
                string detail_sec = Encoding.ASCII.GetString(recvstr, 93, 1);//보안
                string err_stat = Encoding.ASCII.GetString(recvstr, 94, 1);//신원작업상태(에러) 체크
                string err_msg = enkor.GetString(recvstr, 95, 30);//비정상 처리시 내용 통보
                string appattch = enkor.GetString(recvstr, 125, 52);//경호처자료

                string sqlIns = "INSERT INTO PSS_REF_DETAIL(MASTER_ID,COMPLETE_DATE,JOB_CODE,RECEPT_DATE,RECEPT_TIME,RECEPT_TERMINAL,RECEPT_USERSOID,"
                + "REF_NAME,REF_SOID,REQ_KIND,REQ_YEAR,REQ_ID,REF_CHK,REF_CONTENT1,REF_CONTENT2,REF_CONTENT3,REF_CONTENT4,REF_CONTENT5,"
                + "REQ_STATE,ERR_MSG,REQ_ETC) VALUES(@p1,@p2,@p3,@p4,@p5,@p6,@p7,@p8,@p9,@p10,@p11,@p12,@p13,@p14,@p15,@p16,@p17,@p18,@p19,@p20,@p21);";
                //+ "SELECT SCOPE_IDENTITY()";


                //Debug.WriteLine("InsertDetail: masterIDX = " + masterIDX + "," + ex.Message);
                
                cmdIns.Connection = dbcon;
                cmdIns.Transaction = transIns;
                cmdIns.CommandText = sqlIns;
                cmdIns.Parameters.Clear();
                cmdIns.Parameters.Add("@p1", masterIDX);
                cmdIns.Parameters.Add("@P2", date);
                cmdIns.Parameters.Add("@p3", "SHOC");//업무코드
                cmdIns.Parameters.Add("@p4", appdate);//접수일자
                cmdIns.Parameters.Add("@p5", apptime);//접수시간
                cmdIns.Parameters.Add("@p6", appip);//
                cmdIns.Parameters.Add("@p7", resno);//
                cmdIns.Parameters.Add("@p8", appname);//
                cmdIns.Parameters.Add("@p9", appresno);//
                cmdIns.Parameters.Add("@p10", apptype);//
                cmdIns.Parameters.Add("@p11", appyear);//
                cmdIns.Parameters.Add("@p12", appseqno);//
                cmdIns.Parameters.Add("@p13", proper);//
                cmdIns.Parameters.Add("@p14", detail_res);//
                cmdIns.Parameters.Add("@p15", detail_cri);//
                cmdIns.Parameters.Add("@p16", detail_wan);//
                cmdIns.Parameters.Add("@p17", detail_pol);//
                cmdIns.Parameters.Add("@p18", detail_sec);//
                cmdIns.Parameters.Add("@p19", err_stat);//
                cmdIns.Parameters.Add("@p20", err_msg);//
                cmdIns.Parameters.Add("@p21", appattch);//

                cmdIns.ExecuteScalar();
                //detailidx = Convert.ToInt32(count);// Get the last inserted id.   
            }
            catch (Exception ex)
            {
                Debug.WriteLine("InsertDetail error: masterIDX = " + masterIDX + "," + ex.Message);
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                    cmd = null;
                }
            }
            detailIDX = detailidx;
            return detailidx;
        }

        private string getAppSeqNo()//접수일련번호 6자리를 생성
        {
            //string seqno = "";
            //string strSql = "SELECT ISNULL(MAX(IDX)+1,1)FROM PSS_REF_DETAIL";
            //SqlCommand cmd = new SqlCommand(strSql, dbcon);
            ////cmd.Parameters.Add("@p1", OleDbType.VarChar).Value = strUserID;

            //SqlDataAdapter da = new SqlDataAdapter(cmd);
            //DataTable dt = new DataTable();

            //try
            //{
            //    da.Fill(dt);
            //}
            //catch (Exception ex)
            //{
            //    Debug.WriteLine("getAppSeqNo error:" + ex.Message);
            //}
            //finally
            //{
            //    dt.Dispose();
            //    cmd.Dispose();
            //}
            //if (dt.Rows.Count > 0)
            //{
            //    seqno = dt.Rows[0][0].ToString();
            //    int n = Convert.ToInt32(seqno);
            //    seqno = String.Format("{0,5:000000}", n);
            //}
            //return seqno;
            int detailidx = 1;
            string seqno = "";//년도가 바뀌면 자동리셋
            string sqlQuery =   " SELECT " +
                                "   CASE " +
                                "   WHEN DATEDIFF(year,HOST_DATE ,GETDATE()) >= 0 THEN HOSTINDEX + 1 " +
                                "   ELSE 1 " +
                                "   END" +
                                "   AS DIFFRES" +
                                " FROM PSS_HOSTINDEX";

            SqlCommand cmd = new SqlCommand();

            try
            {
                cmd.Connection = dbcon2;
                cmd.CommandText = sqlQuery;
                cmd.Parameters.Clear();
                object count = (object)cmd.ExecuteScalar();
                if (count == null)
                {
                    sqlQuery = "INSERT INTO PSS_HOSTINDEX(HOSTINDEX) VALUES(0);";
                    cmd.CommandText = sqlQuery;
                    cmd.Parameters.Clear();
                    count = (object)cmd.ExecuteScalar();
                    detailidx = 1;
                }
                else 
                    detailidx = Convert.ToInt32(count);// Get the last inserted id.

                sqlQuery = "UPDATE PSS_HOSTINDEX SET HOSTINDEX = " +  detailidx + ";";
                cmd.CommandText = sqlQuery;
                cmd.Parameters.Clear();
                count = (object)cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("getAppSeqNo error:" + ex.Message);
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                    cmd = null;
                }
            }
            seqno = String.Format("{0,5:000000}", detailidx);
            Debug.WriteLine("getAppSeqNo : seqno = " + seqno);
            return seqno;
        }

        private int InsertSECUMaster(string filename,string memo)//상세조회요청/확인 마스터(파일마스터)에 요청등록
        {
            int secuidx = -1;
            DateTime date = DateTime.Now;

            string sqlIns = "INSERT INTO PSS_POL_SECU(MASTER_ID,REQ_DATE,REQ_USERNAME,REQ_FILEPATH,REQ_MEMO) VALUES(@p1,@p2,@p3,@P4,@P5);SELECT SCOPE_IDENTITY()";
            SqlCommand cmd = new SqlCommand();
            try
            {
                cmd.CommandText = sqlIns;
                cmd.Connection = dbcon;
                cmd.Transaction = transIns;

                cmd.Parameters.Clear();
                cmd.Parameters.Add("@p1", masterIDX);
                cmd.Parameters.Add("@p2", date);
                cmd.Parameters.Add("@p3", m_UserID);
                cmd.Parameters.Add("@p4", filename);
                cmd.Parameters.Add("@p5", memo);

                //cmdIns.ExecuteNonQuery();
                object count = (object)cmd.ExecuteScalar();
                secuidx = Convert.ToInt32(count);// Get the last inserted id.   
            }
            catch (Exception ex)
            {
                Debug.WriteLine("InsertSECUMaster error:" + ex.Message);
            }
            finally
            {
                cmd.Dispose();
                ((frmMDIMain)this.ParentForm).WriteSysLog(201, "[" + this.Text + "] " + "보안 신원조회 요청");
            }
       
            return secuidx;
        }

        private int displayPacket(int nRowIndex,Byte[] recvstr,int len)
        {
            DataGridViewRowCollection dsRows = dgvIDRefer.Rows;

            try
            {

                int nRows = dsRows.GetRowCount(DataGridViewElementStates.Visible);

                if (nRowIndex >= nRows || nRowIndex < 0 || len != 177)
                    return -1;

                string STX_SHOC = Encoding.ASCII.GetString(recvstr, 0, 4);

                if (STX_SHOC.CompareTo("SHOC") != 0)
                    return -1;

                string appdate = Encoding.ASCII.GetString(recvstr, 4, 8);//접수일자
                string apptime = Encoding.ASCII.GetString(recvstr, 12, 8);//접수시간
                string appip = Encoding.ASCII.GetString(recvstr, 20, 15);//접수IP
                string resno = Encoding.ASCII.GetString(recvstr, 35, 13);//접수자 주민번호
                string appname = enkor.GetString(recvstr, 48, 16);//신청자성명
                string appresno = Encoding.ASCII.GetString(recvstr, 64, 13);//신청자주번
                string apptype = Encoding.ASCII.GetString(recvstr, 77, 1);//접수구분
                string appyear = Encoding.ASCII.GetString(recvstr, 78, 4);//접수년도
                string appseqno = Encoding.ASCII.GetString(recvstr, 82, 6);//접수일련번호
                string proper = Encoding.ASCII.GetString(recvstr, 88, 1);//신원적합여부
                string detail_res = Encoding.ASCII.GetString(recvstr, 89, 1);//주민
                string detail_cri = Encoding.ASCII.GetString(recvstr, 90, 1);//범죄경력
                string detail_wan = Encoding.ASCII.GetString(recvstr, 91, 1);//수배
                string detail_pol = Encoding.ASCII.GetString(recvstr, 92, 1);//공안
                string detail_sec = Encoding.ASCII.GetString(recvstr, 93, 1);//보안
                string err_stat = Encoding.ASCII.GetString(recvstr, 94, 1);//신원작업상태(에러) 체크
                string err_msg = enkor.GetString(recvstr, 95, 30);//비정상 처리시 내용 통보
                string appattch = enkor.GetString(recvstr, 125, 52);//경호처자료


                if (proper == "X")
                    dgvIDRefer[0, nRowIndex].Value = true;
                else
                    dgvIDRefer[0, nRowIndex].Value = false;
                dgvIDRefer[1, nRowIndex].Value = appseqno.Trim();
                dgvIDRefer[4, nRowIndex].Value = proper.Trim();
                dgvIDRefer[5, nRowIndex].Value = detail_res.Trim();
                dgvIDRefer[6, nRowIndex].Value = detail_cri.Trim();
                dgvIDRefer[7, nRowIndex].Value = detail_wan.Trim();
                dgvIDRefer[8, nRowIndex].Value = detail_pol.Trim();
                dgvIDRefer[9, nRowIndex].Value = detail_sec.Trim();
                dgvIDRefer[10, nRowIndex].Value = err_stat.Trim();
                dgvIDRefer[11, nRowIndex].Value = err_msg.Trim();
                dgvIDRefer[12, nRowIndex].Value = appattch.Trim();
                dgvIDRefer[13, nRowIndex].Value = "처리완료";

                if(detail_wan == "X")
                    dgvIDRefer[7, nRowIndex].Style.ForeColor = Color.Red;
                else
                    dgvIDRefer[7, nRowIndex].Style.ForeColor = Color.Black;

                dgvIDRefer.InvalidateRow(nRowIndex);

            }
            catch (Exception ex)
            {
                Debug.WriteLine("displayPacket:" + ex.Message);
            }
            return nRowIndex;
        }

        private void btnSendReq_Click(object sender, EventArgs e)
        {
            try
            {
#if FALSE
                //TCPClient tcc = new TCPClient();
               // tcc.Connect("127.0.0.1", 4999);

                string sendcmd = "";

                string recvcmd = "";

                sendcmd += "SHOC";

                string tempstr;

                DateTime date = DateTime.Now;

                sendcmd += date.ToString("yyyyMMdd");
                sendcmd += date.ToString("HH/MM/ss");

                tempstr = String.Format("{0,-15}", tbIP.Text);
                //String.Format("{0:-15}", tbIP.Text);
                sendcmd += tempstr;
                string resno = "9912051122345";
                sendcmd += resno;//접수자주민번호

                tempstr = String.Format("{0,-16}", "테스트이름1");

                //String decodedString = enkor.GetString(encodedBytes);
                //Byte[] encodedBytes2 = enkor.GetBytes(decodedString);

                //string appname3 = convstring(tempstr);
                sendcmd += tempstr;
                sendcmd += "0012051122345";
                sendcmd += "1";//접수번호
                sendcmd += date.ToString("yyyy");
                sendcmd += String.Format("{0,-6}","000001");
                sendcmd += String.Format("{0,-52}", "경호처 자료첨부");

//                tcc.sendPacket(sendcmd);
//                tcc.recvPacket(ref recvcmd);
                appType = cbType.SelectedIndex;
                if (th != null && th.IsAlive)
                {
                    th.Abort();
                    th.Join();
                }
                if (client != null)
                {
                    client.Close(3000);
                    client = null;
                }
                IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4999);
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.Connect(ipep);


                NetworkStream m_ns = new NetworkStream(client);
                m_reader = new StreamReader(m_ns);
                m_writer = new StreamWriter(m_ns);

                Byte[] encodedBytes = enkor.GetBytes(sendcmd);

                string decodedString = enkor.GetString(encodedBytes);                
                //String decodedString = enkor.GetString(encodedBytes);

                System.Text.Encoding enc = System.Text.Encoding.ASCII;
                string myString = enc.GetString(encodedBytes);

                m_writer.Write(myString);//Write=코드변환이 안된다.Write 또는 string 타입 파라미터 내부에서 다시 바뀌는듯..
                m_writer.Flush();

#else

#if FALSE                
                if (th != null && th.IsAlive)
                {
                    th.Abort();
                    th.Join();
                }
                if (client != null)
                {
                    client.Close(3000);
                    client = null;
                }
                IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4999);
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.Connect(ipep);


                NetworkStream m_ns = new NetworkStream(client);
                m_reader = new StreamReader(m_ns);
                m_writer = new StreamWriter(m_ns);

                ThreadStart ts = new ThreadStart(ReqProc);
                th = new Thread(ts);
                th.Start();

                nRowIndex = 0;
                sendPacket();
#else


                if (bSentReq > 0)
                {
                    //신원조회요청건수:
                    MessageBox.Show("신원조회요청이 이미 완료된 상태입니다.다른 신규 요청건을 조회하려면 불러오기(Load) 버튼을 누르세요", "신원조회요청",
                        MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }
#if FALSE
                DataGridViewRowCollection dsRows = dgvIDRefer.Rows;
                int nRows = dsRows.GetRowCount(DataGridViewElementStates.Visible);//AddRow 모드 enable 이면 마지막은 빈줄
                if (nRows < 1)
                {
                    MessageBox.Show("요청대상 자료가 비어있습니다.", "신원조회요청",
                        MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }

                if (MessageBox.Show("정보통신 신원조회를 요청하시겠습니까?", "신원조회요청",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) != DialogResult.OK)
                    return;

                nappType = cbType.SelectedIndex;
                myIP = tbIP.Text;
                appTitle = tbSubject.Text;
#endif
                bAbort = false;

                if (thRequest != null && thRequest.IsAlive)
                {
                    thRequest.Abort();
                    thRequest.Join(2000);
                    thRequest = null;
                }

                if (tcc != null)
                {
                    tcc.Close();
                    tcc = null;
                }

                sockerr = false;
                tcc = new TCPClient();
                Socket sock = tcc.Connect(Settings.Default.APPCIp.Trim(),Convert.ToInt32(Settings.Default.APPCPort));

                if (sock == null || (sock != null && sock.Connected == false))
                {
                    MessageBox.Show("네트워크 연결이 실패했습니다.네트워크 상태를 확인후 재시도 하세요.", "정보통신 신원조회 실패", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }
                m_CheckCount = 0;
                lbSecu.Text = m_CheckCount.ToString();
                lbSecu.Invalidate();

                ThreadStart ts = new ThreadStart(ReqProc);
                thRequest = new Thread(ts);
                thRequest.Start();

                m_ProgMainRefDlg = new frmMainReqPop();
                DialogResult rc = m_ProgMainRefDlg.ShowDialog();
                if (rc == DialogResult.Cancel)
                    bAbort = true;


#endif
#endif

            }
            catch (Exception ex)
            {
                //if (client != null && client.Connected) client.Close();
                Debug.WriteLine("Can't connect to remote server:" + ex.Message);
            }

        }

        public void ReqProc()
        {
            int error = 0;
            try
            {
                bSendingReq = 1;
                EnableSearchButton(false);

                Socket sock = tcc.getSocket();
                Byte[] recvcmd = new Byte[200];
                int nCount = 0;
                int nidx = 0;
                int rc = 0;

                CreateTransctionInsert();

                if (sock == null || (sock != null && sock.Connected == false))
                    sockerr = true;

                while (sock != null && sock.Connected && bAbort == false)
                {
                    try
                    {
                        if (sock == null || (sock != null && sock.Connected == false))
                        {
                            sockerr = true;
                            break;
                        }
                        rc = this.sendPacket(nidx);
                        if (rc == -1)
                            break;
                        int rlen = tcc.recvPacket(ref recvcmd, 177);

                        if (rlen <= 0)
                        {
                            sockerr = true;
                            break;
                        }

                        packetParse(nCount, nidx, recvcmd, rlen);

                        //myDele del = new myDele(packetParse);
                        //del(nCount, nidx, recvcmd, rlen);
                        nidx++;
                        nCount++;
                    }
                    catch (Exception ex)
                    {
                        error = 1;
                        Debug.WriteLine("ReqProc error1:" + ex.Message);
                        CancelTransctionInsert();
                    }
                }
                if(tcc != null)
                    tcc.Close();
                tcc = null;

                Debug.WriteLine("close socket");
                //전체 선택된 갯수와 같을때만 정상처리 할것
                if (bAbort || error != 0 || sockerr)
                {
                    CancelTransctionInsert();

                    Debug.WriteLine("CancelTransctionInsert:");
                }
                else if (error == 0)
                    CommitTransctionInsert();

                bSendingReq = 0;
                EnableSearchButton(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("ReqProc error:" + ex.Message);
            }
            finally
            {
                DestroyTransctionInsert();
                ((frmMDIMain)this.ParentForm).WriteSysLog(200, "[" + this.Text + "] " + "정보통신 신원조회 요청");
                CallMainReq(1);
            }
        }

        public void packetParse(int nReqNo,int nRowIndex, Byte[] recvstr, int len)
        {
            if (!this.InvokeRequired)
            {
                string msg = "";
                DataGridViewRowCollection dsRows = dgvIDRefer.Rows;
                int nRows = dsRows.GetRowCount(DataGridViewElementStates.Visible);
                msg = nReqNo + 1 + " / " + nRows;
                m_ProgMainRefDlg.DispMsg(msg);

                dgvIDRefer.Rows[nRowIndex].Selected = true;
                int RowPerPage = dgvIDRefer.DisplayedRowCount(false);
                if(RowPerPage > 0)
                    dgvIDRefer.FirstDisplayedScrollingRowIndex = (nRowIndex / RowPerPage) * RowPerPage;

                return;
            }
            try
            {
                this.displayPacket(nRowIndex, recvstr, len);
                if (nReqNo == 0)//first data which request to host
                {
                    InsertMaster();
                    bSentReq++;//신원조회요청한 건수
                }
                InsertDetail(recvstr);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("packetParse error:" + ex.Message);
            }

            myDele del = new myDele(packetParse);
            this.BeginInvoke(del,nReqNo,nRowIndex,recvstr,len);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            //thread safe
            searchName = tbSearchName.Text;
            searchResNo = tbSearchResNo.Text;
            bSearchAll = radioAll.Checked;

            bSearchName = radioName.Checked;
            bSearchResNo = radioResNo.Checked;
            bSearchCONT = radioCONT.Checked;
            
            bSearchCONT1 = chkCONT1.Checked;
            bSearchCONT2 = chkCONT2.Checked;
            bSearchCONT3 = chkCONT3.Checked;
            bSearchCONT4 = chkCONT4.Checked;
            bSearchCONT5 = chkCONT5.Checked;

            if (bSendingReq == 1)
            {   //신원조회요청이 미종료 상태이면 DB 트랜잭션때문에 Exception 에러가 난다.신원조회요청과 동기화처리
                MessageBox.Show("신원조회요청이 진행중입니다.신원조회요청이 완료된 후 검색하세요", "검색불가",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                return;

            }
            if (masterIDX == -1)//신원조회요청이 수행되었을때 값이 들어온다.문서를 새로 로드하면 요청을 다시해야하기 때문에 reset되어 여기에서 걸린다.
            {
                MessageBox.Show("신원조회요청이 이전에 수행되지 않았습니다.먼저 신원조회요청을 완료한 후 검색하세요", "검색불가",
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                return;

            }

            //if (thSecuReq != null && thSecuReq.IsAlive)
            //{
            //    thSecuReq.Abort();
            //    thSecuReq.Join(3000);
            //    thSecuReq = null;
            //}

            SearchProc();
            //ThreadStart ts = new ThreadStart(SearchProc);
            //thSecuReq = new Thread(ts);
            //thSecuReq.Start();
        }

        //DataSource 바인딩을 쓰면 행삭제가 안된다..

        private void emptyGrid()
        {
            //DataGridViewRowCollection dsRows = dgvIDRefer.Rows;
            //int nRows = dsRows.GetRowCount(DataGridViewElementStates.Visible);//마지막은 빈줄
            //for (int i = nRows - 1; i >= 0; i--)
            //{
            //    try
            //    {
            //        if (dgvIDRefer[2, i].Value != null)
            //            dsRows.Remove(dsRows[i]);
            //    }
            //    catch (Exception ex)
            //    {
            //        Debug.WriteLine("emptyGrid :error remove datagridview:" + ex.Message);
            //    }
            //}
            if (fLoaded == true)
            {
                if (dgvIDRefer.RowCount > 0)
                    dgvIDRefer.Rows.Clear();
                dgvIDRefer.Invalidate();
            }
        }

        private void EnableSearchButton(bool enable)
        {
            if (!this.InvokeRequired)
            {
                btnSearch.Enabled = enable;
                btnSendReq.Enabled = enable;
                btnExportExcel.Enabled = enable;
                btnDetailRefer.Enabled = enable;
                btnLoad.Enabled = enable;
                btnOpen.Enabled = enable;
                //dgvIDRefer.ReadOnly = false;
                if (enable == true)
                {
                    CallRefreshCount(0);
                }
                dgvIDRefer.Invalidate();
            }
            else
            {
                SearchDelegate del = new SearchDelegate(EnableSearchButton);
                this.BeginInvoke(del,enable);
            }
        }

        private void addQueryCond(ref string query,string addstr,int oper)
        {
            if (query.Length > 0)
            {

                if(oper == 0)
                    query += " AND ";
                else if (oper == 1)
                    query += " OR ";
            }
            query += addstr;
        }

        public void SecuRefProc()
        {

            DateTime date = System.DateTime.Now;

            string secuno = getSECUSeqNo();//unique idx
            string year = date.ToString("yyyy");
            string month = date.ToString("MM");

            string filename = date.ToString("yyyyMMdd") + "_" + secuno + ".xls";

            string filepath = Application.StartupPath + "\\" + filename;
            DataTable dt = MakeDataTable();

            Tools.ExportToExcel.ExportToExcel exp = new Tools.ExportToExcel.ExportToExcel();
            exp.dataTable2Excel(dt, null, filepath, "Sheet1");

            string FtpServer = Settings.Default.FtpServerIP;
            string FtpUserName = Settings.Default.FTPUser;
            string FtpPassword = Settings.Default.FtpPassword;
            int FtpPort = Settings.Default.FtpServerPort;

            try
            {
                FtpClient ftp = new FtpClient(FtpServer, FtpUserName, FtpPassword, 20, FtpPort);
                ftp.Login();
                try
                {
                    ftp.MakeDir(year);
                    ftp.ChangeDir(year);
                    ftp.MakeDir(month);
                    ftp.ChangeDir(month);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("ftp.MakeDir: error, file already exists" + ex.Message);
                }

                ftp.BinaryMode = true;
                ftp.Upload(filepath);
                ftp.Close();
                string remotefile = "/" + year + "/" + month + "/" + filename;
                InsertSECUMaster(remotefile, secuReqMemo);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("btnDetailRefer_Click: error " + ex.Message);
            }

            CallSecuReq(1);
        }

        public void SearchProc()
        {
            int error = 0;
            try
            {

                emptyGrid();
                m_CheckCount = 0;

                //>>조건검색 ------------------------------------------------------------------

                //string sqlQuery =   "SELECT * FROM " +
                //                    "(SELECT * FROM PSS_REF_DETAIL WHERE MASTER_ID = @p1) A ";

                string sqlQuery = "	SELECT * " +
                                "	FROM PSS_REF_DETAIL A " +
                                "	JOIN PSS_MASTER B  " +
                                "	ON(A.MASTER_ID = B.IDX) " +
                                "	WHERE (A.MASTER_ID = @p1) ";

                string sqlCond = "";
                string sqlFullCond = "";

                if(bSearchAll)
                    sqlCond = "";
                else if (bSearchName)
                    addQueryCond(ref sqlCond, " REF_NAME = " + "'" + searchName + "%'",-1);
                else if (bSearchResNo)
                    addQueryCond(ref sqlCond, " REF_SOID = " + "'" + searchResNo + "%'",-1);

                else if (bSearchCONT)
                {
                    if (bSearchCONT1)
                        addQueryCond(ref sqlCond, " REF_CONTENT1 = 'X'",-1);
                    if (bSearchCONT2)
                        addQueryCond(ref sqlCond, " REF_CONTENT2 = 'X'", cbCONT1.SelectedIndex);
                    if (bSearchCONT3)
                        addQueryCond(ref sqlCond, " REF_CONTENT3 = 'X'", cbCONT2.SelectedIndex);
                    if (bSearchCONT4)
                        addQueryCond(ref sqlCond, " REF_CONTENT4 = 'X'", cbCONT3.SelectedIndex);
                    if (bSearchCONT5)
                        addQueryCond(ref sqlCond, " REF_CONTENT5 = 'X'", cbCONT4.SelectedIndex);
                }

                if (sqlCond.Length > 0)
                    sqlQuery += " AND ( " + sqlCond + ")";

                sqlQuery += " ORDER BY A.REF_CHK DESC,A.REF_CONTENT1 DESC, A.REF_CONTENT2 DESC, A.REF_CONTENT3 DESC, A.REF_CONTENT4 DESC, A.REF_CONTENT5 DESC;";
                Debug.WriteLine("QUERY = " + sqlQuery);
                //<< 조건검색 ------------------------------------------------------------------

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = sqlQuery;
                cmd.Connection = dbcon;
                cmd.Parameters.Clear();
                cmd.Parameters.Add("@p1", masterIDX);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                try
                {
                    da.Fill(dt);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("SearchProc error:" + ex.Message);
                }
                finally
                {
                    dt.Dispose();
                    cmd.Dispose();
                }
                if (dt.Rows.Count > 0)
                {
                    tbUser.Text = dt.Rows[0]["REF_ACCOUNT"].ToString();
                    tbSubject.Text = dt.Rows[0]["REF_TITLE"].ToString();
                    tbDate.Text = dt.Rows[0]["REF_DATE"].ToString();
                    //접수구분
                    //cbType.SelectedIndex = 0;

                    DataGridViewRowCollection dsRows = dgvIDRefer.Rows;
                    int nchecked = 0;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        dsRows.Add(1);
                        dgvIDRefer[0, i].Value = false;//선택
                        dgvIDRefer[1, i].Value = dt.Rows[i]["REQ_ID"].ToString();  // 접수일련번호
                        dgvIDRefer[2, i].Value = dt.Rows[i]["REF_NAME"].ToString();  // 신청자성명
                        dgvIDRefer[3, i].Value = dt.Rows[i]["REF_SOID"].ToString();  // 신청자주민번호
                        dgvIDRefer[4, i].Value = dt.Rows[i]["REF_CHK"].ToString();  // 신원적합여부
                        dgvIDRefer[5, i].Value = dt.Rows[i]["REF_CONTENT1"].ToString();  // 주민
                        dgvIDRefer[6, i].Value = dt.Rows[i]["REF_CONTENT2"].ToString();  // 범죄경력
                        dgvIDRefer[7, i].Value = dt.Rows[i]["REF_CONTENT3"].ToString();  // 수배
                        dgvIDRefer[8, i].Value = dt.Rows[i]["REF_CONTENT4"].ToString();  // 공안
                        dgvIDRefer[9, i].Value = dt.Rows[i]["REF_CONTENT5"].ToString();  // 보안
                        dgvIDRefer[10, i].Value = dt.Rows[i]["REQ_STATE"].ToString();  // 신원작업상태
                        dgvIDRefer.Columns[12].DisplayIndex = 10;
                        dgvIDRefer[11, i].Value = dt.Rows[i]["ERR_MSG"].ToString();  // 에러메세지
                        dgvIDRefer[12, i].Value = dt.Rows[i]["REQ_ETC"].ToString();  // 경호처자료
                        dgvIDRefer[13, i].Value = "처리완료";
                        string chk = dt.Rows[i]["REF_CHK"].ToString();
                        string wanted = dt.Rows[i]["REF_CONTENT3"].ToString();
                        if (chk == "X")
                        {
                            dgvIDRefer[0, i].Value = true;//선택
                            nchecked++;
                        }
                        else
                            dgvIDRefer[0, i].Value = false;//선택

                        if (wanted == "X")
                            dgvIDRefer[7, i].Style.ForeColor = Color.Red;
                        else
                            dgvIDRefer[7, i].Style.ForeColor = Color.Black;

                        dgvIDRefer.InvalidateRow(i);
                    }
                    //체크박스체크가 표시안됨
                    m_CheckCount = nchecked;
                    m_TotalCount = dt.Rows.Count;
                    CallRefreshCount(1);

                    dgvIDRefer.Invalidate();
                    //dgvIDRefer.Rows[0].Selected = true;

                    
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("SearchProc error:" + ex.Message);
            }
        }

        private DataTable MakeDataTable()//그리드에서 체크항목만을 가져온다
        {
            DataTable mainDT = new DataTable();
            //mainDT.Columns.Add("선택", System.Type.GetType("System.Boolean"));//체크박스

            mainDT.Columns.Add("접수 일련번호", typeof(string));
            mainDT.Columns.Add("신청자 성명", typeof(string));
            mainDT.Columns.Add("신청자 주민번호", typeof(string));
            mainDT.Columns.Add("신원 적합여부", typeof(string));

            mainDT.Columns.Add("주민", typeof(string));
            mainDT.Columns.Add("범죄경력", typeof(string));
            mainDT.Columns.Add("수배", typeof(string));
            mainDT.Columns.Add("공안", typeof(string));
            mainDT.Columns.Add("보안", typeof(string));

            //mainDT.Columns.Add("신원작업상태", typeof(string));
            //mainDT.Columns.Add("에러 메시지", typeof(string));
            mainDT.Columns.Add("경호처자료", typeof(string));

            //mainDT.Columns.Add("호스트 통신상태", typeof(string));
            
            DataGridViewRowCollection dsRows = dgvIDRefer.Rows;
            int nRows = dsRows.GetRowCount(DataGridViewElementStates.Visible);//마지막은 빈줄 - (AllowUserToAddRows = true 인 경우)
            int nRow = 0;
            for (int i = 0; i < nRows; i++)
            {
                DataRow newRow = mainDT.NewRow();
                if (dgvIDRefer[2, i].Value == null)
                    continue;
                int rc = IsRowChecked(i);
                if (rc < -1)
                    break;//end of rows
                if (rc == 0)
                    continue;//not check

                int col = 0;
                int ncol = 0;
                int nCols = dgvIDRefer.Columns.GetColumnCount(DataGridViewElementStates.Visible);
                for (col = 0; col < nCols; col++)
                {
                    if (col == 0 || col == 10 || col == 11 || col == 13) continue;//제외
                    newRow[ncol] = dgvIDRefer[col, i].Value.ToString();
                    ncol++;
                }
                nRow++;
                mainDT.Rows.Add(newRow);    
            }
            return mainDT;
        }

        private void btnExportExcel_Click(object sender, EventArgs e)
        {
            DateTime date = System.DateTime.Now;
            string filename = date.ToString("yyyyMMdd") + tbSubject.Text; 
            
            Tools.ExportToExcel.ExportToExcel exp = new Tools.ExportToExcel.ExportToExcel();
            sfdExportToxcel.FileName = filename + ".xls";
            sfdExportToxcel.Filter = "Excel 파일|*.xls|모든파일|*.*";
            sfdExportToxcel.FilterIndex = 1;
            sfdExportToxcel.RestoreDirectory = true;

            if (sfdExportToxcel.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = sfdExportToxcel.FileName;
                DataTable dt = MakeDataTable();
                try
                {
                    exp.dataTable2Excel(dt, null, path, "Sheet1");
                    ((frmMDIMain)this.ParentForm).WriteSysLog(202, "[" + this.Text + "] " + "정보통신 신원조회 결과 엑셀로 저장");
                }
                catch (Exception ex)
                {

                }
            }
        }

        private string getSECUCount()//마스터에 대한 보안신원조회의 카운트
        {
            int num = 0;
            string mymsg = "0 회";
            string sqlQuery = "SELECT COUNT(*) FROM PSS_POL_SECU WHERE (MASTER_ID = @p1);";

            if (masterIDX < 0)
                return mymsg;
            SqlCommand cmd = new SqlCommand();

            try
            {
                cmd.CommandText = sqlQuery;
                cmd.Connection = dbcon;
                cmd.Parameters.Clear();
                cmd.Parameters.Add("@p1", masterIDX);

                object count = (object)cmd.ExecuteScalar();
                num = Convert.ToInt32(count);// Get the last inserted id.   
            }
            catch (Exception ex)
            {
                Debug.WriteLine("getSECUCount error:" + ex.Message);
            }
            finally
            {
                cmd.Dispose();
            }
            mymsg = String.Format("{0} 회", num);
            return mymsg;
        }

        private string getSECUSeqNo()//보안신원조회마스터 일련번호 11자리를 생성
        {
            int idx = 1;
            string seqno = "";
            string sqlQuery = "SELECT ISNULL(MAX(IDX)+1,1) FROM PSS_POL_SECU;";
            SqlCommand cmd = new SqlCommand();

            try
            {
                cmd.CommandText = sqlQuery;
                cmd.Connection = dbcon;
                cmd.Parameters.Clear();
                object count = (object)cmd.ExecuteScalar();
                idx = Convert.ToInt32(count);// Get the last inserted id.   
            }
            catch (Exception ex)
            {
                Debug.WriteLine("getSECUSeqNo error:" + ex.Message);
            }
            finally
            {
                cmd.Dispose();
            }
            seqno = String.Format("{0,6:000000}", idx);
            return seqno;
        }

        private void frmMainRefer_Resize(object sender, EventArgs e)
        {
            Grid_Resizing(ref dgvIDRefer);
        }

        private void frmMainRefer_ResizeEnd(object sender, EventArgs e)
        {
            Grid_Resizing(ref dgvIDRefer);
        }

        private void Grid_Resizing(ref DataGridView TargetDataGridView)
        {
            Size frmSize = this.ClientSize;
            int dgvLeft = TargetDataGridView.Left;
            int dgvTop = TargetDataGridView.Top;
            TargetDataGridView.Height = frmSize.Height - dgvTop - 13;
            TargetDataGridView.Width = frmSize.Width - SystemInformation.VerticalScrollBarWidth - 13;

            groupBox1.Width = frmSize.Width - SystemInformation.VerticalScrollBarWidth - 13;
            groupBox2.Width = frmSize.Width - SystemInformation.VerticalScrollBarWidth - 13;
            groupBox3.Width = frmSize.Width - SystemInformation.VerticalScrollBarWidth - 13;
        }

        private void chkCONT1_CheckedChanged(object sender, EventArgs e)
        {
            chkCONT2_CheckedChanged(sender, e);
            chkCONT3_CheckedChanged(sender, e);
            chkCONT4_CheckedChanged(sender, e);
            chkCONT5_CheckedChanged(sender, e);
        }

        private void chkCONT2_CheckedChanged(object sender, EventArgs e)//범죄경력
        {
            if (chkCONT1.Checked && chkCONT2.Checked) //주민이 체크안됬으면 비활성화
                cbCONT1.Enabled = true;
            else
                cbCONT1.Enabled = false;
            chkCONT3_CheckedChanged(sender, e);
            chkCONT4_CheckedChanged(sender, e);
            chkCONT5_CheckedChanged(sender, e);
        }

        private void chkCONT3_CheckedChanged(object sender, EventArgs e)//수배
        {
            if (chkCONT3.Checked && (chkCONT1.Checked == true || chkCONT2.Checked == true)) //주민,범죄경력이 체크안됬으면 비활성화
                cbCONT2.Enabled = true;
            else
                cbCONT2.Enabled = false;
            chkCONT4_CheckedChanged(sender, e);
            chkCONT5_CheckedChanged(sender, e);
        }

        private void chkCONT4_CheckedChanged(object sender, EventArgs e)
        {
            if (chkCONT4.Checked && (chkCONT1.Checked == true || chkCONT2.Checked == true || chkCONT3.Checked == true)) //주민,범죄경력이 체크안됬으면 비활성화
                cbCONT3.Enabled = true;
            else
                cbCONT3.Enabled = false;
            chkCONT5_CheckedChanged(sender, e);
        }

        private void chkCONT5_CheckedChanged(object sender, EventArgs e)
        {
            if (chkCONT5.Checked && (chkCONT1.Checked == true || chkCONT2.Checked == true || chkCONT3.Checked == true || chkCONT4.Checked == true)) //주민,범죄경력이 체크안됬으면 비활성화
                cbCONT4.Enabled = true;
            else
                cbCONT4.Enabled = false;

            radioCONT.Checked = true;
        }

        private void dgvIDRefer_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rect = new Rectangle(e.RowBounds.Location.X,
                   e.RowBounds.Location.Y,
                   dgvIDRefer.RowHeadersWidth - 4,
                   e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics,
                         (e.RowIndex + 1).ToString(),
                         dgvIDRefer.RowHeadersDefaultCellStyle.Font,
                         rect,
                         dgvIDRefer.RowHeadersDefaultCellStyle.ForeColor,
                         TextFormatFlags.VerticalCenter | TextFormatFlags.Right);

        }

        private void tbSearchName_TextChanged(object sender, EventArgs e)
        {
            if(tbSearchName.Text.Length > 0)
                radioName.Checked = true;
        }

        private void tbSearchResNo_TextChanged(object sender, EventArgs e)
        {
            if (tbSearchResNo.Text.Length > 0)
                radioResNo.Checked = true;
        }

        private void dgvIDRefer_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void dgvIDRefer_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            dgvIDRefer.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void dgvIDRefer_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex >= 0 && e.ColumnIndex == 0)
                {
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dgvIDRefer.Rows[e.RowIndex].Cells[0];

                    if ((Boolean)checkCell.Value == true)
                        m_CheckCount++;
                    else
                        m_CheckCount--;

                    CallRefreshCount(0);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("CellValueChanged:" + ex.Message);

            }

        }

    }
}
