using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Xml;
using iMESCIO.SCI.ERP.Request;
using iMESCIO.SCI.ERP.Response;
using iMESCIO.SCI.ERP.Request_E10ICD;
using iMESCIO.SCI.ERP.Response_E10ICD;
using iMESCIO.SCI.Base;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using iMESCore.Settings;
using static iMESCore.DataBase.iMESSql;
using static iMESCore.Base.iMESComXML;
using static iMESCore.Base.iMESConst;
using static iMESCore.Base.iMESComSubroutine;
using System.Data.Common;

namespace AutoRunLib_C
{




    public class clsAutoRunLibrary
    {

        // 2016/06/23 YF, 原呼叫標準各模組的WebService, 改統一呼叫wsInvoke

        public enum ERPName
        {
            TIPTOP = 0,
            Workflow = 1,
            T100 = 2,
            HMI = 3,
            APS = 4
        }

        private DataTable dtERPSetting = null;

        private IDbCommand cmmTemp;
        private string strDataBaseType;                 // DataBase Type:oracle, mysql, access
        private string strConnectionString;             // Connection string
        private string strReportDataBaseType;
        private string strReportConnectionString;       // Report DB Connection string
        private string strMQType;                       // MessageQueue Type:TIBCO, MQSeries, MSMQ

        private IDbCommand cmmTempERP;
        private string strERPconnectionString;
        private string strERPDataBaseType;
        private string strERPReportConnectionString;

        private string strERPCreator = "ERP";    // 取得Config設定之defCreator.
        private string strDefLanguage;                // 取得Config設定之LanguageMode.
        private string strLanguage_T100;           // MES對應ERP T100語系

        private AppSettings objSetting = new AppSettings();
        private clsDBCom objDBcom = new clsDBCom();

        public string strComputerName, strERPUnitNo;
        public string strAppPath;

        public string gERPUser;             // ERP使用者名稱
        public string gERPPassword;         // ERP密碼
        public string gERPWSURL;            // ERP Web服務網址
        public string gERPOraganization;    // ERP營運中心代碼
        public string gERPLanguage;         // ERP語系
        public string gERPVersion;          // ERP版本

        // //Web Service相關變數
        private XmlDocument XmlDoc = new XmlDocument();
        private StringReader tmpStringReader;
        private string InXml, OutXml, strIdentity, strParameter, XmlData, XmlSchema;

        private string ExceptionXML; // =====

        private string ERP_EntID;
        private string ERP_Site;
        private string ERP_URL;
        private string results;
        private string strLanguageMode = "zh-cht";
        private string strResourceDir = "Resources";

        // Dim objkcWIP As New kcWIP.clsOperatorState   '宣告Sys的物件

        // //Initial Object--------------------------------------------------------------------------------------------------------------------------------
        public clsAutoRunLibrary()
        {
            // //Get database type
            strDataBaseType = objSetting.GetDataBaseType();
            // //Get connection string
            strConnectionString = objSetting.GetConnectionString(strDataBaseType);
            // //Get Message Queue Type
            strMQType = objSetting.GetMQType();

            strReportDataBaseType = objSetting.GetReportDataBaseType();
            // //Get connection string    
            strReportConnectionString = objSetting.GetReportConnectionString(strReportDataBaseType);

            // ERP
            // //Get ERP database type
            strERPDataBaseType = objSetting.GetDataBaseType_ERP();
            // //Get ERP connection string
            strERPconnectionString = objSetting.GetConnectionString_ERP(strERPDataBaseType);

            try
            {
                strResourceDir = objSetting["ResourceDir"].ToString();
            }
            catch (Exception)
            { }
            try
            {
                strLanguageMode = objSetting["LanguageMode"].ToString();
            }
            catch (Exception)
            {
            }

            // T100 整合項目增加,  取得 Web.Config 設定項目, 2015/12/15 Add.

            try
            {
                // 從Web.config取出目前的DatabaseType
                strERPCreator = System.Configuration.ConfigurationSettings.AppSettings.Get("defCreator");
                // 2016-03-09, Joe, 取出預設ERP單位屬性編號
                strERPUnitNo = System.Configuration.ConfigurationSettings.AppSettings.Get("defERPUnitNoProperty");
                // 2016-03-02, Joe, 取出預設語系並轉換成ERP對應語系，後續T100多語系資料需用到
                strDefLanguage = System.Configuration.ConfigurationSettings.AppSettings.Get("LanguageMode");
                switch (strDefLanguage.ToUpper() ?? "")
                {
                    case "ZH-CHS":
                        {
                            strLanguage_T100 = "zh_CN";
                            break;
                        }
                    case "EN":
                        {
                            strLanguage_T100 = "en_US";
                            break;
                        }

                    default:
                        {
                            strLanguage_T100 = "zh_TW";
                            break;
                        }
                }
            }
            catch (Exception ex)
            {
                // 發生錯誤時丟回本身的Function Name及系統錯誤訊息
            }


        }


        // //Property--------------------------------------------------------------------------------------------------------------------------------
        public string ConnectionString
        {
            get
            {
                return strConnectionString;
            }
        }

        public string DataBaseType
        {
            get
            {
                return strDataBaseType;
            }
        }

        // Public ReadOnly Property ERPConnectionString()
        // Get
        // ERPConnectionString = strERPconnectionString
        // End Get
        // End Property

        // Public ReadOnly Property ERPDataBaseType()
        // Get
        // ERPDataBaseType = strERPDataBaseType
        // End Get
        // End Property

