using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;
using System.Data.SqlClient;
using System.ServiceProcess;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using Microsoft.Win32;
using System.Linq;

using Cosmos.UserFrame;
using Cosmos.BaseFrame;
using Cosmos.Common;
using Cosmos.CommonManager;
using Cosmos.ServiceProvider;

namespace Cosmos.Win
{
    public partial class frmDatabaseInit : Form
    {
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private TranStatus m_cTrnStatus = new TranStatus();                         // 거래정보

        private string m_sPosMenuKey = string.Empty;
        public string PosMenuKey
        {
            get { return this.m_sPosMenuKey; }
            set { this.m_sPosMenuKey = value;}
        }

        #region 생성자
        /// <summary>
        /// 생성자
        /// </summary>
        public frmDatabaseInit()
        {
            InitializeComponent();

            base.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true);
            //this.UpdateStyles();

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보
        }

        private void frmDatabaseInit_Load(object sender, EventArgs e)
        {
            try
            {
                FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);

                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.SCH_MESSAGE_BOX);

                this.Tag = "START";
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        private void frmDatabaseInit_Activated(object sender, EventArgs e)
        {
            try
            {
                if (this.Tag.ToString() == "START")
                {
                    this.Tag = "";

                    if (m_sPosMenuKey == "SQLDB")
                    {
                        // 데이터 베이스 생성
                        lblMessage.Text = "Database initialization";
                        this.Update();

                        ModifyDataBase();

                        // 정산 프로시져 생성
                        LS_ADMT_Procedure();

                        //#20181106 sql server 메모리 제한 스크립트 적용 start
                        //SqlserverMemoryUseLimit();
                        //#20181106 sql server 메모리 제한 스크립트 적용 end
                    }

                    this.Close();
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                this.Close();
            }
        }
        #endregion 

        #region 데이터베이스 복구 처리
        private void DBFileRestoreProc()
        {
            string sMstScriptFile = "MST_DB_RESTORE.SQL";
            string sLogScriptFile = "LOG_DB_RESTORE.SQL";
            string sBackupPath = BaseCom.NxBackPath + PosConst.BACKUP_PATH.DB;
            try
            {
                #region 01-POSMST 복구
                var mstFiles = Directory.GetFiles(sBackupPath, "*_POSMST.BAK").OrderByDescending(filename => filename);
                if (mstFiles.LongCount() > 0)
                {
                    File.Copy(mstFiles.First<String>(), sBackupPath + "POSMST.BAK", true);

                    if (File.Exists(sBackupPath + "POSMST.BAK") == true)
                    {
                        if (File.Exists(BaseCom.NxBinPath + sMstScriptFile) == true)
                        {
                            // Master DB 복구
                            if (File.Exists(BaseCom.NxBinPath + "OSQL_EXEC.bat") == true)
                            {
                                string sExec = BaseCom.NxBinPath + "OSQL_EXEC.bat";
                                string sParam = m_cPosStatus.Base.LocalDbSource + " " + m_cPosStatus.Base.LocalDbUserID + " " + m_cPosStatus.Base.LocalDbPassword + " POSMST " + BaseCom.NxBinPath + sMstScriptFile;
                                CmUtil.ExecuteWaitProcess(sExec, sParam, System.Diagnostics.ProcessWindowStyle.Hidden);

                                // Delete renamed file.
                                System.Threading.Thread.Sleep(300);
                                File.Delete(sBackupPath + "POSMST.BAK");
                            }
                        }
                    }
                }
                #endregion 01-POSMST 복구

                #region 02-POSLOG 복구
                var logFiles = Directory.GetFiles(sBackupPath, "*_POSLOG.BAK").OrderByDescending(filename => filename);
                if (logFiles.LongCount() > 0)
                {
                    File.Copy(logFiles.First<String>(), sBackupPath + "POSLOG.BAK", true);

                    if (File.Exists(sBackupPath + "POSLOG.BAK") == true)
                    {
                        // Log DB 복구
                        if (File.Exists(BaseCom.NxBinPath + "OSQL_EXEC.bat") == true)
                        {
                            string sExec = BaseCom.NxBinPath + "OSQL_EXEC.bat";
                            string sParam = m_cPosStatus.Base.LocalDbSource + " " + m_cPosStatus.Base.LocalDbUserID + " " + m_cPosStatus.Base.LocalDbPassword + " POSMST " + BaseCom.NxBinPath + sLogScriptFile;
                            CmUtil.ExecuteWaitProcess(sExec, sParam, System.Diagnostics.ProcessWindowStyle.Hidden);

                            // Delete renamed file.
                            System.Threading.Thread.Sleep(300);
                            File.Delete(sBackupPath + "POSLOG.BAK");
                        }
                    }
                }
                #endregion 02-POSLOG 복구
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion 데이터베이스 복구 처리

        #region 데이터 베이스 생성 처리
        /// <summary>
        /// 데이터 베이스 생성 처리
        /// </summary>
        private void ModifyDataBase()
        {
            string sSQL = "";
            int nRet = 0;
            DataTable dtReturn = new DataTable();
            
            try
            {
                SqlDB cSqlDB = new SqlDB(m_cPosStatus.Base.LocalDbSource, "MASTER", m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // SQL 서버 연결 체크
                /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                for (int nConn = 0; nConn < 5; nConn++)
                {
                    // 데이터베이스 연결 체크
                    for (int i = 0; i < 10; i++)
                    {
                        sSQL = "SELECT NAME FROM MASTER..SYSDATABASES ORDER BY dbid desc";

                        nRet = cSqlDB.DBDataTableSelect(sSQL, CommandType.Text, (SqlParameter[])null, out dtReturn);
                        if (nRet != UserCom.OK)
                        {
                            UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                "SQL SERVER CONNECT FAIL => " + nRet.ToString());
                            System.Threading.Thread.Sleep(1000);
                            continue;
                        }
                        break;
                    }
                    if (nRet == UserCom.OK) break;       // 연결 성공

                    // DB 연결 실패시 SQL 서비스 재기동 처리
                    cSqlDB.DBClose();
                    //#20171024 restore 주석 start
                    //DBFileRestoreProc();
                    //#20171024 restore 주석 end
                    ChangeSqlService(true);     // SQL 서버 로컬 권한으로 접속 설정 변경(WIN7)
                    ReStartSqlService();        // 서비스 재기동
                    cSqlDB.DBOpen();
                }
                if (nRet != UserCom.OK) return; 

                /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // 마스터 DB 연결 체크
                /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                for (int i = 0; i < 5; i++)
                {
                    sSQL = "SELECT NAME FROM POSMST..sysobjects WHERE type ='u' ORDER BY name";
                    nRet = cSqlDB.DBDataTableSelect(sSQL, CommandType.Text, (SqlParameter[])null, out dtReturn);
                    if (nRet != UserCom.OK)
                    {
                        UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                "SQL SERVER POSMST FAIL => " + nRet.ToString());
                        
                        if (File.Exists(BaseCom.NxMstPath + @"\POSMST.mdf") == true)
                        {
                            sSQL = " ALTER DATABASE POSMST SET OFFLINE WITH ROLLBACK IMMEDIATE ";
                            nRet = cSqlDB.DBExecuteNonQuery(new string[] { sSQL }, CommandType.Text, (SqlParameter[])null, false);

                            sSQL = " EXEC sp_detach_db 'POSMST', 'true' ";
                            nRet = cSqlDB.DBExecuteNonQuery(new string[] { sSQL }, CommandType.Text, (SqlParameter[])null, false);
                            System.Threading.Thread.Sleep(1000);

                            sSQL = " EXEC sp_attach_db @dbname = N'POSMST', ";
                            sSQL += "    @filename1 = N'" + BaseCom.NxMstPath + @"\POSMST.mdf', ";
                            sSQL += "    @filename2 = N'" + BaseCom.NxMstPath + @"\POSMST_log.ldf'";
                            nRet = cSqlDB.DBExecuteNonQuery(new string[] { sSQL }, CommandType.Text, (SqlParameter[])null, false);
                        }
                        System.Threading.Thread.Sleep(1000);
                        nRet = UserCom.NG;
                        continue;
                    }
                    break;
                }

                if (nRet != UserCom.OK)
                {
                    // 마스터 연결 실패시 DB를 생성
                    for (int i = 0; i < 3; i++)
                    {
                        UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                "SQL SERVER POSMST CREATE START");

                        CmUtil.FileCopy(BaseCom.NxMstPath + @"\POSMST.mdf", BaseCom.NxMstPath + @"\POSMST.mdf." + DateTime.Now.ToString("yyyyMMddHHmmss"), true);
                        CmUtil.FileCopy(BaseCom.NxMstPath + @"\POSMST_log.ldf", BaseCom.NxMstPath + @"\POSMST_log.ldf." + DateTime.Now.ToString("yyyyMMddHHmmss"), true);
                        System.Threading.Thread.Sleep(1000);

                        sSQL = "CREATE DATABASE [POSMST] ON  PRIMARY ";
                        sSQL += " ( NAME = N'POSMST', FILENAME = N'" + BaseCom.NxMstPath + @"\POSMST.mdf' , SIZE = 102400KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)";
                        sSQL += " LOG ON";
                        sSQL += " ( NAME = N'POSMST_log', FILENAME = N'" + BaseCom.NxMstPath + @"\POSMST_log.ldf' , SIZE = 10240KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)";

                        nRet = cSqlDB.DBExecuteNonQuery(new string[] { sSQL }, CommandType.Text, (SqlParameter[])null, false);
                        if (nRet == UserCom.OK || nRet == UserCom.NG4)
                        {
                            m_cPosStatus.Base.MstDownDate = m_cPosStatus.Mst.ComplexShopType == "0" ? PosConst.BEGINNING_MST_DOWN_DATE : PosConst.BEGINNING_COMPLEX_SHOP_MST_DOWN_DATE;
                            nRet = UserCom.OK;
                            break;
                        }

                        UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                            "SQL SERVER POSMST CREATE FAIL => " + nRet.ToString());
                        System.Threading.Thread.Sleep(1000);
                    }
                }
                if (nRet != UserCom.OK) return;


                /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // 판매 DB 연결 체크
                /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                for (int i = 0; i < 5; i++)
                {
                    sSQL = "SELECT NAME FROM POSLOG..sysobjects WHERE type ='u' ORDER BY name";
                    nRet = cSqlDB.DBDataTableSelect(sSQL, CommandType.Text, (SqlParameter[])null, out dtReturn);
                    if (nRet != UserCom.OK)
                    {
                        UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                "SQL SERVER POSLOG FAIL => " + nRet.ToString());

                        if (File.Exists(BaseCom.NxDataPath + @"\POSLOG.mdf") == true)
                        {
                            sSQL = " ALTER DATABASE POSLOG SET OFFLINE WITH ROLLBACK IMMEDIATE ";
                            nRet = cSqlDB.DBExecuteNonQuery(new string[] { sSQL }, CommandType.Text, (SqlParameter[])null, false);

                            sSQL = " EXEC sp_detach_db 'POSLOG', 'true' ";
                            nRet = cSqlDB.DBExecuteNonQuery(new string[] { sSQL }, CommandType.Text, (SqlParameter[])null, false);
                            System.Threading.Thread.Sleep(1000);

                            sSQL = " EXEC sp_attach_db @dbname = N'POSLOG', ";
                            sSQL += "    @filename1 = N'" + BaseCom.NxDataPath + @"\POSLOG.mdf', ";
                            sSQL += "    @filename2 = N'" + BaseCom.NxDataPath + @"\POSLOG_log.ldf'";
                            nRet = cSqlDB.DBExecuteNonQuery(new string[] { sSQL }, CommandType.Text, (SqlParameter[])null, false);
                        }

                        System.Threading.Thread.Sleep(1000);
                        nRet = UserCom.NG;
                        continue;
                    }
                    break;
                }
                if (nRet != UserCom.OK)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                "SQL SERVER POSLOG CREATE START");

