예제 #1
0
파일: CommPro.cs 프로젝트: Crazye/VPRR
        /// <summary>
        ///     Import sap file common procdure for form and service
        /// </summary>
        public static bool importSap(string folderName,bool isService, RichTextBox rtx = null)
        {
            bool isDone = true;
            string dataLine;
            string w_articulo = null;
            int? w_piezas = null;
            int w_signo = 1;
            DateTime dateTime = DateTime.Now;

            //Get current base directory
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

            LogHelper logHelper = new LogHelper();
            if (!isService && rtx != null)
            {
                logHelper = new LogHelper(rtx);
            }

            FileTimeInfo fiFileNewest;                                                //New arrive fileInfo;

            dt_instock_pec = CommFac.CrtInstockPec();                                 //Create instock_pec temporary table schema
            dt_Inpendiente_pec = CommFac.CrtInpendPec();                              //Create Inpendiente_pec temporary table schema
            try
            {
                dt_artic = CommFac.CrtArtic();                                        //Create material code table artic schema
            }
            catch(Exception)
            {
                logHelper.LogError("No material_code.xml file.", null);
                isDone = false;
                return isDone;
            }

            //Check artic material_code table if is null
            if (dt_artic.Rows.Count == 0) { logHelper.LogError("No Material code data in material_code.xml file.", null); }

            logHelper.LogMessage("------------------------------------------------------------------------------------------------------");
            logHelper.LogWarning("Importing SAP files arrived into our system......");

            //dateDia = DateTime.Parse(dateTime.ToString()).ToString("dd-MM-yy");//Get the current date format to 'yyyyMMdd'

            //Check if exist SAP files in the folder,if not exist,process stop;
            //The fileNames is without suffix.
            string[] fileNames = CommFac.GetFiles(folderName, "IF817BC1.*.dat");
            //string[] fileNames = CommFac.GetFiles(folderName, ConfigAppSettings.GetValue("SAP_File_Pattern"));
            //folder Files exists
            if (fileNames.Length > 0)
            {
                //Check the new arrived file,and archived it to importSAP\ archive folder with datetime suffix, Order by the last modify date
                fiFileNewest = CommFac.GetLatestFileTimeInfo(folderName, ".dat");

                //Check the new arrived file filename, the file num(IF817BC1.*.dat),If * is not numberic, process terminated;
                string[] arrFileNum = fiFileNewest.FileName.Split('_');

                string strHeader = arrFileNum[0].Split('.')[0]; //
                string strExt = arrFileNum[1].Split('.')[1];

                //if (!CommFac.isNumberic(fiFileNewest.FileName.Split('.')[1]))
                //{
                //    //New arrived SAP file is not available, delete it
                //    logHelper.LogError("The new arrived SAP file" + fiFileNewest.FileName + " is not an available file.", null);
                //    //Delete
                //    //System.IO.File.Delete(fiFileNewest.FileFullName);
                //    logHelper.LogError("The new arrived SAP file" + fiFileNewest.FileName + " has been deleted.", null);
                //    isDone = false;
                //}

                if (strHeader != "IF817BC1" || strExt != "dat"){

                    //New arrived SAP file is not available, delete it
                    logHelper.LogError("The new arrived SAP file" + fiFileNewest.FileName + " is not an available file.", null);
                    //Delete
                    System.IO.File.Delete(fiFileNewest.FileFullName);
                    logHelper.LogError("The new arrived SAP file" + fiFileNewest.FileName + " has been deleted.", null);
                    isDone = false;
                    return isDone;
                }

                //Get the newest IF817BC1.*.dat file in importSAP\archive\ folder and read it to dataTable;
                //Read the newest IF817BC1.*.dat file to temporary DataTable ystock_pentes;
                dt_ystock_pentes = CommFac.GetIF817DT(fiFileNewest.FileFullName);

                #region ////////////////////////////////Email Notification/////////////////////////////////////////////

                //Check if new arrived SAP file is missing(or empty)
                //when both the email address and the email notification setting ‘on’ are set in the configuration file.

                if (dt_ystock_pentes.Rows.Count == 0)
                {
                    logHelper.LogWarning("Check " + fiFileNewest.FileName + " SAP file is missing.");
                    //Notice on
                    if (ConfigAppSettings.GetValue("Email_Notification").Trim().ToLower() == "on")
                    {
                        //Send Email
                        List<string> mailToList = CommFac.GetMailToList(mailToAddrs);

                        //Mail body contents
                        StringBuilder sbMailBodyContext = new StringBuilder();
                        sbMailBodyContext.AppendLine("To whom it may concern,\n");
                        sbMailBodyContext.AppendLine("You are receiving this email because there is no valid IF817BC1.*.dat in place.");
                        sbMailBodyContext.AppendLine("Please contact the technical support.\n");
                        sbMailBodyContext.AppendLine("VPRR generated email");
                        string strEnv = ConfigAppSettings.GetValue("Env").ToUpper();
                        if (strEnv == "PROD")
                        {
                            strEnv = "";
                        }
                        else
                        {
                            strEnv += " - ";
                        }
                        CommFac.DeliveryMail(Smtp_ServerName, Int32.Parse(Smtp_PortNum), Smtp_UserName, Smtp_PassWord, Mail_From, Mail_FromAlias
                            , mailToList, strEnv + "SAP real stock flat file missing notification", sbMailBodyContext.ToString(), null, boolEnv);

                        logHelper.LogWarning("Missing SAP file, notification Email has been sent!");
                        logHelper.LogError("", null);
                        isDone = false;
                        return isDone;
                    }
                    //Notice off
                    else
                    {
                        logHelper.LogWarning("Check " + fiFileNewest.FileName + " SAP file is missing.");
                        logHelper.LogError("", null);
                        isDone = false;
                        return isDone;
                    }
                }

                #endregion

                //Create \archive\yyyyMMdd\ folder

                if (!System.IO.Directory.Exists(Environment.CurrentDirectory + Path_ImportSAP_Archive + DateTime.Now.ToString("yyyyMMdd"))){
                    System.IO.Directory.CreateDirectory(Environment.CurrentDirectory + Path_ImportSAP_Archive + DateTime.Now.ToString("yyyyMMdd"));
                }

                //Archived SAP file with datetime suffix.
                if (System.IO.File.Exists(Environment.CurrentDirectory + Path_ImportSAP_Archive + DateTime.Now.ToString("yyyyMMdd") + @"\" + fiFileNewest.FileName)){
                    System.IO.File.Delete(Environment.CurrentDirectory + Path_ImportSAP_Archive + DateTime.Now.ToString("yyyyMMdd") + @"\" + fiFileNewest.FileName);
                }
                //Copy the new arrived file to \archive folder
                System.IO.File.Move(fiFileNewest.FileFullName, Environment.CurrentDirectory + Path_ImportSAP_Archive + DateTime.Now.ToString("yyyyMMdd") + @"\" + fiFileNewest.FileName);
                //Display log info
                logHelper.LogMessage("The new arrived SAP file has been moved to archive folder");

                //foreach the files in importSAP\RCV folder, check the if the file is an available file,if not available,delete it.
                foreach (string fileName in fileNames)
                {
                    //Delete the remaining files
                    System.IO.File.Delete(Environment.CurrentDirectory + Path_ImportSAP + fileName + ".dat");

                }

                //Start checking the dataline in SAP files(The records in dt_ystock_pentes temporary datatable)
                logHelper.LogWarning("Checking " + fiFileNewest.FileName + " SAP file datalines......");   //Start checking the last IF817BC1.*.dat file

                #region Check the first line and last line in ystock_pentes temporary table (BGOFM/EDOFM in SAP file records)

                logHelper.LogWarning("Checking the First 'BGOFM' and 'EDOFM' lines of SAP file...... ");

                //Check the first line
                dataLine = dt_ystock_pentes.Rows[0]["LINEA"].ToString();

                //Check the first line start with 'BGOFM'or not
                if (dataLine.Substring(0, 5) == "BGOFM")
                {
                    //logHelper.LogMessage("Check first line start with 'BGOFM' Success!", MethodBase.GetCurrentMethod().DeclaringType);
                }
                else
                {
                    logHelper.LogError("Check first line start with 'BGOFM' Fail!", null);
                    isDone = false;
                    return isDone;
                }

                //Check the first line contains more than one 'BGOFM' characters
                if (CommFac.SubstringCount(dataLine, "BGOFM") > 1)
                {
                    logHelper.LogError("Check first line contains more than one 'BGOFM' characters, Fail!", null);
                    isDone = false;
                    return isDone;
                }

                //Check last line of the file start with 'EDOFM'
                dataLine = dt_ystock_pentes.Rows[dt_ystock_pentes.Rows.Count - 1]["LINEA"].ToString();
                if (dataLine.Substring(0, 5) == "EDOFM")
                {
                    //logHelper.LogMessage("Check last line start with 'EDOFM' Success!", MethodBase.GetCurrentMethod().DeclaringType);
                }
                else
                {
                    logHelper.LogError("Check last line start with 'EDOFM' Fail!", null);
                    isDone = false;
                    return isDone;
                }

                //Check the last line if contains more than one 'BGOFM' characters
                if (CommFac.SubstringCount(dataLine, "EDOFM") > 1)
                {
                    logHelper.LogError("Check first line contains more than one 'EDOFM' characters, Fail!",  null);
                    isDone = false;
                    return isDone;
                }

                //Check if the oreden field value of 'EDOFM' == dt_ystock_pentes records count
                int id = Convert.ToInt32(dt_ystock_pentes.Rows[dt_ystock_pentes.Rows.Count - 1]["ORDEN"].ToString());
                if (id == dt_ystock_pentes.Rows.Count)
                {
                    //logHelper.LogMessage("Check the last line 'EDOFM' id,Success", MethodBase.GetCurrentMethod().DeclaringType);
                }
                else
                {
                    logHelper.LogError("Check the last line 'EDOFM' id, Fail",  null);
                    isDone = false;
                    return isDone;
                }

                //Check the first line and last line(except the first 6 characters 'EDOFM ')
                string dataLineFirst = dt_ystock_pentes.Rows[0]["LINEA"].ToString().Substring(6).Trim();
                string dataLineLast = dt_ystock_pentes.Rows[dt_ystock_pentes.Rows.Count - 1]["LINEA"].ToString().Substring(6).Trim();

                if (dataLineFirst.Equals(dataLineLast))
                {
                    // logHelper.LogMessage("Check the first line and last line,Success!", MethodBase.GetCurrentMethod().DeclaringType);
                }
                else
                {
                    logHelper.LogError("Check the first line and last line,Fail!",  null);
                    isDone = false;
                    return isDone;
                }

                #endregion

                #region manipulate the records in ystock_pentes temporary table(SAP File records)

                logHelper.LogWarning("Manipulating the records in SAP file...... ");
                foreach (DataRow dr in dt_ystock_pentes.Rows)
                {
                    //Check if the line start with 'STCKW'
                    dataLine = dr["LINEA"].ToString().Substring(0, 5);
                    if (dataLine == "STCKW")
                    {
                        //logHelper.LogMessage("Check the line start with 'STCKW',success", MethodBase.GetCurrentMethod().DeclaringType);

                        w_articulo = dr["LINEA"].ToString().Substring(11, 18).Trim();//AW3000/10

                    }

                    //Check line start with 'STCKS'
                    if (dataLine == "STCKS")
                    {
                        //if this line contains 'SERV'
                        if (CommFac.SubstringCount(dr["LINEA"].ToString(), "SERV") > 0)
                        {

                            //string str1 = dr["LINEA"].ToString().Substring(16, 18);
                            //Check Substring(16,18)== w_articulo  ->> HTB3520G/12
                            if (dr["LINEA"].ToString().Substring(16, 18).Trim() == w_articulo)
                            {
                                //logHelper.LogMessage("Check LINEA 17-35 characters == " + w_articulo + " Success!", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check LINEA 17-35 characters == " + w_articulo + " Fail!", null);
                                isDone = false;
                                return isDone;
                            }

                            //Get int w_piezas   ->> STCKS FR52 SERV HTD3250/12         00000000002
                            w_piezas = int.Parse(dr["LINEA"].ToString().Substring(35, 11));

                            //To be checking the next line if is 'DELTS', and then not add this record.
                            //GoTo 'DELTS' line and add 'DELTS' row into table.
                            int idxRow = dt_ystock_pentes.Rows.IndexOf(dr);
                            if (dt_ystock_pentes.Rows[idxRow + 1]["LINEA"].ToString().Substring(0, 5) == "DELTS")
                            {
                                goto singStr;
                            }
                            //Insert data into instock_pec or inpendiente_pec table
                            //Check w_piezas value
                            if (w_piezas > 0)
                            {
                                //Add row into instock_pec table
                                dt_instock_pec.Rows.Add(new object[] { w_articulo, w_piezas });
                            }
                            else
                            {
                                //Add row into inpendiente_pec table
                                dt_Inpendiente_pec.Rows.Add(new object[] { w_articulo, w_piezas * -1 });
                            }
                        }
                    }

                singStr:

                    //Check the line start with 'DELTS'
                    if (dataLine == "DELTS")
                    {
                        //if the line contains 'SERV'
                        if (CommFac.SubstringCount(dr["LINEA"].ToString(), "SERV") > 0)
                        {
                            //Check w_piezas value is Null
                            if (w_piezas == null)
                            {
                                logHelper.LogError("w_piezas'value is null,process stoped", null);
                                isDone = false;
                                return isDone;
                            }
                            //Check w_articulo characters
                            if (dr["LINEA"].ToString().Substring(16, 18).Trim() == w_articulo)
                            {
                                //logHelper.LogMessage("Character w_articulo checked success!", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Characer w_articulo checking fail,process stoped", null);
                                isDone = false;
                                return isDone;
                            }

                            //Get int w_signo
                            if (dr["LINEA"].ToString().Substring(65, 1) == "+")
                            {
                                w_signo = 1;
                            }
                            else
                            {
                                w_signo = -1;
                            }

                            //Get w_piezas value
                            //VJ - 2           '
                            w_piezas = w_piezas + int.Parse(dr["LINEA"].ToString().Substring(67, 11)) * w_signo;

                            //Check w_piezas value
                            if (w_piezas > 0)
                            {
                                //Add row into instock_pec table
                                dt_instock_pec.Rows.Add(new object[] { w_articulo, w_piezas });
                            }
                            else
                            {
                                //Add row into inpendiente_pec table
                                dt_Inpendiente_pec.Rows.Add(new object[] { w_articulo, w_piezas * -1 });
                            }

                        }
                    }//end of delts;
                }//end foreach;

                #endregion

                #region Get vprr_pec table

                //On this section, Select instock_pec&inpendent_pec table with artic table,
                //In order to get common materials both exist in instock_pec and artic, inpendent_pec and artic table.
                //Then insert the common materials records in instock_eci into vprr_pec table. inpendent_pec into vprr_pec table.
                #region instock_pec&artic

                //Get the common records in artic and instock_pec table
                //where instock_pec.SAP_MATERIAL_CODE = artic.SAP_MATERIAL_CODE

                //temp table for instock_pec and artic table
                DataTable dt_instockArtic = new DataTable("instockArtic");

                DataColumn dc = new DataColumn("SAP_MATERIAL_CODE", typeof(string));
                dt_instockArtic.Columns.Add(dc);
                dc = new DataColumn("REAL_STOCK_QUANTITY", typeof(long));
                dt_instockArtic.Columns.Add(dc);
                //artic columns
                dc = new DataColumn("EAN_CODE", typeof(string));
                dt_instockArtic.Columns.Add(dc);
                //dc = new DataColumn("SAP_MATERIAL_CODE", typeof(string));
                //dt_instockArtic.Columns.Add(dc);

                //Linq select artic and instock_pec table,output dt_instockArtic table(r_stock)

                var query1 = from dt1 in dt_instock_pec.AsEnumerable()//查询
                             from dt2 in dt_artic.AsEnumerable()

                             where dt1.Field<string>("SAP_MATERIAL_CODE").Trim() == dt2.Field<string>("SAP_MATERIAL_CODE").Trim() //条件
                             select new
                             {
                                 SAP_MATERIAL_CODE = dt1.Field<string>("SAP_MATERIAL_CODE"),
                                 REAL_STOCK_QUANTITY = dt1.Field<long>("REAL_STOCK_QUANTITY"),
                                 //INTERNAL_MATERIAL_CODE = dt2.Field<string>("INTERNAL_MATERIAL_CODE"),
                                 EAN_CODE = dt2.Field<string>("EAN_CODE")

                             };

                query1.ToList().ForEach(x =>
                    dt_instockArtic.Rows.Add(new object[] { x.SAP_MATERIAL_CODE, x.REAL_STOCK_QUANTITY, x.EAN_CODE }));

                //insert common records in artic and instock_pec table  into vprr_pec
                //Create vprr_pec table schema
                dt_vprrpec = CommFac.CrtVprrPec();

                try
                {
                    foreach (DataRow dr in dt_instockArtic.Rows)
                    {
                        dt_vprrpec.Rows.Add(new object[] { dr["EAN_CODE"], 1, dr["REAL_STOCK_QUANTITY"], 0 });

                    }
                }
                catch
                {
                    logHelper.LogError("Add rows into vprr_pec temp table error.", null);
                    isDone = false;
                    return isDone;
                }

                #endregion

                #region inpendent_pec&artic
                //Output r_pedidoss data
                //inpendent_pec columns
                DataTable dt_inpedArtic = new DataTable("inpedArtic");
                dc = new DataColumn("SAP_MATERIAL_CODE", typeof(string));
                dt_inpedArtic.Columns.Add(dc);
                dc = new DataColumn("OPEN_ORDER_QUANTITY", typeof(long));
                dt_inpedArtic.Columns.Add(dc);
                //artic columns
                //dc = new DataColumn("INTERNAL_MATERIAL_CODE", typeof(string));
                //dt_inpedArtic.Columns.Add(dc);
                dc = new DataColumn("EAN_CODE", typeof(string));
                dt_inpedArtic.Columns.Add(dc);

                //Linq select artic and inpendent_pec table,output dt_inpedArtic table(c_pedidos)

                var query2 = from dt1 in dt_Inpendiente_pec.AsEnumerable()//查询
                             from dt2 in dt_artic.AsEnumerable()

                             where dt1.Field<string>("SAP_MATERIAL_CODE").Trim() == dt2.Field<string>("SAP_MATERIAL_CODE").Trim() //条件
                             select new
                             {
                                 SAP_MATERIAL_CODE = dt1.Field<string>("SAP_MATERIAL_CODE"),
                                 OPEN_ORDER_QUANTITY = dt1.Field<long>("OPEN_ORDER_QUANTITY"),
                                 //INTERNAL_MATERIAL_CODE = dt2.Field<string>("INTERNAL_MATERIAL_CODE"),
                                 EAN_CODE = dt2.Field<string>("EAN_CODE")

                             };

                query2.ToList().ForEach(x =>
                    dt_inpedArtic.Rows.Add(new object[] { x.SAP_MATERIAL_CODE, x.OPEN_ORDER_QUANTITY, x.EAN_CODE }));

                try
                {
                    //insert common records in artic and inpend_pec table into vprr_pec
                    foreach (DataRow dr in dt_inpedArtic.Rows)
                    {

                        dt_vprrpec.Rows.Add(new object[] { dr["EAN_CODE"], 1, 0, dr["OPEN_ORDER_QUANTITY"] });

                    }
                }
                catch
                {
                    logHelper.LogError("Add rows into vprr_pec temp table error.", null);
                    isDone = false;
                    return isDone;
                }

                #endregion

                //Finished get the vprr_pec table;

                #endregion

                //this.timerCheckSAPFiles.Enabled = false; //Stop timer for checking SAP files.
                //logHelper.LogWarning("Start Outputting SND file..................", MethodBase.GetCurrentMethod().DeclaringType);

                //System.Threading.Thread.Sleep(60 * 1000);  //Sleep thread for 1 minute.
                //this.btnOutPutSND.PerformClick();
                //this.timerCheckECIFiles.Start();//Start checking files from ECI files.
            }
            //File not exist or missing
            else
            {
                //Send no detecting Sap file email
                if (ConfigAppSettings.GetValue("Email_Notification").Trim().ToLower() == "on")
                {
                    logHelper.LogError("SAP file not found, notification mail has been sent.", null);
                    List<string> mailToList = CommFac.GetMailToList(mailToAddrs);

                    //Mail body contents
                    StringBuilder sbMailBodyContext = new StringBuilder();
                    sbMailBodyContext.AppendLine("To whom it may concern,\n");
                    sbMailBodyContext.AppendLine("You are receiving this email because there is no valid IF817BC1.*.dat in place.");
                    sbMailBodyContext.AppendLine("Please contact the technical support.\n");
                    sbMailBodyContext.AppendLine("VPRR generated email");
                    string strEnv = ConfigAppSettings.GetValue("Env").ToUpper();
                    if (strEnv == "PROD")
                    {
                        strEnv = "";
                    }
                    else
                    {
                        strEnv += " - ";
                    }
                    CommFac.DeliveryMail(Smtp_ServerName, Int32.Parse(Smtp_PortNum), Smtp_UserName, Smtp_PassWord, Mail_From, Mail_FromAlias
                        , mailToList, strEnv + "SAP real stock flat file missing notification", sbMailBodyContext.ToString(), null, boolEnv);
                    isDone = false;
                    return isDone;
                }
                else
                {
                    logHelper.LogError("No SAP files detect.", null);
                    isDone = false;
                    return isDone;
                }
            }

            return isDone;
        }
예제 #2
0
파일: CommPro.cs 프로젝트: Crazye/VPRR
        public static string WakeUpTimeSAP = ConfigAppSettings.GetValue("Time_ImportSAP"); //Get wakeup time of receiving SAP files.

        #endregion Fields

        #region Methods

        /// <summary>
        ///     Import eci file common procdure for form and service
        /// </summary>
        public static bool importECI(string folderName,bool isService, RichTextBox rtx = null)
        {
            bool isDone = true;

            //Clear temporary datatable.
            dt_artic = null;
            dt_instock_eci = null;
            dt_stock_eci = null;
            dt_instock_pec = null;
            dt_Inpendiente_pec = null;
            dt_ystock_pentes = null;
            dt_vprrpec = null;
            dt_yvprr = null;
            dt_stockeciArtic = null;
            dt_vprrstockArtic = null;

            LogHelper logHelper = new LogHelper();
            if (!isService && rtx != null){ logHelper = new LogHelper(rtx);}

            DateTime dateTime = DateTime.Now;
            CultureInfo cultureInfo;
            DateTimeStyles dateTimeStyles;
            cultureInfo = CultureInfo.CreateSpecificCulture("");
            dateTimeStyles = DateTimeStyles.None;
            FileTimeInfo fiFileNewest;         //New arrive fileInfo;

            //Get current base directory
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

            try
            {
                ///Information receive from ECI
                ///Get last file and input to temporary table instock_eci
                #region //////////////////////////////////////Detect ECI files and archive//////////////////////////////////

                logHelper.LogMessage("------------------------------------------------------------------------------------------------------");
                logHelper.LogWarning("Importing ECI files arrived to our local system......");

                //Check the ImportECI folder if RCV_INVRPT96_*.DAT files exist,if not exist the files, process terminated.
                //string[] fileNames = CommFac.GetFiles(folderName, "RCV_INVRPT96_*.dat");
                string[] fileNames = CommFac.GetFiles(folderName, ConfigAppSettings.GetValue("ECI_File_Pattern"));
                //folder file exist
                if (fileNames.Length > 0)
                {

                    //foreach \RCV\RCV_INVRPT96_*.dat files in the folder; Check which file is the new arrive. Order by the last modify date
                    fiFileNewest = CommFac.GetLatestFileTimeInfo(folderName,".dat");

                    //Check the new arrived file filename, the file num(RCV_INVRPT96_*.dat),If * is not numberic, process terminated;
                    //string[] arrFileNum = fiFileNewest.FileName.Split('_');

                    //if (!CommFac.isNumberic(arrFileNum[2].Split('.')[0])) // Get filename * value;
                    //{
                    //    //New arrived ECI file is not available,delete
                    //    logHelper.LogError("The new arrived ECI file" + fiFileNewest.FileName + " is not an available file.", null);
                    //    //Delete
                    //    System.IO.File.Delete(fiFileNewest.FileFullName);
                    //    logHelper.LogError("The new arrived ECI file" + fiFileNewest.FileName + " has been deleted.", null);
                    //    isDone = false;
                    //    return isDone;
                    //}

                    //Read the new arrived RCV file dataline to datatable dt_instock_eci, for dataline checking.
                    dt_instock_eci = CommFac.GetRCVDT(fiFileNewest.FileFullName);

                    #region //////////////////////////////////////Email Notification//////////////////////////////////////////////////

                    //Check if the new arrived ECI file missed(or empty), take an Email notificaton
                    //when both the email address and the email notification setting ‘on’ are set in the configuration file.
                    if (dt_instock_eci.Rows.Count == 0)
                    {
                        logHelper.LogWarning("Check " + fiFileNewest.FileName + " ECI file is missing.");
                        //Notice on
                        if (ConfigAppSettings.GetValue("Email_Notification").Trim().ToLower() == "on")
                        {
                            List<string> mailToList = CommFac.GetMailToList(mailToAddrs);

                            //Mail body contents
                            StringBuilder sbMailBodyContext = new StringBuilder();
                            sbMailBodyContext.AppendLine("To whom it may concern,\n");
                            //sbMailBodyContext.AppendLine("You are receiving this email because there is no valid RCV_INVRPT96_*.dat in place.");
                            sbMailBodyContext.AppendFormat("You are receiving this email because there is no valid {0} in place.",ConfigAppSettings.GetValue("ECI_File_Pattern"));
                            sbMailBodyContext.AppendLine("Please contact the technical support.\n");
                            sbMailBodyContext.AppendLine("VPRR generated email");
                            //Get environment string
                            string strEnv = ConfigAppSettings.GetValue("Env").ToUpper();
                            /*If environment is 'PROD',
                             the mail subject no display PROD string title.*/
                            if (strEnv == "PROD")
                            {
                                strEnv = "";
                            }
                            else
                            {
                                strEnv += " - ";
                            }
                            //Begin delivery notification email.
                            CommFac.DeliveryMail(Smtp_ServerName, Int32.Parse(Smtp_PortNum), Smtp_UserName, Smtp_PassWord, Mail_From, Mail_FromAlias
                                , mailToList, strEnv + "ECI actual stock file missing notification", sbMailBodyContext.ToString(), null, boolEnv);

                            logHelper.LogWarning("ECI actual stock flat file not found, notification Email has been sent!");
                            logHelper.LogError("",null);
                            isDone = false;
                            return isDone;

                        }
                        //Notice off
                        else
                        {
                            logHelper.LogWarning("Check " + fiFileNewest.FileName + " ECI file is missing.");
                            logHelper.LogError("", null);
                            isDone = false;
                            return isDone;
                        }
                    }

                    #endregion

                    //Create archive folder \archive\yyyyMMdd\

                    if (!System.IO.Directory.Exists(Environment.CurrentDirectory + Path_ImportECI_Archive + DateTime.Now.ToString("yyyyMMdd"))){
                        System.IO.Directory.CreateDirectory(Environment.CurrentDirectory + Path_ImportECI_Archive + DateTime.Now.ToString("yyyyMMdd"));
                    }

                    //If the ECI file already in archive folder, delete it.
                    if (System.IO.File.Exists(Environment.CurrentDirectory + Path_ImportECI_Archive + DateTime.Now.ToString("yyyyMMdd") + @"\" + fiFileNewest.FileName)){
                        System.IO.File.Delete(Environment.CurrentDirectory + Path_ImportECI_Archive + DateTime.Now.ToString("yyyyMMdd") + @"\" + fiFileNewest.FileName);
                    }
                    //Move the new arrived file to \archive\INVRPT96.RCV.dataDia(archived the new arrived file)
                    System.IO.File.Move(fiFileNewest.FileFullName, Environment.CurrentDirectory + Path_ImportECI_Archive + DateTime.Now.ToString("yyyyMMdd") + @"\" + fiFileNewest.FileName);

                    logHelper.LogMessage("The new arrived file " + fiFileNewest.FileName + " has been moved to ECI archive folder");

                    //foreach \importECI\RCV_INVRPT96_*.dat files in the folder and move it importECI\archive\RCV_INVRPT96_*.dat.datedia
                    //filename without .dat suffix
                    foreach (string fileName in fileNames) {    //Delete the remaining files
                        System.IO.File.Delete(folderName + fileName + ".dat");
                    }
                }
                else  //No file found in \ImportECI\RCV\RCV_INVRPT96_*.DAT
                {
                    if (ConfigAppSettings.GetValue("Email_Notification").Trim().ToLower() == "on")
                    {
                        //Send no detecting eci file email
                        logHelper.LogError("ECI file not found, notification mail has been sent.", null);
                        List<string> mailToList = CommFac.GetMailToList(mailToAddrs);

                        //Mail body contents
                        StringBuilder sbMailBodyContext = new StringBuilder();
                        sbMailBodyContext.AppendLine("To whom it may concern,\n");
                        //sbMailBodyContext.AppendLine("You are receiving this email because there is no valid RCV_INVRPT96_*.dat in place.");
                        sbMailBodyContext.AppendFormat("You are receiving this email because there is no valid {0} in place.", ConfigAppSettings.GetValue("ECI_File_Pattern"));
                        sbMailBodyContext.AppendLine("Please contact the technical support.\n");
                        sbMailBodyContext.AppendLine("VPRR generated email");
                        //Get environment string
                        string strEnv = ConfigAppSettings.GetValue("Env").ToUpper();
                        /*If environment is 'PROD',
                             the mail subject no display PROD string title.*/
                        if (strEnv == "PROD")
                        {
                            strEnv = "";
                        }
                        else
                        {
                            strEnv += " - ";
                        }
                        //Begin delivery email.
                        CommFac.DeliveryMail(Smtp_ServerName, Int32.Parse(Smtp_PortNum), Smtp_UserName, Smtp_PassWord, Mail_From, Mail_FromAlias
                            , mailToList, strEnv + "ECI actual stock file missing notification", sbMailBodyContext.ToString(), null, boolEnv);
                        isDone = false;
                        return isDone;
                    }
                    else
                    {
                        logHelper.LogError("No ECI files detect.", null);
                        isDone = false;
                        return isDone;
                    }
                }

                #endregion

                #region /////////////////////////////Check dataline in instock_eci and import into stock_eci///////////////////
                //logHelper.LogWarning("Start checking "+ fiFileNewest.FileName +" ECI file datalines......", MethodBase.GetCurrentMethod().DeclaringType);

                //Start checking the first five lines in instock_eci table

                for (int rowNum = 0; rowNum <= 4; rowNum++)
                {
                    switch (rowNum)
                    {
                        case 0:
                            #region Checking the first line

                            logHelper.LogWarning("Checking first line of ECI file......");

                            //Check the first line if start with "CABEC"
                            string strLineType = dt_instock_eci.Rows[rowNum]["LINE_TYPE"].ToString();

                            if (strLineType == "CABEC")
                            {
                                // logHelper.LogMessage("First five characters with 'CABEC',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("First five characters are not 'CABEC',FAIL.", null);
                                isDone = false;
                            }

                            //Check REST_LINE(1-13) if equals to ('8422416999990','8422416888881','8422416000016')
                            string dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(0, 13);

                            if (dataLine == "8422416999990" || dataLine == "8422416888881" || dataLine == "8422416000016")
                            {

                                // logHelper.LogMessage("Check the REST_LINE 1-13 characters are correct,SUCCESS,", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check the REST_LINE 1-13 characters are not correct,FAIL.", null);
                                isDone = false;
                            }

                            //Check REST_LINE(50-56) characters if are 'INVRPT'
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(49, 6);

                            if (dataLine == "INVRPT")
                            {
                                // logHelper.LogMessage("Check REST_LINE 'INVRPT',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check REST_LINE 'INVRPT',FAIL", null);
                                isDone = false;
                            }

                            //Check REST_LINE 56-59 characters is '96A'
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(55, 3);

                            if (dataLine == "96A")
                            {
                                //logHelper.LogMessage("Check REST_LINE '96A',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {

                                logHelper.LogError("Check REST_LINE '96A',FAIL", null);
                                isDone = false;
                            }

                            //Check REST_LINE 'EAN004'
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(58);

                            if (dataLine == "EAN004")
                            {
                                //logHelper.LogMessage("Check REST_LINE 'EAN004',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {

                                logHelper.LogError("Check REST_LINE 'EAN004',FAIL", null);
                                isDone = false;
                            }

                            #endregion
                            break;
                        case 1:
                            #region Checking the second line

                            logHelper.LogWarning("Checking second line of ECI file......");
                            dataLine = dt_instock_eci.Rows[rowNum]["LINE_TYPE"].ToString().Substring(0, 5);

                            //Check LINE_STYLE field
                            //Check if the line start with 'INFST'
                            if (dataLine == "INFST")
                            {
                                //logHelper.LogMessage("Check start with 'INFST',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check start with 'INFST',FAIL", null);
                                isDone = false;
                            }

                            //Check the REST_LINE field

                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(0, 2);

                            if (dataLine == "78")
                            {
                                //logHelper.LogMessage("Check REST_LINE '78',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check REST_LINE '78',FAIL", null);
                                isDone = false;
                            }
                            //Check the REST_LINE '9  '
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(20, 3);

                            if (dataLine == "9  ")
                            {
                                //logHelper.LogMessage("Check REST_LINE '9  ',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check REST_LINE '9  ',FAIL",  null);
                                isDone = false;
                            }
                            //Check datatime section if a available datetime format
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(23, 8);

                            bool flag = DateTime.TryParseExact(dataLine, "yyyymmdd", null, dateTimeStyles, out dateTime);

                            if (flag)
                            {
                                // logHelper.LogMessage("The DATETIME checking " + dataLine + " SUCCESS,", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {

                                logHelper.LogError("The DATETIME checking " + dataLine + " FAIL",  null);
                                isDone = false;
                            }

                            #endregion
                            break;
                        case 2:
                            #region Checking the third line

                            logHelper.LogWarning("Checking third line of ECI file......");
                            dataLine = dt_instock_eci.Rows[rowNum]["LINE_TYPE"].ToString().Substring(0, 5);

                            //Check if the third line start with 'INTER'
                            if (dataLine == "INTER")
                            {
                                // logHelper.LogMessage("Check if the line start with 'INTER',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check if the line start with 'INTER',FAIL", null);
                                isDone = false;
                            }

                            //Check the third line 'MS'
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(0, 2);

                            if (dataLine == "MS")
                            {
                                //logHelper.LogMessage("Check REST_LINE 'MS',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check REST_LINE 'MS',FAIL",  null);
                                isDone = false;
                            }
                            //Check the dataline contains '8422416000016', '8422416000023'
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(3, 13);

                            if (dataLine == "8422416000016" || dataLine == "8422416000023")
                            {
                                //logHelper.LogMessage("Check REST_LINE contains '8422416000016' or '8422416000023',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check REST_LINE contains '8422416000016' or '8422416000023',FAIL",  null);
                                isDone = false;
                            }
                            //Check the third line '9'
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(26, 1);

                            if (dataLine == "9")
                            {
                                //logHelper.LogMessage("Check REST_LINE '9',SUCCESS,", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check REST_LINE '9',FAIL",  null);
                                isDone = false;
                            }

                            #endregion
                            break;
                        case 3:
                            #region Checking the forth line

                            logHelper.LogWarning("Checking forth line of ECI file......");
                            //Start checking the forth line start with 'INTER'
                            dataLine = dt_instock_eci.Rows[rowNum]["LINE_TYPE"].ToString().Substring(0, 5);

                            if (dataLine == "INTER")
                            {
                                //logHelper.LogMessage("Check the forth line start with 'INTER',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check the forth line start with 'INTER',FAIL",  null);
                                isDone = false;
                            }

                            //Checking the line 'MR'
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(0, 2);

                            if (dataLine == "MR")
                            {
                                //logHelper.LogMessage("Check REST_LINE 'MR',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check REST_LINE 'MR',FAIL",  null);
                                isDone = false;
                            }

                            //Check second section contains '8713387560631'
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(3, 13);

                            if (dataLine == "8713387560631")
                            {
                                //logHelper.LogMessage("Check REST_LINE(0,2)=='8713387560631',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check REST_LINE(0,2)=='8713387560631',FAIL", null);
                                isDone = false;
                            }

                            //Check the third line '9'
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(26, 1);

                            if (dataLine == "9")
                            {
                                //logHelper.LogMessage("Check REST_LINE '9',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check REST_LINE '9',FAIL", null);
                                isDone = false;
                            }

                            #endregion
                            break;
                        case 4:
                            #region Checking the fifth line

                            logHelper.LogWarning("Checking fifth line of ECI file...... ");
                            //Check the fifth line start with 'INTER'
                            dataLine = dt_instock_eci.Rows[rowNum]["LINE_TYPE"].ToString().Substring(0, 5);

                            if (dataLine == "INTER")
                            {
                                //logHelper.LogMessage("Check the fifth line start with 'INTER',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check fifth line start with 'INTER',FAIL", null);
                                isDone = false;
                            }

                            //Check the line GY
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(0, 2);

                            if (dataLine == "GY")
                            {
                                //logHelper.LogMessage("Check REST_LINE 'GY',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check REST_LINE 'GY',FAIL", null);
                                isDone = false;
                            }

                            //Check the second section contains '8713387560631'
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(3, 13);

                            if (dataLine == "8713387560631")
                            {
                                //logHelper.LogMessage("Check REST_LINE '8713387560631',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check REST_LINE '8713387560631',FAIL",  null);
                                isDone = false;
                            }
                            //Check the third section contains 9
                            dataLine = dt_instock_eci.Rows[rowNum]["REST_LINE"].ToString().Substring(26, 1);

                            if (dataLine == "9")
                            {
                                // logHelper.LogMessage("Check REST_LINE '9',SUCCESS", MethodBase.GetCurrentMethod().DeclaringType);
                            }
                            else
                            {
                                logHelper.LogError("Check REST_LINE '9',FAIL", null);
                                isDone = false;
                            }

                            #endregion
                            break;
                    }
                }

                #region Check Remainning lines of instock_eci table datalines and insert into stock_eci table

                string w_ean = null;
                int w_piezas = 0;

                dt_stock_eci = CommFac.CrtStockECI();//Create table stock_eci schema for store ECI file datalines

                logHelper.LogWarning("Checking remainning lines of ECI file...... ");
                //Begin loop remain lines of ECI file , except the last line;
                foreach (DataRow row in dt_instock_eci.Rows)
                {
                    //If the line five characters start with 'LIENA'
                    if (row["LINE_TYPE"].ToString().Substring(0, 5) == "LINEA")
                    {
                        w_ean = row["REST_LINE"].ToString().Substring(8, 14);
                    }

                    //If the line five characters start with 'CANTI'
                    if (row["LINE_TYPE"].ToString().Substring(0, 5) == "CANTI")
                    {
                        w_piezas = int.Parse(row["REST_LINE"].ToString().Substring(0, 13)) + (int.Parse(row["REST_LINE"].ToString().Substring(14, 3)) / 1000);

                        dt_stock_eci.Rows.Add(new object[] { '1', w_ean, w_piezas }); //Add row into instock_eci;

                    }
                }

                //Output instock_eci table finished.

                #region Check final line of instock_eci table

                string finalLine = dt_instock_eci.Rows[dt_instock_eci.Rows.Count - 1]["LINE_TYPE"].ToString();

                //Check if the records start with 'FINAL';
                if (finalLine == "FINAL")
                {
                    logHelper.LogMessage("Check instock_eci final line start with 'FINAL',SUCCESS");
                }
                else
                {
                    logHelper.LogError("Check instock_eci final line start with 'FINAL',FAIL", null);
                    isDone = false;
                }

                //Check the final line REST_LINE characters value  ==  w_referencia(the first dataline(36-50 characters));
                string w_referencia = dt_instock_eci.Rows[0]["REST_LINE"].ToString().Substring(35, 14);

                finalLine = dt_instock_eci.Rows[dt_instock_eci.Rows.Count - 1]["REST_LINE"].ToString();

                if (finalLine.Substring(0) == w_referencia)
                {
                    logHelper.LogMessage("Check first line equals final line SUCCESS!");
                }
                else
                {
                    logHelper.LogError("Check first line equals final line FAIL",  null);
                    isDone = false;
                }

                #endregion

                //this.timerCheckECIFiles.Enabled = false; //Stop timer tick for Checking ECI files.
                //logHelper.LogWarning("Start checking files from SAP..............", MethodBase.GetCurrentMethod().DeclaringType);
                //this.timerCheckSAPFiles.Start();//Start timer tick for checking SAP files.

                #endregion
                #endregion
            }
            catch (Exception ex)
            {
                //Get the Exception for all importECI procedure ,record it to Logger Manager log files.
                logHelper.LogError("Exceptions occurred,Please find errors in log file", ex);
                isDone = false;
            }

            return isDone;
        }
예제 #3
0
파일: CommPro.cs 프로젝트: Crazye/VPRR
        /// <summary>
        ///     Import output file common procdure for form and service
        /// </summary>
        public static bool output(bool isService, RichTextBox rtx = null)
        {
            bool isDone = true;

            LogHelper logHelper = new LogHelper();
            if (!isService && rtx != null)
            {
                logHelper = new LogHelper(rtx);
            }
            dt_yvprr = CommFac.CrtYvprr(); //Create temporary yvprr table schema

            //Get current base directory
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

            logHelper.LogMessage("------------------------------------------------------------------------------------------------------");
            //logHelper.LogWarning("Start output SND file for ECI customer......", MethodBase.GetCurrentMethod().DeclaringType);

            #region select stock_eci and artic table(where stock_eci.MATERIAL_EAN_CODE = artic.EAN_CODE)

            dt_stockeciArtic = new DataTable("stock_eciArtic");

            if (dt_stock_eci != null)
            {
                //Stock_eci rows
                DataColumn dc_stockeciArtic = new DataColumn("MATERIAL_EAN_CODE", typeof(string));
                dt_stockeciArtic.Columns.Add(dc_stockeciArtic);
                dc_stockeciArtic = new DataColumn("STOCK_QUANTITY", typeof(long));
                dt_stockeciArtic.Columns.Add(dc_stockeciArtic);
                //artic rows
                dc_stockeciArtic = new DataColumn("SAP_MATERIAL_CODE", typeof(string));
                dt_stockeciArtic.Columns.Add(dc_stockeciArtic);
                dc_stockeciArtic = new DataColumn("EAN_CODE", typeof(string));
                dt_stockeciArtic.Columns.Add(dc_stockeciArtic);

                try
                {
                    var q3 = from dt1 in dt_stock_eci.AsEnumerable() //linq search
                             from dt2 in dt_artic.AsEnumerable()

                             where dt1.Field<string>("MATERIAL_EAN_CODE").Trim() == dt2.Field<string>("EAN_CODE")//condition
                             select new
                             {
                                 //stock_eci columns data
                                 MATERIAL_EAN_CODE = dt1.Field<string>("MATERIAL_EAN_CODE"),
                                 STOCK_QUANTITY = dt1.Field<long>("STOCK_QUANTITY"),
                                 //artic columns data
                                 SAP_MATERIAL_CODE = dt2.Field<string>("SAP_MATERIAL_CODE"),
                                 EAN_CODE = dt2.Field<string>("EAN_CODE"),

                             };

                    q3.ToList().ForEach(x =>
                        dt_stockeciArtic.Rows.Add(new object[] { x.MATERIAL_EAN_CODE, x.STOCK_QUANTITY, x.SAP_MATERIAL_CODE, x.EAN_CODE }));

                }
                catch
                {
                    logHelper.LogError("Add rows into stockeciArtic temp table error.", null);
                    isDone = false;
                }

            }
            else
            {
                logHelper.LogError("stock_eci datatable is null,Please importECI file first",  null);
                isDone = false;
            }

            #endregion

            //On this section, Select records both in RCV_INVPRT96_*.dat and IF817BC1_*.dat file.
            #region select vprr_pec and stock_eci with artic table

            dt_vprrstockArtic = new DataTable("vprrstockArtic");

            //materialEanCode column
            DataColumn dc_materialEanCode = new DataColumn("MATERIAL_EAN_CODE", typeof(string));
            dt_vprrstockArtic.Columns.Add(dc_materialEanCode);

            //Sap_material_code column
            DataColumn dc_sapMaterialCode = new DataColumn("SAP_MATERIAL_CODE", typeof(string));
            dt_vprrstockArtic.Columns.Add(dc_sapMaterialCode);

            //Real_stock_quantity column
            DataColumn dc_realStockQty = new DataColumn("REAL_STOCK_QUANTITY", typeof(int));
            dt_vprrstockArtic.Columns.Add(dc_realStockQty);

            //stockquantity column
            DataColumn dc_stockQty = new DataColumn("STOCK_QUANTITY", typeof(int));
            dt_vprrstockArtic.Columns.Add(dc_stockQty);

            //Open_orden_quantity column
            DataColumn dc_openOrdenQty = new DataColumn("OPEN_ORDER_QUANTITY", typeof(int));
            dt_vprrstockArtic.Columns.Add(dc_openOrdenQty);

            //Ean_code column
            DataColumn dc_eanCode = new DataColumn("EAN_CODE", typeof(string));
            dt_vprrstockArtic.Columns.Add(dc_eanCode);

            try
            {
                var query_forYvprr = from dt1 in dt_vprrpec.AsEnumerable() //linq search
                                     from dt2 in dt_stockeciArtic.AsEnumerable()

                                     where dt1.Field<string>("EAN_CODE") == dt2.Field<string>("EAN_CODE") //condition
                                     select new
                                     {
                                         //Columns data
                                         MATERIAL_EAN_CODE = dt2.Field<string>("MATERIAL_EAN_CODE"),
                                         SAP_MATERIAL_CODE = dt2.Field<string>("SAP_MATERIAL_CODE"),
                                         REAL_STOCK_QUANTITY = dt1.Field<int>("REAL_STOCK_QUANTITY"),
                                         STOCK_QUANTITY = dt2.Field<long>("STOCK_QUANTITY"),
                                         OPEN_ORDER_QUANTITY = dt1.Field<int>("OPEN_ORDER_QUANTITY"),
                                         EAN_CODE = dt1.Field<string>("EAN_CODE")
                                     };

                query_forYvprr.ToList().ForEach(x =>
                    dt_vprrstockArtic.Rows.Add(new object[] {x.MATERIAL_EAN_CODE, x.SAP_MATERIAL_CODE, x.REAL_STOCK_QUANTITY, x.STOCK_QUANTITY, x.OPEN_ORDER_QUANTITY,
                    x.EAN_CODE}));

            }
            catch
            {
                logHelper.LogError("Add rows into vprrstockArtic temp table error.", null);
                isDone = false;
            }

            #endregion
            //Insert the common materials code records data into yvprr table for output SND file.
            #region loop through all recoreds in vprrstockArtic table and insert into yvprr table.

            int w_piezas = 0;
            object w_inter = 0;
            string w_signo = "2  ";
            int iLine = 1;

            try
            {
                foreach (DataRow drYvprr in dt_vprrstockArtic.Rows)
                {
                    //Get w_piezas
                    w_piezas = int.Parse(drYvprr["REAL_STOCK_QUANTITY"].ToString()) - int.Parse(drYvprr["OPEN_ORDER_QUANTITY"].ToString());

                    //Insert 'LINEA' data into yvprr.
                    DataRow dr = dt_yvprr.NewRow();
                    dr["REST_SEGMENT"] = "LINEA" + iLine.ToString().PadLeft(3, '0') + "     " + drYvprr["EAN_CODE"].ToString();
                    dt_yvprr.Rows.Add(dr);

                    //Insert 'CANTI' data into yvprr.
                    w_inter = drYvprr["STOCK_QUANTITY"].ToString();
                    w_piezas = w_piezas - int.Parse(w_inter.ToString());

                    if (w_piezas < 0)
                    {
                        w_signo = "1  ";
                    }
                    else
                    {
                        w_signo = "2  ";
                    }

                    //Insert 'CANTI' Lines;
                    if (w_piezas < 0)
                    {
                        string[] w_piezasArr = w_piezas.ToString().Split('-');
                        w_piezas = int.Parse(w_piezasArr[1]);
                    }

                    dr = dt_yvprr.NewRow();
                    dr["REST_SEGMENT"] = "CANTI                 " + w_piezas.ToString().PadLeft(13, '0') + ".000" + w_signo;
                    dt_yvprr.Rows.Add(dr);

                    iLine += 1;
                }

                //Final line;
                DataRow drFinal = dt_yvprr.NewRow();
                drFinal["REST_SEGMENT"] = "FINAL";
                dt_yvprr.Rows.Add(drFinal);
            }
            catch
            {
                logHelper.LogError("Add rows into yvprr temp table error.", null);
                isDone = false;
            }

            #endregion
            //Output SND flat file for ECI customer.
            #region To outPut&archive .SND File for ECI customer

            //Get file timeStamp
            DateTime dateTime = DateTime.Now;
            //dateDia = DateTime.Parse(dateTime.ToString()).ToString("dd-MM-yy");

            if (dt_yvprr.Rows.Count == 0)
            {
                logHelper.LogError("Please importECI file first",  null);
                isDone = false;
            }

            //Check if output file exist
            if (File.Exists(Environment.CurrentDirectory + Path_ExportECI + @"\INVRPT96_" + dateTime.ToString("dd-MM-yy") + ".SND"))
            {
                File.Delete(Environment.CurrentDirectory + Path_ExportECI + @"\INVRPT96_" + dateTime.ToString("dd-MM-yy") + ".SND");
            }

            FileStream fileStream = new FileStream(Environment.CurrentDirectory + Path_ExportECI + @"\INVRPT96_" + dateTime.ToString("dd-MM-yy") + ".SND", FileMode.OpenOrCreate, FileAccess.Write);

            try
            {
                using (StreamWriter streamWriter = new StreamWriter(fileStream))
                {
                    for (int iRow = 0; iRow < dt_yvprr.Rows.Count; iRow++)
                    {
                        streamWriter.WriteLine(dt_yvprr.Rows[iRow]["REST_SEGMENT"].ToString());
                    }
                }
            }
            catch
            {
                logHelper.LogError("No INVRPT96_SND.dat generated,process terminated.",  null);
                isDone = false;
            }
            logHelper.LogWarning("INVRPT96.SND file generated and output to \\exportECI\\ Successfully!");

            //Archive SND file

            //Create \archive\yyyyMMdd\ folder

            if (!System.IO.Directory.Exists(Environment.CurrentDirectory + Path_ExportECI_Archive + DateTime.Now.ToString("yyyyMMdd")))
            {
                System.IO.Directory.CreateDirectory(Environment.CurrentDirectory + Path_ExportECI_Archive + DateTime.Now.ToString("yyyyMMdd"));
            }

            string sourcePath = Environment.CurrentDirectory + Path_ExportECI + "INVRPT96_" + dateTime.ToString("dd-MM-yy") + ".SND";
            string targetPath = Environment.CurrentDirectory + Path_ExportECI_Archive + DateTime.Now.ToString("yyyyMMdd") + @"\";

            if (System.IO.File.Exists(targetPath + "INVRPT96.SND"))
            {
                System.IO.File.Delete(targetPath + "INVRPT96.SND");
            }

            //Copy INVRPT96_date.SND file to archive folder
            System.IO.File.Copy(sourcePath, targetPath + "INVRPT96.SND");

            //Move INVRPT96_date.SND file to FTP VPRR\OutBox\ECI\
            string strFTPOutBox = ConfigAppSettings.GetValue("PathFTP_ExportECI");//FTP Outbox
            if(System.IO.File.Exists(strFTPOutBox)){System.IO.File.Delete(strFTPOutBox + "INVRPT96_" + dateTime.ToString("dd-MM-yy") + ".SND");}
            if (System.IO.File.Exists(sourcePath))
            {
                System.IO.File.Move(sourcePath,strFTPOutBox + "INVRPT96_" + dateTime.ToString("dd-MM-yy") + ".SND");
            }

            //logHelper.LogWarning("Finished archiving INVRPT96_" + dateDia + ".SND to archive folder......", MethodBase.GetCurrentMethod().DeclaringType);
            logHelper.LogWarning("VPRR processed successful and terminated.");

            #endregion

            return isDone;
        }