        public string MQType
        {
            get
            {
                return strMQType;
            }
        }


        // //Function--------------------------------------------------------------------------------------------------------------------------------
        #region 共用的function (不可刪除)

        // //Public function----------------------------------------------------------------------------------------------------
        public string ExecuteFunction(string FunctionName, Collection colParameters = null)
        {
            string ExecuteFunctionRet = default(string);
            // 此 Function 將執行傳入之FunctionName
            // 傳入值: FunctionName,colParameters
            // 傳回值: DataSet(成功), nothing(失敗)

            // colParameters的資料範例如下
            // colParameters.Add("C1", "CustomerNo")
            // colParameters.Add("P1", "ProductNo")

            int i;

            try
            {
                // 2019/07/26 OwenLiu, Mantis:0060463, AutoRunService 支持行業包共用架構
                // --------------------------------------------------------------------------------------------------
                // 半導體芯片製造行業包(SEMI_WAFER)：S, AutoRunLib_SEMI_WAFER.dll, Job Function固定以 fun_S_ 開頭
                // 半導體芯片測試行業包(IC_CP_PKG)：P, AutoRunLib_IC_CP_PKG.dll, Job Function固定以 fun_P_ 開頭
                // 集成電路封測行業包(IC_FT_PKG)：I, AutoRunLib_IC_FT_PKG.dll, Job Function固定以 fun_I_ 開頭
                // 分立器件封測行業包(DISCRETE_PKG)：D, AutoRunLib_DISCRETE_PKG.dll, Job Function固定以 fun_D_ 開頭
                // LED封測行業包(LED_PKG)：L, AutoRunLib_LED_PKG.dll, Job Function固定以 fun_L_ 開頭
                // 序號組裝行業包(ASM)：A, AutoRunLib_ASM.dll, Job Function固定以 fun_A_ 開頭
                // --------------------------------------------------------------------------------------------------
                // 1.處理 FunctionName 大小寫問題
                // 本機執行:將DLL放在執行檔編譯後的位置底下(AutoRunService)
                string strFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\";
                string strLibFileName = "";
                string strLibraryName = "";
                if (FunctionName.ToUpper().StartsWith("FUN_S_")) // SEMI_WAFER
                {
                    strLibFileName = "AutoRunLib_SEMI_WAFER.dll";
                }
                else if (FunctionName.ToUpper().StartsWith("FUN_P_")) // IC_CP_PKG
                {
                    strLibFileName = "AutoRunLib_IC_CP_PKG.dll";
                }
                else if (FunctionName.ToUpper().StartsWith("FUN_I_")) // IC_FT_PKG
                {
                    strLibFileName = "AutoRunLib_IC_FT_PKG.dll";
                }
                else if (FunctionName.ToUpper().StartsWith("FUN_D_")) // DISCRETE_PKG
                {
                    strLibFileName = "AutoRunLib_DISCRETE_PKG.dll";
                }
                else if (FunctionName.ToUpper().StartsWith("FUN_L_")) // LED_PKG
                {
                    strLibFileName = "AutoRunLib_LED_PKG.dll";
                }
                else if (FunctionName.ToUpper().StartsWith("FUN_A_")) // ASM
                {
                    strLibFileName = "AutoRunLib_ASM.dll";
                }
                else if (FunctionName.ToUpper().StartsWith("FUN_C_")) // 個案
                {
                    strLibFileName = "AutoRunLib_C.dll";
                }
                else
                {
                    strLibFileName = "AutoRunLib.dll";
                }
                strLibraryName = strLibFileName.Substring(0, strLibFileName.LastIndexOf(".dll")) + ".clsAutoRunLibrary";
                strFilePath += strLibFileName;
                var mainAssembly = System.Reflection.Assembly.LoadFrom(strFilePath);
                System.Reflection.MethodInfo[] MyMethodInfos = mainAssembly.GetType(strLibraryName).GetMethods(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); // 取出Private的Function

                var loopTo = MyMethodInfos.Length - 1;
                for (i = 0; i <= loopTo; i++)
                {
                    if ((MyMethodInfos[i].Name.ToUpper() ?? "") == (FunctionName.ToUpper() ?? ""))
                    {
                        FunctionName = MyMethodInfos[i].Name;
                        break;
                    }
                }

                // 2.執行Private Function,傳出DataSet
                object objArgs = new object[] { colParameters };
                string strClassName = "clsAutoRunLibrary";
                Type t;
                System.Reflection.MethodInfo mi;
                Type[] argumentTypes;
                System.Reflection.ConstructorInfo ctor;
                object obj;

                try
                {
                    t = mainAssembly.GetType(mainAssembly.GetName().Name + "." + strClassName, true, true);
                }
                catch (Exception ex)
                {
                    throw;
                }

                argumentTypes = Type.EmptyTypes;
                ctor = t.GetConstructor(argumentTypes);
                obj = ctor.Invoke(new object[] { });
                mi = t.GetMethod(FunctionName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

                ExecuteFunctionRet = Conversions.ToString(mi.Invoke(obj, (object[])objArgs));
            }


            catch (Exception e1)
            {
                // 2016-08-25, Joe, 加.InnerException將exception傳出
                if (e1.InnerException == null)
                {
                    ExecuteFunctionRet = "fail;" + e1.Message;
                }
                else
                {
                    ExecuteFunctionRet = "fail;" + e1.InnerException.Message;
                }
            }

            finally
            {

            }

            return ExecuteFunctionRet;

        }

        private string SendMultiEmailNonGroup(ref string EmailSubject, string EmailBody = defString, string EmailAddress = defString, string AttachFileName = defString, byte[] AttachFile = null, string EmailAddressCC = defString)
        {
            string SendMultiEmailNonGroupRet = default(string);

            // 將發Mail給非群組收件者 多人可用 , 隔開

            string[] aryAddress, aryAddressCC;
            string tmpXML = default(string), tmpXMLCC = default(string);
            aryAddress = Strings.Split(EmailAddress, ",");

            // 子收件者包幾個child tag
            foreach (string StrTemp in aryAddress)
            {
                string argTagName = "address";
                string argValue = CombineXMLValue(argTagName, StrTemp);
                tmpXML += CombineXMLValueTag(argValue);
            }

            if ((EmailAddressCC ?? "") != defString && !string.IsNullOrEmpty(EmailAddressCC))
            {
                aryAddressCC = Strings.Split(EmailAddressCC, ",");
                foreach (string StrTemp in aryAddressCC)
                {
                    string argTagName1 = "address";
                    string argValue1 = CombineXMLValue(argTagName1, StrTemp);
                    tmpXMLCC += CombineXMLValueTag(argValue1);
                }
            }


            try
            {
                string argCurUserNo = "AUTORUN";
                string argSendTime = Conversions.ToString(DateTime.Now);
                strIdentity = CombineXMLIdentity(modWIN.gComputerName, argCurUserNo, argSendTime);
                string argvalue_name = "emailaddress";
                string argname = "EmailAddress";
                string argtype = "String";
                string argdesc = "";
                strParameter = CombineXMLParameterMultiValue(argvalue_name, argname, argtype, tmpXML, argdesc);
                string argvalue_name1 = "emailsubject";
                string argname1 = "EmailSubject";
                string argtype1 = "String";
                string argdesc1 = "";
                strParameter += CombineXMLParameter(argvalue_name1, argname1, argtype1, EmailSubject, argdesc1);
                string argvalue_name2 = "emailbody";
                string argname2 = "EmailBody";
                string argtype2 = "String";
                string argvalue = CInput(EmailBody);
                string argdesc2 = "";
                strParameter += CombineXMLParameter(argvalue_name2, argname2, argtype2, argvalue, argdesc2);

                if (!string.IsNullOrEmpty(tmpXMLCC))
                {
                    string argvalue_name3 = "emailaddresscc";
                    string argname3 = "EmailAddressCC";
                    string argtype3 = "String";
                    string argdesc3 = "";
                    strParameter += CombineXMLParameterMultiValue(argvalue_name3, argname3, argtype3, tmpXMLCC, argdesc3);
                }

                if ((AttachFileName ?? "") != defString)
                {
                    string argvalue_name4 = "attachfilename";
                    string argname4 = "AttachFileName";
                    string argtype4 = "String";
                    string argdesc4 = "";
                    strParameter += CombineXMLParameter(argvalue_name4, argname4, argtype4, AttachFileName, argdesc4);
                }

                var XmlDoc = new XmlDocument();
                InXml = CombineXMLRequest(strIdentity, strParameter);

                if ((AttachFileName ?? "") != defString)
                {
                    OutXml = modAutoRunLibrary.InvokeSrv("wsSYS.SendMultiEmailAndAttachFile", InXml, AttachFile);
                }
                else
                {
                    OutXml = modAutoRunLibrary.InvokeSrv("wsSYS.SendMultiEmail", InXml);
                }

                XmlDoc.LoadXml(OutXml);

                if (chkExecutionSuccess(XmlDoc))  // 找出Exception訊並顯示出來
                {
                    SendMultiEmailNonGroupRet = "success";
                }
                else
                {
                    // 20220901,13871,0118251: 【度亘】描述性语言报表，排程执行失败,調整錯誤訊息
                    SendMultiEmailNonGroupRet = "fail;" + GetExceptionMesMsg(XmlDoc) + ";" + GetExceptionSysMsg(XmlDoc);
                }

                XmlDoc = null;
            }

            catch (Exception ex)
            {
                SendMultiEmailNonGroupRet = "fail;" + ex.Message;
            }

            return SendMultiEmailNonGroupRet;

        }

        private void SendJobFailEmail(Collection colParameters)
        {
            // 發送Email前置作業, 可判別群組與非群組寄送

            var dsGroup = new DataSet();
            var strGroupBasis = default(string);

            string[] aryEmailAddress;
            string strEmailAddress, strNonGroup = default(string), strGroup = default(string), strEmailBody, strEmailTitle; // EmailInfo

            // 取出參數EmailAddress 取不到則不發送
            // 2013/10/18, Hank, 修改若無EmailAddress欄位會crash
            if (colParameters.Contains("EmailAddress") == false || colParameters["EmailAddress"] == null || string.IsNullOrEmpty(Strings.Trim(Conversions.ToString(colParameters["EmailAddress"]))))
            {
                return;
            }
            else
            {
                strEmailAddress = Strings.Trim(Conversions.ToString(colParameters["EmailAddress"]));
            }
            strEmailTitle = "MES AutoRun-" + Strings.Trim(Conversions.ToString(colParameters["JobNo"])) + " Fail";
            strEmailBody = Strings.Trim(Conversions.ToString(colParameters["EmailBody"]));

            LoadGroupBasis(ref dsGroup);

            // 切出 有效群組與非群組
            aryEmailAddress = Strings.Split(strEmailAddress, ",");
            for (int i = 0, loopTo = aryEmailAddress.Length - 1; i <= loopTo; i++)
            {
                if (System.Text.RegularExpressions.Regex.Matches(aryEmailAddress[i], "@").Count == 1)  // Non Group
                {
                    strNonGroup += Strings.Trim(aryEmailAddress[i]) + ",";
                }
                else if (dsGroup.Tables[strGroupBasis].Select("GroupNo ='" + Strings.Trim(aryEmailAddress[i]) + "'").Length > 0) // Group 
                {
                    strGroup += Strings.Trim(aryEmailAddress[i]) + ",";
                }
            }

            // 去掉最後字元為 ,
            if (Strings.Right(strGroup, 1) == ",")
                strGroup = Strings.Mid(strGroup, 1, Strings.Len(strGroup) - 1);
            if (Strings.Right(strNonGroup, 1) == ",")
                strNonGroup = Strings.Mid(strNonGroup, 1, Strings.Len(strNonGroup) - 1);

            // 群組寄送
            if (!string.IsNullOrEmpty(strGroup))
            {
                string argFileName = "N/A";
                modAutoRunLibrary.SendMultiEmail(ref argFileName, ref strEmailTitle, strEmailBody, strGroup);
            }
            // 非群組寄送
            if (!string.IsNullOrEmpty(strNonGroup))
            {
                SendMultiEmailNonGroup(ref strEmailTitle, strEmailBody, strNonGroup);
            }

        }

        private string ChgTranslateName(Collection ColSaveControl, string LanguageMode = "en")
        {
            // 目的：
            // 將 Collection 上所有的 Object 都做語系切換
            // 語系檔命名為 MESResource.XX.Resx
            // zh-CHS（簡體）、zh-CHT（繁體）、en（英文）

            string strResourceFile;

            if (string.IsNullOrEmpty(LanguageMode))
            {
                return default(string);
            }
            else
            {
                strResourceFile = "MESResource." + LanguageMode;
            }

            string strResourcePath;
            strResourcePath = AppDomain.CurrentDomain.BaseDirectory + "Resources";

            // 檢查檔案是否存在
            if (string.IsNullOrEmpty(FileSystem.Dir(strResourcePath + @"\" + strResourceFile + ".resources")))  // File not exist
            {
                return default(string);
            }

            var rm = System.Resources.ResourceManager.CreateFileBasedResourceManager(strResourceFile, strResourcePath, null);
            string TmpString;
            int i;

            foreach (var objControl in ColSaveControl)
            {
                if (objControl is iMESUltraGrid.iMESUltraGridControl)
                {
                    TmpString = Conversions.ToString((objControl as iMESUltraGrid.iMESUltraGridControl).Name.Substring(3, (Strings.Len((objControl as iMESUltraGrid.iMESUltraGridControl).Name) - 3)));
                    TmpString = rm.GetString(TmpString.ToUpper());
                    if (Conversions.ToBoolean(Operators.AndObject(!string.IsNullOrEmpty(TmpString), Operators.ConditionalCompareObjectNotEqual((objControl as iMESUltraGrid.iMESUltraGridControl).iMESUltraGrid.Text, "", false))))
                    {
                        (objControl as iMESUltraGrid.iMESUltraGridControl).iMESUltraGrid.Text = TmpString;
                    }
                }

                else if (objControl is Infragistics.Win.UltraWinGrid.UltraGrid)
                {

                    int bandCount;
                    int colCount;

                    var loopTo = ((Infragistics.Win.UltraWinGrid.UltraGrid)objControl).DisplayLayout.Bands.Count - 1;
                    for (bandCount = 0; bandCount <= loopTo; bandCount++)
                    {

                        var loopTo1 = ((Infragistics.Win.UltraWinGrid.UltraGrid)objControl).DisplayLayout.Bands[bandCount].Columns.Count - 1;
                        for (colCount = 0; colCount <= loopTo1; colCount++)
                            ((Infragistics.Win.UltraWinGrid.UltraGrid)objControl).DisplayLayout.Bands[bandCount].Columns[colCount].Header.Caption = Conversions.ToString(Interaction.IIf(string.IsNullOrEmpty(rm.GetString(((Infragistics.Win.UltraWinGrid.UltraGrid)objControl).DisplayLayout.Bands[bandCount].Columns[colCount].Key.ToUpper())), ((Infragistics.Win.UltraWinGrid.UltraGrid)objControl).DisplayLayout.Bands[bandCount].Columns[colCount].Header.Caption, rm.GetString(((Infragistics.Win.UltraWinGrid.UltraGrid)objControl).DisplayLayout.Bands[bandCount].Columns[colCount].Key.ToUpper())));

                        // 20120911, Aaron, Group By Box
                    } ((Infragistics.Win.UltraWinGrid.UltraGrid)objControl).DisplayLayout.GroupByBox.ResetPrompt();
                    TmpString = ((Infragistics.Win.UltraWinGrid.UltraGrid)objControl).DisplayLayout.GroupByBox.Prompt;
                    TmpString = rm.GetString(TmpString.ToUpper());

                    if (!string.IsNullOrEmpty(TmpString))
                    {
                        ((Infragistics.Win.UltraWinGrid.UltraGrid)objControl).DisplayLayout.GroupByBox.Prompt = TmpString;
                    }
                }
                TmpString = "";
            }

            return default(string);

        }
        public string ChgTranslateName_Content(string ErrorName)
        {
            string ChgTranslateName_ContentRet = default(string);

            // 1.Check LanguageMode
            string strMsgFile, strGenFile;
            if (string.IsNullOrEmpty(modWIN.gLanguageMode))
            {
                strMsgFile = "msg_name" + "en";
                strGenFile = "mesresource" + "en";
            }
            else
            {
                strMsgFile = "msg_name." + modWIN.gLanguageMode;
                strGenFile = "mesresource." + modWIN.gLanguageMode;
            }

            // 2.Get File Path
            string strResourcePath = AppDomain.CurrentDomain.BaseDirectory + "Resources";

            // 檢查檔案是否存在
            if (string.IsNullOrEmpty(FileSystem.Dir(strResourcePath + @"\" + strMsgFile + ".resources")))  // File not exist
            {
                ChgTranslateName_ContentRet = ErrorName;
                return ChgTranslateName_ContentRet;
            }
            if (string.IsNullOrEmpty(FileSystem.Dir(strResourcePath + @"\" + strGenFile + ".resources")))  // File not exist
            {
                ChgTranslateName_ContentRet = ErrorName;
                return ChgTranslateName_ContentRet;
            }

            // 4.Replace原始訊息.
            string strErrName_Rep = "";
            if (Strings.InStr(ErrorName, "[%", CompareMethod.Text) > 0)
            {
                // Replace[%%]
                var rmGen = System.Resources.ResourceManager.CreateFileBasedResourceManager(strGenFile, strResourcePath, null);
                string strKey, strKeyValue;
                int intStart, j, k, l;

                intStart = 1;
                j = 1;

                while (j != 0)
                {
                    j = Strings.InStr(intStart, ErrorName, "[%", CompareMethod.Text);
                    if (j == 0)
                    {
                        strErrName_Rep += Strings.Mid(ErrorName, intStart);
                    }
                    else
                    {
                        k = Strings.InStr(j + 2, ErrorName, "%]", CompareMethod.Text);
                        if (k == 0)
                        {
                            // 找不到對應的結束字元.
                            strErrName_Rep += Strings.Mid(ErrorName, intStart);
                            j = 0;
                        }
                        else
                        {
                            // 檢查是否有不對稱的情況.
                            l = Strings.InStr(j + 2, ErrorName, "[%", CompareMethod.Text);
                            if (l == 0 || l > k)
                            {
                                strErrName_Rep += Strings.Mid(ErrorName, intStart, j - intStart);
                                strKey = Strings.Mid(ErrorName, j + 2, k - j - 2);
                                // 將Key執行語系轉換
                                try
                                {
                                    strKeyValue = rmGen.GetString(strKey.ToUpper());
                                }
                                catch (Exception ex)
                                {
                                    strKeyValue = strKey;
                                }
                                if (string.IsNullOrEmpty(strKeyValue))
                                {
                                    strErrName_Rep += strKey;
                                }
                                else
                                {
                                    strErrName_Rep += strKeyValue;
                                }
                                // 下次截取字串的起始位置
                                intStart = k + 2;
                            }
                            else
                            {
                                // 不對稱,找到最內層的[%%]
                                int m;
                                // 在前面的條件下,一定找得到.
                                m = Strings.InStrRev(ErrorName, "[%", k, CompareMethod.Text);
                                // 擷出不轉換的字串.
                                strErrName_Rep += Strings.Mid(ErrorName, intStart, m - intStart);
                                strKey = Strings.Mid(ErrorName, m + 2, k - m - 2);
                                // 將Key執行語系轉換
                                try
                                {
                                    strKeyValue = rmGen.GetString(strKey.ToUpper());
                                }
                                catch (Exception ex)
                                {
                                    strKeyValue = strKey;
                                }
                                if (string.IsNullOrEmpty(strKeyValue))
                                {
                                    strErrName_Rep += strKey;
                                }
                                else
                                {
                                    strErrName_Rep += strKeyValue;
                                }
                                // 下次截取字串的起始位置
                                intStart = k + 2;
                            }
                        }
                    }
                }

                rmGen = null;
            }

            // 5.Final Message.
            string strFinalMsg;
            // 原始訊息
            if (string.IsNullOrEmpty(strErrName_Rep))
            {
                strFinalMsg = ErrorName;
            }
            else
            {
                strFinalMsg = strErrName_Rep;
            }

            ChgTranslateName_ContentRet = strFinalMsg;
            return ChgTranslateName_ContentRet;


        }

        ~clsAutoRunLibrary()
        {

            if (objSetting != null)
                objSetting = null;

        }

        /// <summary>
        /// 向資料庫取得使用TipTop時的ERP整合設定資訊。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        public void funGetERPSetting(string pERPName)
        {
            // Gary Lu 20120614:ERP整合設定統一由此函數取得
            StringReader tmpStringReader; // 將字串轉換成可讀入DataSet的物件
            string strERPSettingTableName;
            string InXml, OutXml, strIdentity, strParameter, XmlData, XmlSchema; // 呼叫WS的字串參數
            var XmlDoc = new XmlDocument();
            try
            {
                var dsERPSetting_TP = new DataSet();

                // 組InXml
                string argSendTime = Conversions.ToString(DateTime.Now);
                strIdentity = CombineXMLIdentity(modWIN.gComputerName, modWIN.gUserNo, argSendTime);
                string argvalue_name = "erpname";
                string argname = "ERPName";
                string argtype = "String";
                string argdesc = "";
                strParameter = CombineXMLParameter(argvalue_name, argname, argtype, pERPName, argdesc);
                InXml = CombineXMLRequest(strIdentity, strParameter);

                // 呼叫Web服務執行
                OutXml = modAutoRunLibrary.InvokeSrv("wsSYS.LoadERPSetting", InXml);

                // 解讀Web服務的執行結果
                XmlDoc.LoadXml(OutXml);

                if (chkExecutionSuccess(XmlDoc))
                {

                    // 讀取取出資料表的名稱
                    strERPSettingTableName = XmlDoc.GetElementsByTagName("returnvalue").Item(0).SelectNodes("loaderpsetting").Item(0).SelectNodes("name").Item(0).InnerXml;

                    // 取出Schema,dataset讀取Schema可防止Null Field及DateTime的問題

                    XmlSchema = XmlDoc.DocumentElement.GetElementsByTagName("loaderpsetting").Item(0).SelectNodes("schema").Item(0).InnerXml;
                    if (!string.IsNullOrEmpty(XmlSchema))
                    {
                        // 將XML讀入String Reader object中,因為Dataset讀入XML時必須透過String Reader物件
                        tmpStringReader = new StringReader(XmlSchema);
                        dsERPSetting_TP.ReadXmlSchema(tmpStringReader);
                        tmpStringReader.Close();
                    }

                    // 取出Data
                    XmlData = XmlDoc.DocumentElement.GetElementsByTagName("loaderpsetting").Item(0).SelectNodes("value").Item(0).InnerXml;
                    if (!string.IsNullOrEmpty(XmlData))
                    {
                        tmpStringReader = new StringReader(XmlData);
                        dsERPSetting_TP.ReadXml(tmpStringReader, XmlReadMode.InferSchema);
                        tmpStringReader.Close();
                    }

                    if (dsERPSetting_TP.Tables[strERPSettingTableName].Rows.Count > 0)
                    {
                        gERPUser = dsERPSetting_TP.Tables[strERPSettingTableName].Rows[0]["ERP_USER"].ToString();
                        gERPPassword = dsERPSetting_TP.Tables[strERPSettingTableName].Rows[0]["ERP_PWD"].ToString();
                        gERPWSURL = dsERPSetting_TP.Tables[strERPSettingTableName].Rows[0]["ERP_WSURL"].ToString();
                        gERPOraganization = dsERPSetting_TP.Tables[strERPSettingTableName].Rows[0]["ERP_ORG"].ToString();
                        gERPLanguage = dsERPSetting_TP.Tables[strERPSettingTableName].Rows[0]["ERP_LANG"].ToString();
                        gERPVersion = dsERPSetting_TP.Tables[strERPSettingTableName].Rows[0]["ERP_VERSION"].ToString();
                    }
                    else
                    {
                        throw new Exception("[%ERPWSURL%] not found!");
                    }
                }
                else
                {
                    throw new Exception("[%ERPWSURL%] not found!");
                }
            }

            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 取得ERP整合的設定資料
        /// </summary>
        /// <param name="ERPName"></param>
        /// <param name="pTable"></param>
        /// <returns></returns>
        private bool GetERPSetting(ref DataTable pTable, string pERPName = defString, int pEAIType = 0)
        {

            bool blnResult = false;
            var XmlDoc = new XmlDocument();
            var dsTemp = new DataSet();

            try
            {

                // 組InXml
                string argSendTime = Conversions.ToString(DateTime.Now);
                strIdentity = CombineXMLIdentity(modWIN.gComputerName, modWIN.gUserNo, argSendTime);
                strParameter = "";
                if ((pERPName ?? "") != defString)
                {
                    string argvalue_name = "erpname";
                    string argname = "ERPName";
                    string argtype = "String";
                    string argdesc = "";
                    strParameter += CombineXMLParameter(argvalue_name, argname, argtype, pERPName, argdesc);
                }
                if (pEAIType != 0)
                {
                    string argstrAdditional = CombineAddXML_Condition("EAI_Type = " + pEAIType);
                    strParameter += CombineXMLAdditional(argstrAdditional);
                }



                InXml = CombineXMLRequest(strIdentity, strParameter);

                // 呼叫Web服務執行
                OutXml = modAutoRunLibrary.InvokeSrv("wsSYS.LoadERPSetting", InXml);

                // 解讀Web服務的執行結果
                XmlDoc.LoadXml(OutXml);

                if (chkExecutionSuccess(XmlDoc))
                {

                    XmlSchema = XmlDoc.DocumentElement.GetElementsByTagName("loaderpsetting").Item(0).SelectNodes("schema").Item(0).InnerXml;

                    if (!string.IsNullOrEmpty(XmlSchema))
                    {
                        // 將XML讀入String Reader object中,因為Dataset讀入XML時必須透過String Reader物件
                        tmpStringReader = new StringReader(XmlSchema);
                        dsTemp.ReadXmlSchema(tmpStringReader);
                        tmpStringReader.Close();
                    }

                    XmlData = XmlDoc.DocumentElement.GetElementsByTagName("loaderpsetting").Item(0).SelectNodes("value").Item(0).InnerXml;

                    if (!string.IsNullOrEmpty(XmlData))
                    {
                        tmpStringReader = new StringReader(XmlData);
                        dsTemp.ReadXml(tmpStringReader, XmlReadMode.InferSchema);
                        tmpStringReader.Close();
                    }

                    if (dsTemp.Tables.Count > 0 && dsTemp.Tables[0].Rows.Count > 0)
                    {
                        pTable = dsTemp.Tables[0].Copy();
                        blnResult = true;
                    }
                    else
                    {
                        throw new Exception("[%GetERPSetting%] not found!");
                    }

                    dtERPSetting = dsTemp.Tables[0];
                    var row = dtERPSetting.Rows[0];

                    ERP_EntID = row["ERP_ENTID"].ToString();
                    ERP_Site = row["ERP_ORG"].ToString();
                    ERP_URL = row["ERP_WSURL"].ToString();
                }


                else
                {
                    throw new Exception("[%GetERPSetting%] not found!");
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                XmlDoc = null;
                dsTemp = null;
            }

            return blnResult;

        }

        #region ProcessAbout

        private int[] GetProcessID(string Str_ProcessName)
        {
            int[] GetProcessIDRet = default(int[]);
            int[] IntArray;
            int i;
            Process[] allRelationalProcs = Process.GetProcessesByName(Str_ProcessName);
            i = 0;
            IntArray = new int[1];

            foreach (var thisProcess in allRelationalProcs)
            {
                try
                {
                    Array.Resize(ref IntArray, i + 1);
                    IntArray[i] = thisProcess.Id;
                    i += 1;
                }
                catch (Exception ex)
                {
                    // MessageBox.Show(ex.GetBaseException.ToString, "GetProcessID Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                }
            }

            GetProcessIDRet = IntArray;
            return GetProcessIDRet;

        }

        private int[] GetNewPID(int[] OldPID, int[] AllPID)
        {
            int[] GetNewPIDRet = default(int[]);
            int i, j, k;
            int[] IntArray;
            j = 0;
            IntArray = new int[1];

            var loopTo = Information.UBound(AllPID);
            for (i = 0; i <= loopTo; i++)
            {
                k = Array.IndexOf(OldPID, AllPID[i]);
                if (k == -1)
                {
                    Array.Resize(ref IntArray, j + 1);
                    IntArray[j] = AllPID[i];
                    j += 1;
                }
            }
            GetNewPIDRet = IntArray;
            return GetNewPIDRet;

        }

        private bool KillProcess(int Str_ProcessID)
        {
            try
            {
                var Process = System.Diagnostics.Process.GetProcessById(Str_ProcessID);

                if (Conversions.ToBoolean(!Process.CloseMainWindow()))
                {
                    Process.Kill();
                }
            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.GetBaseException.ToString, "Close Process Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            }

            return default(Boolean);

        }

        #endregion

        private void LoadGroupBasis(ref DataSet dsGroup)
        {
            // 讀取使用者群組主檔
            var strGroupBasis = default(string);

            // 先判斷是否dataset中已有equipmenttype之datatable,若有,需先remove否則會有錯誤
            if (!(dsGroup.Tables[strGroupBasis] == null))
            {
                dsGroup.Tables.Remove(strGroupBasis);
            }

            // 組InXml的字串
            string argSendTime = Conversions.ToString(DateTime.Now);
            strIdentity = CombineXMLIdentity(modWIN.gComputerName, modWIN.gUserNo, argSendTime);
            // 加上IssueState要求取出所有資料
            string argvalue_name = "issuestate";
            string argname = "issuestate";
            string argtype = "Integer";
            string argvalue = defInteger.ToString();
            string argdesc = "";
            strParameter = CombineXMLParameter(argvalue_name, argname, argtype, argvalue, argdesc);
            int modAutoRundefTmp = defInteger;
            modAutoRundefTmp = Conversions.ToInteger(argvalue);
            InXml = CombineXMLRequest(strIdentity, strParameter);

            try
            {
                // OutXml = wsUSR.LoadGroupBasis(InXml)
                OutXml = modAutoRunLibrary.InvokeSrv("wsUSR.LoadGroupBasis", InXml);

                // 利用XmlDoc物件處理ReturnValue 
                XmlDoc.LoadXml(OutXml);

                if (chkExecutionSuccess(XmlDoc))
                {
                    strGroupBasis = XmlDoc.GetElementsByTagName("returnvalue").Item(0).SelectNodes("loadgroupbasis").Item(0).SelectNodes("name").Item(0).InnerXml;
                    // 取出Schema,dataset讀取Schema可防止Null Field及DateTime的問題

                    XmlSchema = XmlDoc.DocumentElement.GetElementsByTagName("loadgroupbasis").Item(0).SelectNodes("schema").Item(0).InnerXml;
                    if (!string.IsNullOrEmpty(XmlSchema))
                    {
                        // 將XML讀入String Reader object中,因為Dataset讀入XML時必須透過String Reader物件
                        tmpStringReader = new StringReader(XmlSchema);
                        dsGroup.ReadXmlSchema(tmpStringReader);
                        tmpStringReader.Close();
                    }
                    // 取出Data
                    XmlData = XmlDoc.DocumentElement.GetElementsByTagName("loadgroupbasis").Item(0).SelectNodes("value").Item(0).InnerXml;
                    if (!string.IsNullOrEmpty(XmlData))
                    {
                        tmpStringReader = new StringReader(XmlData);
                        dsGroup.ReadXml(tmpStringReader);
                        tmpStringReader.Close();
                    }
                    else
                    {
                        throw new Exception(GetExceptionSysMsg(XmlDoc));
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        public string CombineRequestXMLbyCDO(ref object SCI_Object, string pService, string pUserNo, string pServiceName, string pCalledID = defString, string pRequestKey = defString)
        {
            string CombineRequestXMLbyCDORet = default(string);

            DataRow[] drERPSetting;
            string strFilter = "";

            do
            {
                try
                {
                    strFilter = "ERP_Name ='" + pService + "' ";
                    if ((pCalledID ?? "") != defString && string.IsNullOrEmpty(pCalledID) == false)
                        strFilter += " And CalledID ='" + pCalledID + "' ";
                    // 取得服務資訊
                    drERPSetting = dtERPSetting.Select(strFilter);
                    if (drERPSetting == null)
                        break;
                    if (drERPSetting.Length != 1)
                        break;
                    if ((pCalledID ?? "") == defString)
                    {
                        pCalledID = drERPSetting[0]["CalledID"].ToString();
                    }

                    // 2017-03-17, Joe, 加Parameter for E10
                    (SCI_Object as iMESCIO.SCI.ERP.ERPRequestBase).enterprise_no = drERPSetting[0]["ERP_ENTID"].ToString();
                    (SCI_Object as iMESCIO.SCI.ERP.ERPRequestBase).site_no = drERPSetting[0]["ERP_ORG"].ToString();

                    // 轉XML
                    string RequestHead = "<host prod=\"" + drERPSetting[0]["MESProductName"].ToString() + "\" ver=\"" + drERPSetting[0]["MESProductVer"].ToString() + "\" ip=\"" + drERPSetting[0]["MESIP"].ToString() + "\" id=\"" + drERPSetting[0]["MESID"].ToString() + "\" acct=\"" + drERPSetting[0]["ERP_USER"].ToString() + "\" lang=\"" + drERPSetting[0]["ERP_LANG"].ToString() + "\" timestamp=\"" + Strings.Format(DateTime.Now, "yyyyMMddHHmmssfff") + "\"/>";
                    RequestHead += "<service prod=\"" + drERPSetting[0]["CalledProductName"].ToString() + "\" name=\"" + pServiceName + "\" ip=\"" + drERPSetting[0]["CalledIP"].ToString() + "\" id=\"" + drERPSetting[0]["CalledID"].ToString() + "\"/>";
                    string RequestDataKey = "<datakey><key name=\"EntId\">" + drERPSetting[0]["ERP_ENTID"].ToString() + "</key><key name=\"CompanyId\">" + drERPSetting[0]["ERP_ORG"].ToString() + "</key></datakey>";
                    string RequestXML_Body = Conversions.ToString((SCI_Object as iMESCIO.SCI.ERP.ERPResponseBase).ParseXml());
                    pRequestKey = modAutoRunLibrary.GetRequestKey(RequestHead);
                    string RequestHeader = "<request key=\"" + pRequestKey + "\" type=\"sync\">" + RequestHead + RequestDataKey + "<payload>" + RequestXML_Body + "</payload></request>";
                    // CDO to XML
                    CombineRequestXMLbyCDORet = RequestHeader;
                }

                catch (Exception ex)
                {
                    throw;
                }
            }
            while (false);
            return CombineRequestXMLbyCDORet;

        }

        /// <summary>
        /// EAI 檢核編碼(MD5)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        // Private Function GetRequestKey(ByVal input As String) As String

        // Const ID As String = "28682266" ' 鼎新統編

        // Dim key As String = ""
        // Dim md5Hasher As MD5 = MD5.Create() ' 建立MD5物件

        // Try

        // input += ID

        // ' 將input轉換成MD5，並且以Bytes傳回，由於ComputeHash只接受Bytes型別參數，所以要先轉型別為Bytes
        // Dim data As Byte() = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(input))

        // ' 建立StringBuilder物件
        // Dim sb As New StringBuilder()

        // ' 將Bytes轉型別為String，並且以16進位存放
        // For i As Integer = 0 To data.Length - 1
        // sb.Append(data(i).ToString("x2"))
        // Next i

        // key = sb.ToString

        // Catch ex As Exception
        // Throw
        // Finally
        // md5Hasher = Nothing
        // End Try

        // Return key

        // End Function

        #endregion

        #region 客製JobName


        #endregion

        #region 測試用JobName

        // Add by Martin 2009/03/03 for testing the Url get by using gMESWebServiceHost and GetAppSettings mathod.
        // Private Function funTestFuncton(Optional ByVal colParameters As Collection = Nothing) As String
        // Dim cnnTemp As OleDb.OleDbConnection
        // Dim drTemp As OleDb.OleDbDataReader
        // Dim wsSPC As New wsSPC.wsSPC
        // wsSPC.Url = LocalizeWebService(wsSPC.Url.ToString)
        // wsSPC.EnableDecompression = True

        // strIdentity = CombineXMLIdentity("Autorun", "Autorun", Now)
        // InXml = CombineXMLRequest(strIdentity, strParameter)

        // Try
        // '開始執行
        // OutXml = wsSPC.LoadOQCForm(InXml)
        // 'MsgBox(OutXml, , "Test Function Response!") '2012/08/21,Even,由於該msgbox造成錯誤(程式不允許auto 回復為msgbox形式)

        // funTestFuncton = "success"

        // Catch e1 As Exception
        // funTestFuncton = "fail;" & e1.Message
        // '發生錯誤時丟回本身的Function Name及系統錯誤訊息
        // 'Throw New Exception("clsAutoRunLibary.funTestFuncton: " & e1.Message)

        // '2013/02/05, Hank, Send Email
        // colParameters.Add(funTestFuncton, "EmailBody")
        // SendJobFailEmail(colParameters)

        // Finally
        // Call objSetting.CloseConnection(cnnTemp)
        // If Not wsSPC Is Nothing Then wsSPC.Dispose()
        // End Try

        // End Function

        #endregion

    }
}