                        CmUtil.FileCopy(BaseCom.NxDataPath + @"\POSLOG.mdf", BaseCom.NxDataPath + @"\POSLOG.mdf." + DateTime.Now.ToString("yyyyMMddHHmmss"), true);
                        CmUtil.FileCopy(BaseCom.NxDataPath + @"\POSLOG_log.ldf", BaseCom.NxDataPath + @"\POSLOG_log.ldf." + DateTime.Now.ToString("yyyyMMddHHmmss"), true);
                        System.Threading.Thread.Sleep(1000);

                        sSQL = "CREATE DATABASE [POSLOG] ON  PRIMARY ";
                        sSQL += " ( NAME = N'POSLOG', FILENAME = N'" + BaseCom.NxDataPath + @"\POSLOG.mdf' , SIZE = 102400KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)";
                        sSQL += " LOG ON";
                        sSQL += " ( NAME = N'POSLOG_log', FILENAME = N'" + BaseCom.NxDataPath + @"\POSLOG_log.ldf' , SIZE = 10240KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)";

                        nRet = cSqlDB.DBExecuteNonQuery(new string[] { sSQL }, CommandType.Text, (SqlParameter[])null, false);
                        if (nRet == UserCom.OK || nRet == UserCom.NG4)
                        {
                            nRet = UserCom.OK;
                            break;
                        }

                        UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                            "SQL SERVER POSLOG CREATE FAIL => " + nRet.ToString());
                        System.Threading.Thread.Sleep(1000);
                    }
                }
                if (nRet != UserCom.OK) return;

                sSQL = "SELECT TOP 1 * FROM POSMST..MST_ITEM";
                nRet = cSqlDB.DBDataTableSelect(sSQL, CommandType.Text, (SqlParameter[])null, out dtReturn);
                if (nRet != UserCom.OK && nRet != UserCom.NG)
                {
                    // POSMST 테이블 생성
                    if (File.Exists(BaseCom.NxBinPath + "CreateMST.sql") == true)
                    {
                        ExecuteSqlScript(cSqlDB, BaseCom.NxBinPath + @"\CreateMST.sql");

                        // 백업된 AlterMST.sql 복구
                        if (File.Exists(BaseCom.NxBackPath + "AlterMST.sql") == true)
                            CmUtil.FileCopy("AlterMST.sql", BaseCom.NxBackPath, BaseCom.NxBinPath, "");

                        //#20181026 DB파일 재생성 시 마감프로시저도 재생성 할 수 있도록 처리 start
                        // 백업된 SP_ADJUSTMENT.SQL 복구
                        if (File.Exists(BaseCom.NxBackPath + "SP_ADJUSTMENT.SQL") == true)
                            CmUtil.FileCopy("SP_ADJUSTMENT.SQL", BaseCom.NxBackPath, BaseCom.NxBinPath, "");
                        //#20181026 DB파일 재생성 시 마감프로시저도 재생성 할 수 있도록 처리 end

                    }
                }

                sSQL = "SELECT TOP 1 * FROM POSLOG..TR_SALE_HEADER";
                nRet = cSqlDB.DBDataTableSelect(sSQL, CommandType.Text, (SqlParameter[])null, out dtReturn);
                if (nRet != UserCom.OK && nRet != UserCom.NG)
                {
                    // POSLOG 테이블 생성
                    if (File.Exists(BaseCom.NxBinPath + "CreateLOG.sql") == true)
                    {
                        ExecuteSqlScript(cSqlDB, BaseCom.NxBinPath + @"\CreateLOG.sql");

                        // 백업된 AlterLOG.sql 복구
                        if (File.Exists(BaseCom.NxBackPath + "AlterLOG.sql") == true)
                            CmUtil.FileCopy("AlterLOG.sql", BaseCom.NxBackPath, BaseCom.NxBinPath, "");
                    }
                }

                // POSMST 테이블 변경 스크립트 실행
                if (File.Exists(BaseCom.NxBinPath + "AlterMST.sql") == true)
                {
                    ExecuteSqlScript(cSqlDB, BaseCom.NxBinPath + "AlterMST.sql");
                    // Backup
                    CmUtil.FileMove("AlterMST.sql", BaseCom.NxBinPath, BaseCom.NxBackPath, "", "AlterMST.sql");
                }

                // POSLOG 테이블 변경 스크립트 실행
                if (File.Exists(BaseCom.NxBinPath + "AlterLOG.sql") == true)
                {
                    ExecuteSqlScript(cSqlDB, BaseCom.NxBinPath + "AlterLOG.sql");
                    // Backup
                    CmUtil.FileMove("AlterLOG.sql", BaseCom.NxBinPath, BaseCom.NxBackPath, "", "AlterLOG.sql");
                }


                //  2019-02-19 - 1997fx11 : Kiosk용 Table 생성 시작 (target DB : POSMST)
                sSQL = "SELECT TOP 1 * FROM POSMST..NHS_PRD_MST";
                nRet = cSqlDB.DBDataTableSelect(sSQL, CommandType.Text, (SqlParameter[])null, out dtReturn);
                if (nRet != UserCom.OK && nRet != UserCom.NG)
                {
                    // POSMST 테이블 생성
                    if (File.Exists(BaseCom.NxBinPath + "CreateMST.Kiosk.sql") == true)
                    {
                        ExecuteSqlScript(cSqlDB, BaseCom.NxBinPath + @"\CreateMST.Kiosk.sql");
                    }
                }
                //  Kiosk용 Table 생성 종료
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        /// <summary>
        /// SQL 서버 로컬 권한으로 접속 설정 변경(WIN7)
        /// </summary>
        private void ChangeSqlService(bool bLocal)
        {
            try
            {
                if (bLocal == true)
                {
                    RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\MSSQL$SPCPOS\", RegistryKeyPermissionCheck.ReadWriteSubTree);

                    if (regKey == null) return;

                    //RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\MSSQLSERVER\", RegistryKeyPermissionCheck.ReadWriteSubTree);
                    if (regKey.GetValue("ObjectName").ToString() == "LocalSystem" && regKey.GetValue("Type").ToString() == "272") return;

                    regKey.SetValue("ObjectName", "LocalSystem", RegistryValueKind.String);
                    regKey.SetValue("Type", 0x110, RegistryValueKind.DWord);

                    UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                            "SQL SERVER SERVICE SET CHANGE => " + "LocalSystem");
                }
                else
                {
                    RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\MSSQL$SPCPOS\", RegistryKeyPermissionCheck.ReadWriteSubTree);

                    if (regKey == null) return;
                    
                    //RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\MSSQLSERVER\", RegistryKeyPermissionCheck.ReadWriteSubTree);
                    if (regKey.GetValue("ObjectName").ToString() == @"NT AUTHORITY\NetworkService" && regKey.GetValue("Type").ToString() == "16") return;

                    regKey.SetValue("ObjectName", @"NT AUTHORITY\NetworkService", RegistryValueKind.String);
                    regKey.SetValue("Type", 0x10, RegistryValueKind.DWord);

                    UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                            "SQL SERVER SERVICE SET CHANGE => " + @"NT AUTHORITY\NetworkService");
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        /// <summary>
        /// SQL 서버 서비스 재기동
        /// </summary>
        private void ReStartSqlService()
        {
            try
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                            "SQL SERVER SERVICE RESTART");

                // SQL 서버 설정 변경시 서비스 재기동
                //ServiceController service = new ServiceController(@"MSSQLSERVER");
                ServiceController service = new ServiceController(@"MSSQL$SPCPOS");
                TimeSpan timeout = TimeSpan.FromMilliseconds(5000);

                try
                {
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                }
                catch { }

                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        /// <summary>
        /// SQL 스크립트 파일 실행
        /// </summary>
        private bool ExecuteSqlScript(SqlDB cSqlDB, string sFileName)
        {
            try
            {
                string sScript = CmUtil.ReadTextFile(sFileName);
                if (sScript == "") return true;

                UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                            "SQL SERVER EXEC SCRIPT => " + sFileName);

                string[] saQuery = sScript.Split(new string[] { "\n\r", "\r\n" }, StringSplitOptions.None);
                string sQuery = "";
                foreach (string sData in saQuery)
                {
                    if (sData.Trim().ToUpper() == "GO")
                    {
                        int nRet = cSqlDB.DBExecuteNonQuery(new string[] { sQuery }, CommandType.Text, (SqlParameter[])null, false);
                        if (nRet != UserCom.OK && nRet != UserCom.NG4)
                        {
                            UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                    "SQL SERVER EXEC SCRIPT FAIL");
                        }
                        sQuery = "";
                    }
                    else
                    {
                        sQuery += sData + PosConst.CRLF;
                    }
                }

                if ( sQuery != "")
                {
                    int nRet = cSqlDB.DBExecuteNonQuery(new string[] { sQuery }, CommandType.Text, (SqlParameter[])null, false);
                    if (nRet != UserCom.OK && nRet != UserCom.NG4)
                    {
                        UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                "SQL SERVER EXEC SCRIPT FAIL");
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return false;
        }
        #endregion 

        #region 정산 프로시져 생성 및 수정
        /// <summary>
        /// 정산 프로시져 생성 및 수정
        /// </summary>
        /// <returns></returns>
        private string LS_ADMT_Procedure()
        {
            string sRet = UserCom.RST_ERR;
            string sFileName = "SP_ADJUSTMENT.SQL";

            try
            {
                /*
                // 프로시져 변경시 참고사항 (중요) 

                // 프로시져 생성 샘픔
                //USE [POSMST]
                //go

                //DROP PROC dbo.SP_ADJUSTMENT
                //GO
               
                //CREATE PROC dbo.SP_ADJUSTMENT
                // 기존거 삭제후 적용
                */

                // Main Pos인 경우만 실행
                
                //if (LoadPosMaster() != PosConst.MAIN_POS_DIV.MAIN_POS) return sRet;

                if (File.Exists(BaseCom.NxBinPath + sFileName) == true)
                {
                    // 프로시져 적용
                    if (File.Exists(BaseCom.NxBinPath + "OSQL_EXEC.bat") == true)
                    {
                        string sExec = BaseCom.NxBinPath + "OSQL_EXEC.bat ";
                        string sParam = m_cPosStatus.Base.LocalDbSource + " " + m_cPosStatus.Base.LocalDbUserID + " " + m_cPosStatus.Base.LocalDbPassword + " POSMST " + BaseCom.NxBinPath + sFileName;
                        CmUtil.ExecuteWaitProcess(sExec, sParam, System.Diagnostics.ProcessWindowStyle.Hidden);

                        // Backup
                        CmUtil.FileMove(sFileName, BaseCom.NxBinPath, BaseCom.NxBackPath, "", sFileName);
                    }
                }

                sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return sRet;
        }
        #endregion 

        #region POS 마스터 로딩
        /// <summary>
        /// POS 마스터 로딩
        /// </summary>
        /// <returns></returns>
        public string LoadPosMaster()
        {
            string sQuery = "";
            string sRet = PosConst.MAIN_POS_DIV.MAIN_POS;

            try
            { 
                IMasterUs m_cMstService = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.POS_MASTER);
                // POS 마스터 로딩
                sQuery = "SELECT * FROM POSMST..MST_POS WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' AND POS_NO = '" + m_cPosStatus.Base.PosNo + "'";
                sQuery += "   AND USE_YN  = '" + PosConst.MST_USE_YN.YES + "'";
                DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });

                if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                {
                    DataRow dr = dtDataInfo.Rows[0];

                    // 메인POS 구분 설정(0:서브POS, 1:메인POS)
                    sRet = CmUtil.GetDataRowStr(dr, PosMst.MST_POS.DATA.MAIN_YN);
                }
                
                //if (sRet != PosConst.MAIN_POS_DIV.MAIN_POS) sRet = PosConst.MAIN_POS_DIV.SUB_POS;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return sRet;
        }
        #endregion

        //#20181106 sql server 메모리 제한 스크립트 적용 start
        #region SQLSERVER_MAX_MEMORY.BAT 실행 (Sql Server 메모리 사용량 512MB 제한하기)
        /*
        private void SqlserverMemoryUseLimit()
        {
            try
            {
                //XP만 적용.
                OperatingSystem OS = Environment.OSVersion;

                if (OS.Platform == PlatformID.Win32NT && OS.Version.Major == 5)
                {
                    string sFileName = "SQLSERVER_MAX_MEMORY.SQL";

                    if (File.Exists(BaseCom.NxBinPath + "OSQL_EXEC.bat") == true)
                    {
                        string sExec = BaseCom.NxBinPath + "OSQL_EXEC.bat";
                        string sParam = m_cPosStatus.Base.LocalDbSource + " " + m_cPosStatus.Base.LocalDbUserID + " " + m_cPosStatus.Base.LocalDbPassword + " MASTER " + BaseCom.NxBinPath + sFileName;
                        CmUtil.ExecuteWaitProcess(sExec, sParam, System.Diagnostics.ProcessWindowStyle.Hidden);

                        // Backup
                        CmUtil.FileMove(sFileName, BaseCom.NxBinPath, BaseCom.NxBackPath, "", sFileName);
                    }
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        */
        #endregion
        //#20181106 sql server 메모리 제한 스크립트 적용 end
    }
}
