Beispiel #1
0
        /// <summary>
        ///     Version Feb13-17
        ///     Execute method when timer is due
        ///     Must retreive etlTimer information to validate if service is active / running (busy)
        ///     Validate the following for each of the services:
        ///     1 - The service exist in the EtlTimer table.
        ///     2 - The service is active.
        ///     3 - The service is not currently busy running another thread.
        /// </summary>
        /// <param Object name="e"></param>False
        private void SchedularCallback(object e)
        {   //  Get etlTimer info. for this service
            syncRow = wtf.getImportControl(serviceId);
            //

            if (syncRow.IsActive)
            {
                if (syncRow.IsRunning)
                {   //  Ignore process if service is busy performing another thread
                    wtf.writeSyncLog(9, syncRow.MwEtlTimerId, 1, syncRow.ServiceName, "Sync service for " + syncRow.ServiceName + " not processed, is busy in other thread.");
                    //  this.WriteToFile("NAV Service Log - not processed, service is busy in other thread: {0}");
                }
                else
                {   //  Input Files services is performed here.
                    //  SyncControl();      /// Version 2.0
                    //  SyncControl(syncRow);   /// Version 3.0
                    if (syncRow.MwEtlTimerId == 17 || syncRow.MwEtlTimerId == 1 || syncRow.MwEtlTimerId == 2 || syncRow.MwEtlTimerId == 18)
                    {                              //  Input files comming from db tables
                        SyncControl_Disk(syncRow); /// Version 3.1
                    }
                    else
                    {                         //  Input files comming from windows folders
                        SyncControl(syncRow); /// Version 3.1
                    }
                }
            }
            else
            {   //  Ignore process when service is not active.
                wtf.writeSyncLog(9, syncRow.MwEtlTimerId, 1, syncRow.ServiceName, "Sync service for " + syncRow.ServiceName + " is not active");
                //  this.WriteToFile("NAV Service Log - not processed, service is inactive: {0}");
            }
            this.ScheduleService();
        }
Beispiel #2
0
        int serviceId = 0; // Convert.ToInt16(ConfigurationManager.AppSettings["ServiceID"]);
        ///
        //  EtlTimer sync = new EtlTimer();
        ///  **************************************************************************************
        ///  Replaced in Version 3.0
        ///  Perform Directory File search process when task time is due
        ///  Look for existing files in the new files folder
        ///  Same method is used in the WindowsService version....
        ///  --------------------------------------------------------------------------------------
        ///public void FileSearch(object e, EtlTimer sync)
        //{
        //    if (serviceId == 0)
        //    {
        //        //serviceId = Convert.ToInt16(ConfigurationManager.AppSettings["ServiceID"]); ;
        //        //sync = wtf.getImportControl(serviceId);
        //        serviceId = sync.MwEtlTimerId;
        //    }
        //    List<string> li = new List<string>();
        //    //
        //    wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, " > (GK FileSearch) Start Directory scanning. for " + sync.ServiceName + ".");
        //    //
        //    //li.Add(ConfigurationManager.AppSettings["NewFilesDirectory"].ToString());   //  C:\\AppData
        //    li.Add(sync.InputFileFolder);
        //    if (li.Count == 0)
        //    {
        //        wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, " > (GK FileSearch) No Folder to process. for " + sync.ServiceName);
        //    }
        //    foreach (string path in li)
        //    {
        //        if (File.Exists(path))
        //        {
        //            // This path is a file
        //            ProcessFile(path, sync);
        //        }
        //        else if (Directory.Exists(path))
        //        {
        //            // This path is a directory
        //            ProcessDirectory(path, sync);
        //        }
        //        else
        //        {
        //            //  Invalid File or Directory exit
        //            wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, "(GK FileSearch) <" + path + " > is not a valid file or directory.");
        //        }
        //    }
        //    /// *******************************************************************************
        //    /// Back to Service SchedularCallback Function
        //    /// When FileSearch is completed process flow return to Service1.SchedularCallback.
        //    /// -------------------------------------------------------------------------------
        //}

        ////  ************************************************************************
        ////  Process all files in the directory passed in, recurse on any directories
        ////  that are found, and process the files they contain.
        ////  ------------------------------------------------------------------------
        //public void ProcessDirectory(string targetDirectory, EtlTimer sync)
        //{
        //    ///
        //    string[] fileEntries = Directory.GetFiles(targetDirectory);
        //    foreach (string fileName in fileEntries)
        //    {
        //        ProcessFile(fileName, sync);
        //    }
        //    // Recurse into subdirectories of this directory.
        //    string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        //    foreach (string subdirectory in subdirectoryEntries)
        //        ProcessDirectory(subdirectory, sync);
        //}

        /// *****************************************************************************************
        /// Version 3.0
        /// General files process - Only Text valid Files are processed here:
        ///     (1) - Select files to process depending on file extension and/or file name.
        ///     (2) - Route process to the corresponding file types import process using delegates.
        ///     (3) - Unrecognized file types and Service reading errors are detected here.
        ///     (4) - Errors are logged in service log and reported through web services.
        ///
        ///     USE THIS SECTION TO ADD ALL FILE TYPES TO BE INCLUDED IN THE IMPORT PROCESS
        /// -----------------------------------------------------------------------------------------
        private void ProcessFile(string path, EtlTimer sync)
        {
            int dirLen = (ConfigurationManager.AppSettings["NewFilesDirectory"].ToString()).Length + 1;
            ///
            string extension = (Path.GetExtension(path)).ToString();
            string fileName  = Path.GetFileNameWithoutExtension(path);
            /// Initialize Error messages object basic information
            ServiceResponse errMsg = new ServiceResponse();

            errMsg.FileType   = "5";
            errMsg.FileName   = fileName + extension;
            errMsg.NISOrderId = "0";
            errMsg.Status     = "Not Processed";
            errMsg.Message    = string.Empty;
            try
            {
                /// *********************************************************************************
                /// Select files acceptable to be process, all other file types (extension) will not
                /// be processed (they stay in the newFiles folder) and an error message is generated
                /// to the WebServices.
                /// ---------------------------------------------------------------------------------
                if (extension == ".txt")
                {
                    /// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    ///     Process all txt files here, they must belong to WE or G&K
                    ///  ---------------------------------------------------------------------------------
                    DelTxt handler = null;
                    // Declare a class instance txt:
                    ImportProcedure_GK_PO.TextFiles.ImportProcess txt = new ImportProcedure_GK_PO.TextFiles.ImportProcess();
                    /// Declare an interface instance txtFile:
                    ITextFiles txtfile = (ITextFiles)txt;

                    if (fileName.Substring(0, 6) == "WE XML")
                    {   //  WE - XML Order Files
                        handler = txtfile.ProcessWEFiles;
                    }
                    else
                    {   // G&K Text files
                        handler = txtfile.ProcessGKFiles;
                    }
                    /// =========== >
                    ProcessTxt(path, fileName, handler, sync);
                    /// < ===========
                }
                else
                {   /// Unrecognized file type
                    errMsg.NISOrderId = fileName;
                    errMsg.Message    = "GK ProcessFile) File <" + fileName + extension + ">, unrecognized file type.";
                    wtf.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, errMsg.Message);
                    /// Move file to problem directory
                    icr.SaveProcessedFile(path, false, sync, "GK");
                }
            }
            catch (Exception fle)
            {
                int res = wtf.updImportControl(sync.MwEtlTimerId, 0);     //  set EtlTimer for this service to not Running (isRunning = false)
                errMsg.Message = "((GK_PO ProcessFile) txt reading error - File in " + errMsg.FileName + ". " + fle;
                wtf.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, errMsg.Message);
            }
        }
Beispiel #3
0
        /// <summary>
        ///     Version 3.0
        ///     Route process to the corresponding service ProcessFile Method depending on the
        ///     service id.
        ///     Control the start/end of each service,
        /// </summary>
        /// <param name="path"></param>
        /// <param name="sync"></param>
        private void ProcessFile(string path, EtlTimer sync)
        {
            int    res = wtf.updImportControl(serviceId, 1);  //  set EtlTimer for this service to InUse
            object e   = new object();

            //  =================================================================================
            switch (serviceId)
            {
            case 10:
                ImportProcedure_NIS.FileManagement FileNis = new ImportProcedure_NIS.FileManagement();
                FileNis.ProcessFile(path, sync);
                break;

            case 15:
                ImportProcedure_NBI.FileManagement FileNbiT = new ImportProcedure_NBI.FileManagement();
                FileNbiT.ProcessFile(path, sync);
                break;

            case 16:
                ImportProcedure_STK.FileManagement FileStkT = new ImportProcedure_STK.FileManagement();
                FileStkT.ProcessFile(path, sync);
                break;
            }
            res = wtf.updImportControl(serviceId, 0);     //  set EtlTimer for this service to Inactive
        }
Beispiel #4
0
        //private void WriteToFile(string text)
        //{
        //    string path = "C:\\ServiceLogNAVTest.txt";
        //    using (StreamWriter writer = new StreamWriter(path, true))
        //    {
        //        writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
        //        writer.Close();
        //    }
        //}


        /// <summary>   Version 2.0
        ///     Controls all windows services related with the import function.
        ///     Route the process flow to the corresponding service depending in the process id.
        /// </summary>
        //public void SyncControl()
        //{   //
        //    int res = wtf.updImportControl(serviceId, 1);     //  set EtlTimer for this service to InUse
        //    object e = new object();
        //    //  =================================================================================
        //    if (serviceId == 10)
        //    {
        //        ImportProcedure_NIS.FileManagement fileManagement = new ImportProcedure_NIS.FileManagement();
        //        fileManagement.FileSearch(e, syncRow);
        //    }
        //    else if (serviceId == 11)
        //    {
        //        ImportProcedure_GK_PO.FileManagement fileManagement = new ImportProcedure_GK_PO.FileManagement();
        //        fileManagement.FileSearch(e, syncRow);
        //    }
        //    else if (serviceId == 12)
        //    {
        //        ImportProcedure_ArrowFtp.FileManagement fileManagement = new ImportProcedure_ArrowFtp.FileManagement();
        //        fileManagement.FileSearch(e, syncRow);
        //    }
        //    else if (serviceId == 13)
        //    {
        //        ImportProcedure_NBI.FileManagement fileManagement = new ImportProcedure_NBI.FileManagement();
        //        fileManagement.FileSearch(e, syncRow);
        //    }
        //    else if (serviceId == 15)
        //    {   /// Nav NBI Import test option
        //        ImportProcedure_NBI.FileManagement fileManagement = new ImportProcedure_NBI.FileManagement();
        //        fileManagement.FileSearch(e, syncRow);
        //    }
        //    res = wtf.updImportControl(serviceId, 0);     //  set EtlTimer for this service to Inactive
        //  ================================================================================
        ///}

        /// ************************************************************************************
        /// Version 3.0 methods start here, they replace the SyncControl Method
        /// All import services share the same input (directory/files) access methods
        /// ------------------------------------------------------------------------------------
        public void SyncControl(EtlTimer sync)
        {
            List <string> li = new List <string>();

            //
            wtf.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, " > (FileSearch) Start Directory scanning. for " + sync.ServiceName + ".");
            //
            li.Add(sync.InputFileFolder);
            if (li.Count == 0)
            {
                wtf.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, " > (FileSearch) No Folder to process. for " + sync.ServiceName);
            }
            else
            {   //  Input files folder found
                foreach (string path in li)
                {
                    if (File.Exists(path))
                    {   // This path is a file
                        ProcessFile(path, sync);
                    }
                    else if (Directory.Exists(path))
                    {   // This path is a directory
                        ProcessDirectory(path, sync);
                    }
                    else
                    {   //  Invalid File or Directory exit
                        wtf.writeSyncLog(2, sync.MwEtlTimerId, 1, sync.ServiceName, "(FileSearch) <" + path + " > is not a valid file or directory.");
                    }
                }
            }
        }
Beispiel #5
0
        /// <summary>
        ///     Version 3.0
        ///     Process text files, text files are routed here the corresponding import process and
        ///     WebService depending on the Process method assigned through the delegate specified
        ///     in the handler parameter.
        ///     Does not apply to version 3.0 [After processing, the complete original file content is send to the webServices for
        ///     storage in OrderRaw table.]
        /// </summary>
        /// <param name="path">Incoming file complete path</param>
        /// <param name="tst">file name without extnsion</param>
        /// <param name="handler">Delegate that points to the corresponding process method</param>
        private void ProcessTxt(string path, string tst, DelTxt handler, EtlTimer sync)
        {
            bool ok = false;

            /// =============== >   Process file and WebService using sync method
            //bool processResult = handler(path, tst, sync);
            ok = handler(path, tst, sync);
            /// PERFORM getTextFileContent while waiting for 'processResult' response.
            /// /// DO NOT SAVE INPUT FILE AS RAW DATA IN THE MIDDLEWARE - Version 2.0 up
            /// ****************************************************************************************
            /// Call Web Service to transfer a copy of the processed file through RawData
            /// ----------------------------------------------------------------------------------------
            //  NO RAW DATA IS SEND TO THE MIDDLEWARE
            /// =========================================
            //   bool r = getTextFileContent(path, sync);
            //  =========================================
            /// DON't PERFORM THE FOLLOWING STEPS UNTIL 'processResult' IS COMPLETED
            //bool ok = processResult;
            /// Exit to final file process step.
            //if (ok)
            //{
            ///DAL.ImportControl.ImportControlRepository icr = new DAL.ImportControl.ImportControlRepository();
            wtf.SaveProcessedFile(path, ok, sync, "Arrow");
            //}
        }
Beispiel #6
0
        /// *****************************************************************************************
        /// General Tables process - Only Web/convert orders rows are processed here:
        ///     (1) - Select order type process depending on order type.
        ///     (2) - Route process to the corresponding order types import process using delegates.
        ///     (3) - Unrecognized data types and Service reading errors are detected here.
        ///     (4) - Errors are logged in service log and reported through web services.
        /// -----------------------------------------------------------------------------------------
        public void ProcessOrder(string order, EtlTimer sync)
        {
            /// Initialize Error messages object basic information
            string          OrdNumber = "";
            ServiceResponse errMsg    = new ServiceResponse();

            errMsg.FileType   = "1";
            errMsg.FileName   = "Catalog Design Request: " + order.ToString();
            errMsg.NISOrderId = "0";
            errMsg.Status     = "Not Processed";
            errMsg.Message    = string.Empty;
            try
            {
                /// *********************************************************************************
                /// Select files acceptable to be process, all other file types (extension) will not
                /// be processed (they stay in the newFiles folder) and an error message is generated
                /// to the WebServices.
                /// Only Catalog Web Order (1) row are processed by entry.
                /// ---------------------------------------------------------------------------------
                //  access catalog convert orders list
                if (sync.OrderType == 0)
                {   /// ======== >
                    DesignRequest designRequest = new DesignRequest();
                    designRequest = idr.getDesignRequest(order);
                    /// <=========
                    OrdNumber = designRequest.DesignId;
                    //
                    /// Instanciate NBI Tables methods delegate
                    Del handler = null;
                    // Declare a class instance:
                    ImportProcedure_DesignRequest.DesignRequestJson.ImportProcess table = new ImportProcedure_DesignRequest.DesignRequestJson.ImportProcess();
                    /// Declare an interface instance Table:
                    ImportProcedure_DesignRequest.DesignRequestJson.IDesignRequestTables designClass = (ImportProcedure_DesignRequest.DesignRequestJson.IDesignRequestTables)table;
                    /// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    /// Identify Catalog Web order table and route them to the corresponding import procedure
                    ///  ----------------------------------------------------------------------------
                    //  Catalog Web Order table process
                    handler = designClass.ProcessDesignRequestOrder;
                    //    /// =========== >
                    bool ok = false;
                    ok = handler(designRequest, order, sync);                 //  Process file and WebService
                    //
                    OrdNumber = (designRequest.DesignId).ToString();
                    //
                }
                else
                {   //  update error order - set imported on and import problem on
                    ikr.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, "Table reading error order header not found or no items in file, order " + OrdNumber);
                }
            }
            catch (Exception fle)
            {
                int res = ikr.updImportControl(sync.MwEtlTimerId, 0);     //  set EtlTimer for this service to not Running (isRunning = false)
                errMsg.Message = "(Catalog Design request Process) Table reading error - in order " + errMsg.FileName + ". " + fle;
                ikr.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, errMsg.Message);
            }
        }
Beispiel #7
0
        protected override void OnStart(string[] args)
        {
            //  this.WriteToFile("NAV Service Test started {0}");
            if (syncRow.MwEtlTimerId == 0)
            {
                syncRow = wtf.getImportControl(serviceId);
            }
            //string ret = wtf.writeSyncLog(1, serviceId, 1, syncRow.ServiceName, "==> Window service for: " + syncRow.ServiceName + " started ");
            string ret = wtf.writeSyncLog(1, syncRow.MwEtlTimerId, 1, syncRow.ServiceName, "==> Window service for: " + syncRow.ServiceName + " started ");

            this.ScheduleService();
        }
        /// *****************************************************************************************
        /// General files process - Only NIS XML valid Files are processed here:
        ///     (1) - Select orders to process depending on WasImported status.
        ///     (2) - Route process to the corresponding import process using delegates.
        ///     (3) - NIS table reading errors are detected here.
        ///     (4) - Errors are logged in service log and reported through web services.
        /// -----------------------------------------------------------------------------------------
        public void ProcessOrder(int order, EtlTimer sync)
        {
            /// Initialize Error messages object basic information
            ServiceResponse errMsg = new ServiceResponse();

            errMsg.FileType   = "1";
            errMsg.FileName   = "Order: " + order.ToString();
            errMsg.NISOrderId = "0";
            errMsg.Status     = "Not Processed";
            errMsg.Message    = string.Empty;
            try
            {
                /// *********************************************************************************
                /// Select files acceptable to be process, all other file types (extension) will not
                /// be processed (they stay in the newFiles folder) and an error message is generated
                /// to the WebServices.
                /// Only NIS (1) row are processed by entry.
                /// ---------------------------------------------------------------------------------
                NisTables NisOrder = new NisTables();
                NisOrder = Inr.getNisOrder(order);

                if (NisOrder != null && NisOrder.items != null)
                {
                    /// Instanciate NBI Tables methods delegate
                    Del handler = null;
                    // Declare a class instance xml:
                    ImportProcedure_NIS_V2.BuildJason.ImportProcess table = new ImportProcedure_NIS_V2.BuildJason.ImportProcess();
                    /// Declare an interface instance Table:
                    ImportProcedure_NIS_V2.BuildJason.INISTables orderClass = (ImportProcedure_NIS_V2.BuildJason.INISTables)table;
                    /// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    /// Route to the corresponding NIS import procedure
                    ///  ----------------------------------------------------------------------------
                    handler = orderClass.ProcessNisOrder;
                    bool ok = false;
                    ok = handler(NisOrder, order, sync);                  //  Process file and WebService
                }
                else
                {   //  update error order - set imported on and import problem on
                    int ret = Inr.updNisOrder(order, 0, 1, 0);
                    icr.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, "Table reading error order header or no items found, order " + order);
                }
            }
            catch (Exception fle)
            {
                int res = icr.updImportControl(sync.MwEtlTimerId, 0);     //  set EtlTimer for this service to not Running (isRunning = false)
                errMsg.Message = "(NIS ProcessFile) Table reading error - in order " + errMsg.FileName + ". " + fle;
                icr.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, errMsg.Message);
                int resp = Inr.updNisOrder(Convert.ToInt32(errMsg.FileName), 0, 1, 0);
            }
        }
        /// <summary>
        /// Get syncControlTable status for an specific type of table.
        ///     10 - NIS Imports
        ///     11 - NIB Imports
        ///     12 - Shipping address
        /// </summary>
        /// <param name="type">Service type code</param>
        /// <returns>Boolean  true if service is active and not busy</returns>
        public EtlTimer getImportControl(int type)
        {
            SqlDataReader dr = null;
            //Boolean active = false;
            EtlTimer row = new EtlTimer();

            try
            {
                System.Collections.Specialized.NameValueCollection args = new NameValueCollection();
                args.Add("@etlTaskId", type.ToString());
                //DBContext.DBAccess access = new DBContext.DBAccess();
                //
                dr = access.ExecuteReader("[MW_GetETLTaskTimer]", DBContext.DBAccess.DBConnection.SqlMainNew, args);
                //
                //EtlTimer row = new EtlTimer();
                //string serviceAvailability = "not active";
                while (dr != null && dr.Read())
                {
                    row.MwEtlTimerId        = (Int32)(dr["MwEtlTimerId"].ToString().Length > 0 ? Int32.Parse(dr["MwEtlTimerId"].ToString()) : 0);
                    row.Description         = dr["Description"].ToString().Length > 0 ? dr["Description"].ToString() : "";
                    row.ServiceName         = dr["ServiceName"].ToString().Length > 0 ? dr["ServiceName"].ToString() : "";
                    row.IsActive            = Convert.ToBoolean(dr["IsActive"]);
                    row.FrequencyInSecs     = (Int64)(dr["FrequencyInSecs"].ToString().Length > 0 ? Int64.Parse(dr["FrequencyInSecs"].ToString()) : 0);
                    row.IsRunning           = Convert.ToBoolean(dr["IsRunning"]);
                    row.DailyRunTime        = dr["DailyRunTime"].ToString().Length > 0 ? TimeSpan.Parse(dr["DailyRunTime"].ToString()) : TimeSpan.Zero;
                    row.LastRunDate         = dr["LastRunDate"].ToString().Length > 0 ? DateTime.Parse(dr["LastRunDate"].ToString()) : DateTime.MinValue;
                    row.IsApiRunning        = Convert.ToBoolean(dr["IsApiRunning"]);
                    row.WebServiceOrders    = dr["WebServiceOrders"].ToString().Length > 0 ? dr["WebServiceOrders"].ToString() : "";
                    row.WebServiceAccounts  = dr["WebServiceAccounts"].ToString().Length > 0 ? dr["WebServiceAccounts"].ToString() : "";
                    row.WebServiceDesigns   = dr["WebServiceDesigns"].ToString().Length > 0 ? dr["WebServiceDesigns"].ToString() : "";
                    row.WebServiceRaw       = dr["WebServiceRaw"].ToString().Length > 0 ? dr["WebServiceRaw"].ToString() : "";
                    row.WebServiceErrors    = dr["WebServiceErrors"].ToString().Length > 0 ? dr["WebServiceErrors"].ToString() : "";
                    row.InputFileFolder     = dr["InputFileFolder"].ToString().Length > 0 ? dr["InputFileFolder"].ToString() : "";
                    row.ExcelFileFolder     = dr["ExcelFileFolder"].ToString().Length > 0 ? dr["ExcelFileFolder"].ToString() : "";
                    row.ProblemFileFolder   = dr["ProblemFileFolder"].ToString().Length > 0 ? dr["ProblemFileFolder"].ToString() : "";
                    row.ProcessedFileFolder = dr["ProcessedFileFolder"].ToString().Length > 0 ? dr["ProcessedFileFolder"].ToString() : "";
                }
                return(row);
            }
            finally
            {
                if ((dr != null) && (!dr.IsClosed))
                {
                    dr.Close();
                }
            }
        }
Beispiel #10
0
        //  ************************************************************************
        //  Process all files in the directory passed in, recurse on any directories
        //  that are found, and process the files they contain.
        //  ------------------------------------------------------------------------
        public void ProcessDirectory(string targetDirectory, EtlTimer sync)
        {
            int read = 0;

            ///
            string[] fileEntries = Directory.GetFiles(targetDirectory);
            foreach (string fileName in fileEntries)
            {
                ProcessFile(fileName, sync);
                read = read + 1;
            }
            wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, " > (FileSearch) " + sync.ServiceName + " Files read: " + read.ToString());
            // Recurse into subdirectories of this directory.
            string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
            foreach (string subdirectory in subdirectoryEntries)
            {
                ProcessDirectory(subdirectory, sync);
            }
        }
        /// *****************************************************************************
        /// <summary>
        /// Write error messages to the WindowsService serviceLog and send same message to
        /// the WebService (Errors)
        /// </summary>
        ///
        /// "MwOrderMasterId": "1",
        /// "OrderTypeId"    : "1",    () from MW_OrderType
        ///                                 (WebAccount / WebDesign / WebOrder = 2)
        ///                                 (Nis - Name System = 1 )
        ///                                 (Text file - G&K  system = 5)
        /// "Filename"       : "test.txt",
        /// "Message"        : "test error"
        /// -----------------------------------------------------------------------------
        //public async Task WriteErrorFile(ServiceResponse source, EtlTimer syncRow)
        public void WriteErrorFile(ServiceResponse source, EtlTimer syncRow)
        {
            /// ******************************************************************************
            /// Call Web Service to transfer Error Message
            /// ------------------------------------------------------------------------------
            XDocument doc          = new XDocument();
            string    cleanContent = string.Empty;

            try
            {
                doc = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
                                         new MemoryStream(Encoding.ASCII.GetBytes(source.Request)),
                                         new XmlDictionaryReaderQuotas()));
                string fileContent = doc.ToString();
                cleanContent = fileContent.Replace("\"", "\\\"");
            }
            catch (Exception e)
            {
                cleanContent = e.Message;
            }
            /// Build the error message json string
            string frame2 = "{\"MwOrderMasterId\" : \"" + "1" +
                            "\", \"OrderTypeId\": " + "\"" + source.FileType +
                            "\"" + ", \"FileName\" : \"" + source.FileName +
                            "\", \"Error\": \"" + source.Message +
                            "\", \"Request\": \"" + cleanContent + "\" }";
            /// ==========>
            ///
            ServiceResponse resp = ConsumeWebService(frame2, source.FileName, syncRow.WebServiceErrors, syncRow);
            /// <==========
            /// ******************************************************************************
            /// Write ServiceLog
            /// ------------------------------------------------------------------------------
            //string logPath = (ConfigurationManager.AppSettings["WindowsServiceLog"].ToString());

            string message = " > File: <";       /// Set message prefix

            message = message + source.FileName + ">, Status: <" + source.Status + "> message: <" + source.Message + ">.";

            wtf.writeSyncLog(1, syncRow.MwEtlTimerId, 1, syncRow.ServiceName, message);
        }
        /// *****************************************************************************************
        /// General files process - Only NIS XML valid Files are processed here:
        ///     (1) - Select orders to process depending on Imported conditions.
        ///     (2) - Route process to the corresponding late orders process using delegates.
        ///     (3) - NIS table reading errors are detected here.
        ///     (4) - Errors are logged in service log and reported through web services.
        /// -----------------------------------------------------------------------------------------
        public void ProcessOrder(NISLateOrders order, EtlTimer sync)
        {
            /// Initialize Error messages object basic information
            ServiceResponse errMsg = new ServiceResponse();

            errMsg.FileType   = "1";
            errMsg.FileName   = "Late Order: " + order.ToString();
            errMsg.NISOrderId = "0";
            errMsg.Status     = "Not Processed";
            errMsg.Message    = string.Empty;
            try
            {
                /// *********************************************************************************
                /// Select files acceptable to be process, all other file types (extension) will not
                /// be processed (they stay in the newFiles folder) and an error message is generated
                /// to the WebServices.
                /// Only NIS (1) row are processed by entry.
                /// ---------------------------------------------------------------------------------
                if (order != null)
                {
                    /// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    /// Route to the corresponding NIS procedure
                    ///  ----------------------------------------------------------------------------
                    int res = Inr.insertNisLateOrder(order);
                    icr.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, "late order inserted: " + order.ID);
                }
                else
                {   //  update error order - set imported on and import problem on
                    int ret = Inr.updNisOrder(order.ID, 0, 1, 0);
                    icr.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, "Table reading error Late orders, order " + order);
                }
            }
            catch (Exception fle)
            {
                int res = icr.updImportControl(sync.MwEtlTimerId, 0);     //  set EtlTimer for this service to not Running (isRunning = false)
                errMsg.Message = "(NIS LateOrders) Table reading error - in order " + errMsg.FileName + ". " + fle;
                icr.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, errMsg.Message);
                int resp = Inr.updNisOrder(Convert.ToInt32(errMsg.FileName), 0, 1, 0);
            }
        }
        ///  *******************************************************************************************
        ///  <summary>
        ///  Final file processing stage - Only XML and txt Files are processed here by moving the file
        ///  from their original folder to AppProcess (when the file was processed ok), or to AppProblem
        ///  if there was a problem with it. In both cases, the file is eliminated from AppData.
        /// </summary>
        //  --------------------------------------------------------------------------------------------
        public void SaveProcessedFile(string path, bool ok, EtlTimer sync, string source)
        {
            //WriteLogFile wlf = new WriteLogFile();
            DAL.ImportControl.ImportControlRepository wlf = new DAL.ImportControl.ImportControlRepository();
            ///
            string fStatus  = "processed";
            string fileName = Path.GetFileName(path);
            string newPath;

            if (ok)
            {
                //  Save processesd file in succeeded folder as defined in etlCtrol
                newPath = sync.ProcessedFileFolder + @"\" + fileName;
                //newPath = (ConfigurationManager.AppSettings["ProcessedFilesDirectory"].ToString()) + @"\" + fileName;
                int src = Convert.ToInt32(ConfigurationManager.AppSettings["ServiceID"]);
                ///
                /// Save processed files log - May16-2017
                ///
                int res = writeImportLog(src, source, fileName);
            }
            else
            {
                newPath = sync.ProblemFileFolder + @"\" + fileName;
                //newPath = (ConfigurationManager.AppSettings["ProblemFilesDirectory"].ToString()) + @"\" + fileName;
                fStatus = "rejected with errors.";
            }
            //  delete file, if exist
            if (File.Exists(newPath))
            {
                File.Delete(newPath);
            }
            //  Move File from processed to problem directory
            File.Move(path, newPath);
            //  *************************************************************************
            //  End of file process message in service log
            //  -------------------------------------------------------------------------
            //string tableName = ConfigurationManager.AppSettings["TableName"];
            string ret = wlf.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, "> " + sync.Description + " File: <" + fileName + "> " + fStatus + ".");
        }
Beispiel #14
0
        /// <summary>
        ///     Process orders to import retreived in SyncControl_Disk, earch order will be process individually.
        ///     Will handle:
        ///     -   Catalog Web Orders and Convert orders (Service Id 2)
        ///     -   Name System Orders (Service Id 17)
        /// </summary>
        /// <param name="order">Order Number</param>
        /// <param name="sync">Import control parameters</param>
        /// <param name="item">Order type (1 - Convert. 2 - web orders), apply only for catalog Web Orders</param>
        private void ProcessRow(int order, EtlTimer sync, string item = "")
        {
            int    res = wtf.updImportControl(serviceId, 1);  //  set EtlTimer for this service to InUse
            object e   = new object();

            //  =================================================================================
            if (serviceId == 17)
            {
                ImportProcedure_NIS_V2.FileManagement TableNis = new ImportProcedure_NIS_V2.FileManagement();
                TableNis.ProcessOrder(order, sync);
            }
            else if (serviceId == 1)
            {
                ImportProcedure_DesignRequest.FileManagement TableCatalogDesignRequest = new ImportProcedure_DesignRequest.FileManagement();
                TableCatalogDesignRequest.ProcessOrder(item, sync);
            }
            else if (serviceId == 2)
            {
                ImportProcedure_Catalog.FileManagement TableCatalogWorkOrder = new ImportProcedure_Catalog.FileManagement();
                TableCatalogWorkOrder.ProcessOrder(item, sync);
            }

            res = wtf.updImportControl(serviceId, 0);     //  set EtlTimer for this service to Inactive
        }
        /// ***************************************************************************************
        /// <summary>
        /// Version 10/15/2015 - 14:48
        ///     Consume web services, in case of error, an error description entry is included
        ///     in the log file.
        ///     WeServiceTimer (method performance measure) and WebServiceOption (Production
        ///     or test) options are controlled through AppConfig.File.
        /// </summary>
        /// <param name="frame">Json Data string</param>
        /// <param name="fName">Processed File name</param>
        /// <param name="fType">File type (Raw Data or File data) </param>  unused
        /// <param name="fData">WebService url </param>
        /// <returns>Bool value to true if procces was OK</returns>
        /// --------------------------------------------------------------------------------------
        public ServiceResponse ConsumeWebService(string frame, string fName, string fData, EtlTimer syncRow)   //string fType, string fData)
        {
            /// Process measurement option, only apply when WebServicesTimer has been set to Yes
            /// in the AppConfig.file Will measure the process time from starting this method, until
            /// the response from the WebService is received.
            Stopwatch stopWatch = new Stopwatch();

            if ((ConfigurationManager.AppSettings["WebServicesTimer"].ToString()) == "Yes")
            {
                stopWatch.Start();
            }
            /// ----------------------------------------------------------------------------------
            //WriteLogFile wlf = new WriteLogFile();
            //WriteErrorFile wef = new WriteErrorFile();
            ServiceResponse err  = new ServiceResponse();   /// process errors description object
            ServiceResponse resp = new ServiceResponse();   /// Response from web service

            ///
            err.FileName = fName;
            err.Request  = frame;
            ///
            //bool res = true;
            var result = string.Empty;

            try
            {
                /// ******************************************************************************
                /// Call Web Service
                /// Web service return string message with operation result.
                /// Access to Middleware API is controlled through etlTimer Table (IsApiRunning)
                /// ------------------------------------------------------------------------------
                if (syncRow.IsApiRunning)
                {
                    string uri     = fData;
                    var    request = (HttpWebRequest)WebRequest.Create(uri);
                    request.ContentType = "text/json";
                    request.Method      = "POST";

                    using (var client = new WebClient())
                    {
                        /// Send json data to api supporting special characters within the json data
                        client.Headers[HttpRequestHeader.ContentType] = "application/json";
                        // Optionally specify an encoding for uploading and downloading strings.
                        client.Encoding = System.Text.Encoding.UTF8;
                        // Upload the data.
                        result = client.UploadString(uri, "POST", frame);
                        //resp.Status = "Error";        //  force error response only for testing purposes
                    }
                    resp = JsonConvert.DeserializeObject <ServiceResponse>(result);
                    //  -----------------------------------------------------------------------------------------
                    //  When api service return an error response (status not 'OK'),
                    //  save the data file information in MW_NavImportProblems table
                    //  -----------------------------------------------------------------------------------------
                    if (resp.Status != "OK")
                    {
                        resp.IsOk = false;                          //  Set response flag to no ok
                        int          position = fName.LastIndexOf('-');
                        ProblemFiles prob     = new ProblemFiles();
                        prob.FileName = fName;
                        if (position == -1)
                        {
                            prob.FileNumber = "n/a";
                        }
                        else
                        {
                            prob.FileNumber = fName.Substring(position + 1);
                        }
                        prob.JsonData = frame;
                        prob.FileType = ConfigurationManager.AppSettings["FileType"];
                        //  ================ >
                        int write = wtf.writeProblemFile(prob);
                        //  < ================
                    }
                }
                else
                {
                    /// ----------------------------------------------------------------------------
                    /// Testing webService (using proxy) option, apply only when WebServices Option
                    /// is not set to IsApiRunning in the etlTimer table.
                    /// To use the ApiTest option, uncomment the following code
                    /// ----------------------------------------------------------------------------
                    //ServiceOrdersClient proxy = new ServiceOrdersClient();
                    ////  route webservice based on file type
                    //result = proxy.AddOrder(frame, fName, fType);
                    resp.Status = "OK";
                    resp.IsOk   = true;
                }
                /// --------------------------------------------------------------------------------
                ///
                /// --------------------------------------------------------------------------------
                if (!String.IsNullOrEmpty(resp.Status) && (resp.Status != "OK"))
                {
                    // res = false;
                    resp.IsOk      = false;
                    err.NISOrderId = resp.NISOrderId;
                    err.Status     = resp.Status;
                    err.Message    = "Order id.: " + resp.NISOrderId + " Message: " + resp.Message;
                    ///
                    WriteErrorFile(err, syncRow);
                }
            }
            catch (Exception ex)
            {
                int          position = fName.LastIndexOf('-');
                ProblemFiles prob     = new ProblemFiles();
                prob.FileName = fName;
                if (position == -1)
                {
                    prob.FileNumber = "n/a";
                }
                else
                {
                    prob.FileNumber = fName.Substring(position + 1);
                }
                prob.JsonData = frame;
                prob.FileType = ConfigurationManager.AppSettings["FileType"];
                //  ================ >
                int write = wtf.writeProblemFile(prob);
                //  < ================
                /// Replace service log error by WebService call
                err.NISOrderId = resp.NISOrderId;
                err.Status     = "Not processed";
                err.Message    = "An error occured while running " + fData + " Web Service, : " + ex.Message;
                ///
                WriteErrorFile(err, syncRow);
                // res = false;
                resp.IsOk = false;
            }
            if ((ConfigurationManager.AppSettings["WebServicesTimer"].ToString()) == "Yes")
            {
                stopWatch.Stop();
                // Get the elapsed time as a TimeSpan value.
                TimeSpan ts = stopWatch.Elapsed;
                // Format and display the TimeSpan value.
                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                   ts.Hours, ts.Minutes, ts.Seconds,
                                                   ts.Milliseconds / 10);
                Console.WriteLine("File: " + fName + " WebService RunTime " + elapsedTime);
            }
            if (resp.Status == "OK")
            {
                resp.IsOk = true;
            }
            return(resp);
        }
        /// *************************************************************************************************
        /// <summary>
        ///     07/06/2017 10:23 version
        ///     Catalog Web Orders process, un-imported web orders are retreived and  mapped to an object (header/detail
        ///     sections).
        ///     Each section is send to WebServices as a JSON string if header/detail information is complete,
        ///     when detail info.
        ///     All errors are send to a Webservice (Error) and included in the Service log.
        /// </summary>
        /// <param name="doc">Imported Web orders</param>
        /// <param name="oNumber">Web Order number</param>
        /// <param name="syncRow">EtlTimer sync control data)</param>
        /// <returns>Process status true if procees was completed ok, else false</returns>
        /// -------------------------------------------------------------------------------------------------
        bool ICatalogTables.ProcessCatalogOrder(CatalogOrderTables doc, string oNumber, EtlTimer syncRow)
        {
            //bool rStatus = false;                    //  WebService return status (default=false)
            ServiceResponse rStatus = new ServiceResponse();

            DAL.SupportServices.SupportServices wsm = new DAL.SupportServices.SupportServices();  //  Set WebService methods pointer

            ///  Create error message object and initialice it
            ServiceResponse errMsg = new ServiceResponse();

            errMsg.FileType   = "1";    //  Set Nis Type
            errMsg.FileName   = "Catalog Web orders Table";
            errMsg.NISOrderId = oNumber.ToString();
            errMsg.Status     = "Not Processed";
            errMsg.Message    = "No items found for this order header";
            /// *********************************************************************************************
            //  Order header section
            /// ---------------------------------------------------------------------------------------------
            string jsonHead = "{ \"WebOrderSummary\":" + Newtonsoft.Json.JsonConvert.SerializeObject(doc.CatalogWebOrderSummary);

            /// *********************************************************************************************
            ///  Order Detail Section
            ///  --------------------------------------------------------------------------------------------
            /// ===============================================================================
            /// Send Imported files data content to webServices - information must be complete
            /// Order Header + all related Order Items.
            /// -------------------------------------------------------------------------------
            if (doc.CatalogWebOrderItems.Count > 0)
            {
                /// Serialize Items list and complete json string for Header and Items
                string json2 = jsonHead + ", \"WebOrderItems\" : " + Newtonsoft.Json.JsonConvert.SerializeObject(doc.CatalogWebOrderItems) + "}";
                /// ******************************************************************************
                /// Call Web Service
                /// <param name="json2">        Header/detail object Json serialized string.</param>
                /// <param name="fname">        Xml file name </param>
                /// <param name="syncRow.WebServiceOrders">File Type, route to web service(url)</param>
                /// <param name="syncRow">      EtlTimer control data.
                /// <returns>"rStatus.IsOk" true if WebService was processed, else false</returns>
                /// *** Web service url is defined in the App.Config file key 'NisOrder'.
                /// ------------------------------------------------------------------------------
                /// ==============> save order data through the defined web service
                rStatus = wsm.ConsumeWebService(json2, oNumber, syncRow.WebServiceOrders, syncRow);   //"OrderData", syncRow); //// TEMPORARY UNCOMMENT TO SEND JSON INFO
                /// ------------------------------------------------------------------------------
                ///     UNCOMMENT IF WEB SERVICE IS USED TO SEND JSON INFO
                //      rStatus.IsOK = true;         /// set order process to ok TEMPORARY,
                //      rStatus.NISOrderId = "Nav1234567";
                /// ------------------------------------------------------------------------------
                string apiMsg = "";
                int    resp   = 0;          //  Order update response
                DAL.ImportControl.ImportControlRepository ikr = new DAL.ImportControl.ImportControlRepository();
                DAL.ImportControl.ImportCatalogRepository icr = new DAL.ImportControl.ImportCatalogRepository();
                //
                if (rStatus.IsOk)
                {   //  set order condition to imported
                    apiMsg = " Imported";
                    resp   = icr.updCatalogOrder(oNumber, rStatus.NISOrderId, 1);
                }
                else
                {   //  Set order contion to imported with errors.
                    apiMsg = " Not Imported - API errors";
                }
                string ret = ikr.writeSyncLog(1, syncRow.MwEtlTimerId, 1, syncRow.ServiceName, "> " + syncRow.Description + " Catalog Web Order: <" + doc.CatalogWebOrderSummary.OrderNumber + "> " + apiMsg + ".");
                //  <==============
            }
            else
            {   /// Incomplete order (No order items included and no xls file Name reported in orderHeader)
                jsonHead = jsonHead + " }";
                /// Send Message to WebService
                wsm.WriteErrorFile(errMsg, syncRow);    //// TEMPORARY UNCOMMENT TO SEND JSON INFO
            }
            return(rStatus.IsOk);
        }
Beispiel #17
0
        int serviceId = 0; // Convert.ToInt16(ConfigurationManager.AppSettings["ServiceID"]);
        //  EtlTimer sync = new EtlTimer();     //  Version 2.0
        ///  **************************************************************************************
        ///  Version 2.0 Feb13-17
        ///  Perform Directory File search process when task time is due
        ///  Look for existing files in the NIB new files folder
        ///  Same method is used in the WindowsService version....
        ///  --------------------------------------------------------------------------------------
        //public void FileSearch(object e, EtlTimer sync)       /// NOT USED IN Version 3.0
        //{
        //    if (serviceId == 0)
        //    {
        //        //serviceId = Convert.ToInt16(ConfigurationManager.AppSettings["ServiceID"]); ;
        //        //sync = wtf.getImportControl(serviceId);
        //        serviceId = sync.MwEtlTimerId;
        //    }
        //    List<string> li = new List<string>();
        //    //
        //    wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, " > (NBI FileSearch) Start Directory scanning. for " + sync.ServiceName + ".");
        //    //
        //    //li.Add(ConfigurationManager.AppSettings["NewFilesDirectory"].ToString());   //  C:\\ImportNIBData_xml
        //    li.Add(sync.InputFileFolder);
        //    if (li.Count == 0)
        //    {
        //        wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, " > (NBI FileSearch) No Folder to process. for " + sync.ServiceName);
        //    }
        //    foreach (string path in li)
        //    {
        //        if (File.Exists(path))
        //        {   // This path is a file
        //            ProcessFile(path, sync);
        //        }
        //        else if (Directory.Exists(path))
        //        {   // This path is a directory
        //            ProcessDirectory(path, sync);
        //        }
        //        else
        //        {   //  Invalid File or Directory exit
        //            wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, "(NBI FileSearch) <" + path + " > is not a valid file or directory.");
        //        }
        //    }
        //    wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, " > (FileSearch) " + sync.ServiceName + " Files read: " + FilesRead);
        //    /// *******************************************************************************
        //    /// Back to Service SchedularCallback Function
        //    /// When FileSearch is completed process flow return to Service1.SchedularCallback.
        //    /// -------------------------------------------------------------------------------
        //}

        //  ************************************************************************
        //  Process all files in the directory passed in, recurse on any directories
        //  that are found, and process the files they contain.
        //  ------------------------------------------------------------------------
        //public void ProcessDirectory(string targetDirectory, EtlTimer sync)           /// NOT USED IN Version 3.0
        //{
        //    ///
        //    string[] fileEntries = Directory.GetFiles(targetDirectory);
        //    foreach (string fileName in fileEntries)
        //    {
        //        ProcessFile(fileName, sync);
        //    }
        //    // Recurse into subdirectories of this directory.
        //    string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        //    foreach (string subdirectory in subdirectoryEntries)
        //        ProcessDirectory(subdirectory, sync);
        //}

        /// *****************************************************************************************
        /// Version 3.0 (Feb17-17)
        /// General files process - Only NIB XML valid Files are processed here:
        ///     (1) - Select files to process depending on file extension and/or file name.
        ///     (2) - Route process to the corresponding file types import process using delegates.
        ///     (3) - Unrecognized file types and Service reading errors are detected here.
        ///     (4) - Errors are logged in service log and reported through web services.
        /// -----------------------------------------------------------------------------------------
        public void ProcessFile(string path, EtlTimer sync)
        {
            ServiceResponse errMsg = new ServiceResponse();

            errMsg.FileType   = "2";                    //  NIB file type
            errMsg.FileName   = Path.GetFileName(path); //fileName + extension;
            errMsg.Status     = "Not Processed";
            errMsg.NISOrderId = Path.GetFileNameWithoutExtension(path);;
            ///
            string extension = (Path.GetExtension(path)).ToString();
            string fileName  = Path.GetFileNameWithoutExtension(path);

            try
            {   /// *********************************************************************************
                /// Select files acceptable to be process, all other file types (extension) will not
                /// be processed (they stay in the newFiles folder) and an error message is generated
                /// to the WebServices.
                /// NIB (2) files process
                /// All NIB files have .xml and or sent extension.
                /// ---------------------------------------------------------------------------------
                string prefix = fileName;
                prefix = prefix
                         .Replace("website-account-", "Acc").Replace("website-design-", "Dsn").Replace("website-order-", "Ord");
                prefix = prefix.Substring(0, 3);
                ///
                ///  Validate if this file was already processed    May16-2017
                ///
                int dupFile = wtf.getImportLog(serviceId, "NBI", fileName + extension);

                //if (((extension == ".xml") || (extension == ".sent")) && ((prefix == "Acc") || (prefix == "Dsn") || (prefix == "Ord")))
                if (dupFile == 0 && (((extension == ".xml") || (extension == ".sent")) && ((prefix == "Acc") || (prefix == "Dsn") || (prefix == "Ord"))))
                {
                    XmlDocument doc = new XmlDocument();
                    //  Read / Load selected file content as xml
                    doc.Load(path);
                    /// Instanciate Xml methods delegate
                    Del handler = null;
                    // Declare a class instance xml:
                    ImportProcedure_NBI.XmlFiles.ImportProcess xml = new ImportProcedure_NBI.XmlFiles.ImportProcess();
                    /// Declare an interface instance xmlFile:
                    ImportProcedure_NBI.XmlFiles.IXmlFiles xmlfile = xml;       //  (ImportProcedure_NBI.XmlFiles.IXmlFiles)xml
                    /// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    /// Identify all xml files and route them to the corresponding import procedure
                    /// Replace FileName with prefix's to simplify file type identification.
                    ///  ----------------------------------------------------------------------------
                    if (prefix == "Acc")
                    {   //  NBI - Website-Accounts Files
                        handler = xmlfile.ProcessWebsiteAccountFiles;
                    }
                    else if (prefix == "Dsn")
                    {   //  NBI - Website-Designs Files
                        handler = xmlfile.ProcessWebsiteDesignFiles;
                    }
                    else if (prefix == "Ord")
                    {   //  NBI - Website-Order Files process
                        handler = xmlfile.ProcessWebsiteOrderFiles;
                    }
                    /// =========== >
                    bool ok = handler(doc, fileName, sync);                 //  Process file and WebService
                    icr.SaveProcessedFile(path, ok, sync, "NBI");
                    /// ===========>
                    //ProcessXml(path, doc, fileName, handler, sync);
                    /// < ===========
                }
                else
                {   /// Unrecognized file type
                    /// Initialize Error messages object basic information
                    ///
                    errMsg.Status     = "Not Processed";
                    errMsg.NISOrderId = fileName;
                    if (dupFile > 0)
                    {
                        errMsg.Message = "(NBI ProcessFile) File <" + fileName + extension + ">, duplicate file - already processed.";
                    }
                    else
                    {
                        errMsg.Message = "(NBI ProcessFile) File <" + fileName + extension + ">, unrecognized file type.";
                    }
                    wtf.writeSyncLog(1, Convert.ToInt16(ConfigurationManager.AppSettings["ServiceID"]), 1, sync.ServiceName, errMsg.Message);
                    /// Duplicate file control May16-2017
                    ///
                    if (dupFile == 0)
                    {
                        icr.SaveProcessedFile(path, false, sync, "STK");
                    }
                    else
                    {
                        File.Delete(path);
                    }
                    /// < ===========
                }
            }
            catch (Exception fle)
            {
                int res = wtf.updImportControl(serviceId, 0);     //  set EtlTimer for this service to not Running (isRunning = false)
                errMsg.Message = "(NBI ProcessFile) Xml reading error - File in " + errMsg.FileName + ". " + fle;
                wtf.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, errMsg.Message);
            }
        }
Beispiel #18
0
        DAL.SupportServices.SupportServices wsm = new DAL.SupportServices.SupportServices();  //  Set WebService methods pointer

        // <summary>
        ///     Process WE text files, built an object, generate a Json string and submit it to the
        ///     webServices.
        ///     If any processing errors are detected, the corresponding message is send to WebServices
        /// </summary>
        /// <param name="path">The complete path to the file in process</param>
        /// <param name="fileName">File name without the extension</param>
        /// <returns>Process result in a boolean var. if OK (true) else (false) </returns>
        public bool ProcessArrowFtpFiles(string path, string fileName, EtlTimer sync)
        {
            bool head   = false;  /// Header info detection flag
            bool newIsa = false;  /// Detail info detection flag
            bool item1  = false;  /// Items 1 / 2 sequence control
            //  bool resp = false;    /// Process final status return flag
            ServiceResponse resp    = new ServiceResponse();
            bool            process = true; /// control that process was completed ok
            ///
            int itemsCounter = 0;           /// Detail items counter
            int lineCounter  = 0;           /// Count the number of rows(records) in file
            ///
            string line;

            string[] separators = { "^" };
            ///
            WEFiles        weFiles = new WEFiles();
            List <WEItems> items   = new List <WEItems>();

            //WriteErrorFile wef = new WriteErrorFile();
            /// ---------------------------------------------------------------------------
            /// Read the file line by line. OADS_F00001 File type (Arrow FTP)
            /// ---------------------------------------------------------------------------
            System.IO.StreamReader file = new System.IO.StreamReader(path);
            try
            {
                while ((line = file.ReadLine()) != null)
                {
                    line = line.Replace("~", "");
                    ///// Count lines in file
                    lineCounter++;
                    /// Split input record into string array elements
                    string[] words = line.Split(separators, StringSplitOptions.None);
                    /// -------------------------------------------------------------------
                    /// Start file Identifier processing (Only one per file)
                    /// -------------------------------------------------------------------
                    if (words[0] == "ISA" && !newIsa)
                    {
                        if (words.Count() < 8)
                        {
                            throw new Exception("ISA record without complete info.");
                        }
                        newIsa = true;
                        string isaDate = words[3];
                        string isaTime = words[4];
                        string isaLan  = words[5];
                        string isaCurr = words[6];
                        string isaNumb = words[7];
                        string isaDatp = words[8];
                    }
                    /// -------------------------------------------------------------------
                    /// Header entry processing
                    /// -------------------------------------------------------------------
                    else if (words[0] == "HDR" && newIsa)
                    {
                        head = true;
                        string hdrCust = words[2];
                        string hdrDat1 = words[3];
                        string hdrUsr1 = words[5];
                        string hdrUsr2 = words[6];
                        string hdrDate = words[8];
                        string hdrTime = words[9];
                        string hdrDat3 = words[18];
                    }
                    /// -------------------------------------------------------------------
                    /// Address 1 entry processing
                    /// -------------------------------------------------------------------
                    else if (words[0] == "N1" && head)
                    {
                        string n1Company    = words[3];
                        string n1Address1   = words[4];
                        string n1Address2   = words[5];
                        string n1Contact    = words[6];
                        string n1State      = words[7];
                        string n1PostalCode = words[8];
                        string n1Country    = words[9];
                        string n1Dat1       = words[10];
                        string n1Dat2       = words[11];
                        string n1Dat3       = words[20];
                    }
                    /// -------------------------------------------------------------------
                    /// Address 2 entry processing
                    /// -------------------------------------------------------------------
                    else if (words[0] == "N2" && head)
                    {
                        string n2Company    = words[3];
                        string n2Address1   = words[4];
                        string n2Address2   = words[5];
                        string n2Contact    = words[6];
                        string n2State      = words[7];
                        string n2PostalCode = words[8];
                        string n2Country    = words[9];
                    }
                    /// -------------------------------------------------------------------
                    /// Item 1 entry processing
                    /// -------------------------------------------------------------------
                    else if (words[0] == "IT1" && head)
                    {
                        string it1Sequence    = words[1];
                        string it1Dat1        = words[2];
                        string it1Sku         = words[5];
                        string it1Description = words[11];
                        string it1Dat2        = words[12];
                        string it1Dat3        = words[13];
                        string it1Date        = words[14];
                        string it1Dat4        = words[15];
                        string it1Dat5        = words[16];
                        string it1Comments    = words[19];
                        item1 = true;
                    }
                    /// -------------------------------------------------------------------
                    /// Item 2 entry processing
                    /// -------------------------------------------------------------------
                    else if (words[0] == "IT2" && item1)
                    {
                        item1 = false;
                        string it2Sequence = words[1];
                        string it2Dat1     = words[2];
                        string it2Dat2     = words[3];
                        string it2Dat3     = words[4];
                    }
                    /// -------------------------------------------------------------------
                    /// GRM entry processing
                    /// -------------------------------------------------------------------
                    else if (words[0] == "GRM" && head)
                    {
                        item1 = false;
                        string grmSequence    = words[1];
                        string grmClientId    = words[2];
                        string grmDescription = words[3];
                        string grmColor       = words[4];
                        string grmText        = words[5];
                        string grmDat1        = words[6];
                    }
                    /// -------------------------------------------------------------------
                    /// EOF entry processing
                    /// -------------------------------------------------------------------
                    else if (words[0] == "EOF" && newIsa)
                    {
                        newIsa = false;
                    }
                    else
                    {
                        /// throw error - unrecognized data line (lineCounter)
                        throw new Exception("Invalid data <" + words[0] + "> in row: " + lineCounter);
                    }
                }
            }
            catch (Exception e)
            {
                /// error while reading the file
                process   = false;
                resp.IsOk = false;
                ServiceResponse errMsg = new ServiceResponse();
                errMsg.IsOk       = false;
                errMsg.FileType   = "x";    //  Set Nis Type
                errMsg.FileName   = fileName;
                errMsg.NISOrderId = "0";
                errMsg.Status     = "Not Processed";
                errMsg.Message    = e.Message;
                /// Send Message to WebService
                wsm.WriteErrorFile(errMsg, sync);
            }
            file.Close();
            /// Only if process is completed ok and the number of detail records expected
            /// match the number of records read the object is serialized and send to the
            /// corresponding Web Service
            if (process)
            {
                if (items.Count() == itemsCounter)
                {
                    weFiles.OrderDetail = items;
                    resp.IsOk           = true;
                }
                string json = Newtonsoft.Json.JsonConvert.SerializeObject(weFiles);
                /// ******************************************************************************
                /// Call Web Service
                /// <param name="json2">Include Header serialized + items seialized info.</param>
                /// <param name="fname">File to process name </param>
                /// <param name="type">File Type, determine what service to use (url)</param>
                /// <returns>"rStatus" true if WebService was processed, else false</returns>
                /// Web service url is defined in the App.Config file
                /// ------------------------------------------------------------------------------
                ///
                resp = wsm.ConsumeWebService(json, fileName, "ArrowFTP", sync);
                //  <==============
            }
            return(resp.IsOk);
        }
Beispiel #19
0
        ///  **************************************************************************************
        ///  Version 2.0
        ///  Perform Directory File search process when task time is due
        ///  Look for existing files in the new files folder
        ///  Same method is used in the WindowsService version....
        ///  --------------------------------------------------------------------------------------
        //public void FileSearch(object e, EtlTimer sync)
        //{
        //    if (serviceId == 0)
        //    {
        //        //serviceId = Convert.ToInt16(ConfigurationManager.AppSettings["ServiceID"]); ;
        //        //sync = wtf.getImportControl(serviceId);
        //        serviceId = sync.MwEtlTimerId;
        //    }
        //    List<string> li = new List<string>();
        //    //
        //    wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, " > (FileSearch) Start Directory scanning. for " + sync.ServiceName + ".");
        //    //
        //    //li.Add(ConfigurationManager.AppSettings["NewFilesDirectory"].ToString());   //  C:\\AppData
        //    li.Add(sync.InputFileFolder);
        //    if (li.Count == 0)
        //    {
        //        wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, " > (FileSearch) No Folder to process. for " + sync.ServiceName);
        //    }
        //    foreach (string path in li)
        //    {
        //        if (File.Exists(path))
        //        {   // This path is a file
        //            ProcessFile(path, sync);
        //        }
        //        else if (Directory.Exists(path))
        //        {   // This path is a directory
        //            ProcessDirectory(path, sync);
        //        }
        //        else
        //        {   //  Invalid File or Directory exit
        //            wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, "(FileSearch) <" + path + " > is not a valid file or directory.");
        //        }
        //    }
        //    wtf.writeSyncLog(1, serviceId, 1, sync.ServiceName, " > (FileSearch) " + sync.ServiceName + " Files read: " + FilesRead);
        //    /// *******************************************************************************
        //    /// Back to Service SchedularCallback Function
        //    /// When FileSearch is completed process flow return to Service1.SchedularCallback.
        //    /// -------------------------------------------------------------------------------
        //}

        //  ************************************************************************
        //  Process all files in the directory passed in, recurse on any directories
        //  that are found, and process the files they contain.
        //  ------------------------------------------------------------------------
        //public void ProcessDirectory(string targetDirectory, EtlTimer sync)
        //{
        //    ///
        //    string[] fileEntries = Directory.GetFiles(targetDirectory);
        //    foreach (string fileName in fileEntries)
        //    {
        //        ProcessFile(fileName, sync);
        //    }
        //    // Recurse into subdirectories of this directory.
        //    string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        //    foreach (string subdirectory in subdirectoryEntries)
        //        ProcessDirectory(subdirectory, sync);
        //}

        /// *****************************************************************************************
        /// General files process - Only NIS XML valid Files are processed here:
        ///     (1) - Select files to process depending on file extension and/or file name.
        ///     (2) - Route process to the corresponding file types import process using delegates.
        ///     (3) - Unrecognized file types and Service reading errors are detected here.
        ///     (4) - Errors are logged in service log and reported through web services.
        /// -----------------------------------------------------------------------------------------
        public void ProcessFile(string path, EtlTimer sync)
        {
            string extension = (Path.GetExtension(path)).ToString();
            string fileName  = Path.GetFileNameWithoutExtension(path);
            /// Initialize Error messages object basic information
            ServiceResponse errMsg = new ServiceResponse();

            errMsg.FileType   = "1";
            errMsg.FileName   = fileName + extension;
            errMsg.NISOrderId = "0";
            errMsg.Status     = "Not Processed";
            errMsg.Message    = string.Empty;
            try
            {
                /// *********************************************************************************
                /// Select files acceptable to be process, all other file types (extension) will not
                /// be processed (they stay in the newFiles folder) and an error message is generated
                /// to the WebServices.
                /// Only NIS (1) files are allowed in this directory.
                /// They have .xml and or sent extension.
                /// ---------------------------------------------------------------------------------
                string prefix = fileName;
                ///
                ///  Validate if this file was already processed - May 16 - 2017
                ///
                int serviceId = Convert.ToInt16(ConfigurationManager.AppSettings["ServiceID"]);
                int dupFile   = wtf.getImportLog(serviceId, "NIS", fileName + extension);

                //if (((extension == ".xml") || (extension == ".sent") || (extension == ".Sent")))    //   && (prefix != "Acc" && prefix != "Dsn" && prefix != "Ord"))
                if (dupFile == 0 && ((extension == ".xml") || (extension == ".sent")))
                {
                    XmlDocument doc = new XmlDocument();
                    //  Read / Load selected file content as xml
                    doc.Load(path);
                    /// Instanciate Xml methods delegate
                    Del handler = null;
                    // Declare a class instance xml:
                    ImportProcedure_NIS.XmlFiles.ImportProcess xml = new ImportProcedure_NIS.XmlFiles.ImportProcess();
                    /// Declare an interface instance xmlFile:
                    ImportProcedure_NIS.XmlFiles.IXmlFiles xmlfile = (ImportProcedure_NIS.XmlFiles.IXmlFiles)xml;
                    /// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    /// Identify NIS xml files and route them to the corresponding import procedure
                    ///  ----------------------------------------------------------------------------
                    //  NIS Files process
                    handler = xmlfile.ProcessNisFiles;
                    /// =========== >
                    ProcessXml(path, doc, fileName, handler, sync);
                    /// < ===========
                }
                else
                {   /// Unrecognized file type
                    errMsg.NISOrderId = fileName;
                    errMsg.Message    = "(NIS ProcessFile) File <" + fileName + extension + ">, unrecognized file type.";
                    wtf.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, errMsg.Message);
                    /// Move file to problem directory
                    //DAL.ImportControl.ImportControlRepository icr = new DAL.ImportControl.ImportControlRepository();
                    //icr.SaveProcessedFile(path, false, sync);
                    /// Duplicate files contrl - May16-2017
                    if (dupFile == 0)
                    {
                        icr.SaveProcessedFile(path, false, sync, "NIS");
                    }
                    else
                    {
                        File.Delete(path);          //  delete duplicate file May16-2017
                    }
                }
            }
            catch (Exception fle)
            {
                int res = wtf.updImportControl(sync.MwEtlTimerId, 0);     //  set EtlTimer for this service to not Running (isRunning = false)
                errMsg.Message = "(NIS ProcessFile) Xml reading error - File in " + errMsg.FileName + ". " + fle;
                wtf.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, errMsg.Message);
            }
        }
Beispiel #20
0
        ///  *******************************************************************************************
        /// <summary>
        /// 09/22/2015 16:39 version
        ///      Common Entry to Process all NIS Xml Files.
        ///      (1) File send to the corresponding import procedure depending on the file type.
        ///      (2) Finally process flow is transfer to final file processing stage.
        /// </summary>
        ///  -------------------------------------------------------------------------------------------
        private void ProcessXml(string path, XmlDocument doc, string tst, Del handler, EtlTimer sync)
        {
            bool ok = false;

            /// ----------------------------------------------------------------------------------------
            /// Synchronous Process option
            /// ----------------------------------------------------------------------------------------
            ok = handler(doc, tst, sync);                 //  Process file and WebService
            /// ========== >
            icr.SaveProcessedFile(path, ok, sync, "NIS");
            /// < ==========
        }
Beispiel #21
0
        /// ------------------------------------------------------------------------------------
        /// END OF Version 3.0 methods
        /// ************************************************************************************


        /// ************************************************************************************
        /// Version 3.1 methods start here, they replace the SyncControl Method
        /// All import services share the same input (Db Tables) access methods
        /// ------------------------------------------------------------------------------------
        public void SyncControl_Disk(EtlTimer sync)
        {   //
            wtf.writeSyncLog(1, sync.MwEtlTimerId, 1, sync.ServiceName, " > (TableSearch) Start Directory scanning. for " + sync.ServiceName + ".");
            //
            int    testn    = 0;
            int    order    = 1;
            string webOrder = "";

            //
            if (syncRow.MwEtlTimerId == 17)
            {
                /// Search for unimported NIS order (one at the time)
                while (order > 0) //  && testn < 5)
                {                 //  Get first unimported order from orders table
                    order = inr.getNisOrdersToImport();
                    if (order > 0)
                    {   // a row was found
                        ProcessRow(order, sync);
                        // testn++;
                    }
                }
            }
            else if (syncRow.MwEtlTimerId == 1)
            {
                /// Get unimported Catalog web orders list (order Id.)
                /// Processs Convert Orders
                var List = idr.getDesignRequest_NotImportedList();
                sync.OrderType = 0; //  Set order type to convert
                foreach (var item in List)
                {                   //  Get first unimported order from orders table
                    ProcessRow(order, sync, item);
                    testn++;
                }
            }
            else if (syncRow.MwEtlTimerId == 2)
            {
                /// Get unimported Catalog web orders list (order Id.)
                /// Processs Convert Orders
                var List = icr.getCatalogConvertOrder_NotImportedList();
                sync.OrderType = 1; //  Set order type to convert
                foreach (var item in List)
                {                   //  Get first unimported order from orders table
                    ProcessRow(order, sync, item);
                    testn++;
                }
                //  Process Web Orders
                sync.OrderType = 2;         //  Set order type to Web Orders
                List           = icr.getCatalogOrder_NotImportedList();
                foreach (var item in List)
                {   //  Get first unimported order from orders table
                    ProcessRow(order, sync, item);
                    testn++;
                }
            }
            else if (syncRow.MwEtlTimerId == 18)
            {
                List <NISLateOrders> orders = new List <NISLateOrders>();
                orders = inr.getNisLateOrders();
                int res = wtf.updImportControl(serviceId, 1);     //  set EtlTimer for this service to InUse
                /// Search for imported NIS order that are late orders (one at the time)
                foreach (var item in orders)
                {   //  Get first imported order from orders table
                    LateOrdersProcedure_NIS.FileManagement LateOrdersRequest = new LateOrdersProcedure_NIS.FileManagement();
                    LateOrdersRequest.ProcessOrder(item, sync);
                    testn++;
                }
                res = wtf.updImportControl(serviceId, 0);     //  set EtlTimer for this service to Inactive
            }
        }
        /// *************************************************************************************************
        /// <summary>
        ///     Version 3.0 Feb20-17
        ///     Website-Account Xml File is mapped to Object, then passed to WebServices as a JSON string.
        /// </summary>
        /// <param name="doc">Imported file content read as an XmlDocument</param>
        /// <param name="fName">File name (excluding path section)</param>
        /// <returns>Process status true if procees was completed ok, else false</returns>
        /// -------------------------------------------------------------------------------------------------
        bool IXmlFiles.ProcessStkOrderFiles(XmlDocument doc, string fName, EtlTimer syncRow)
        {
            //bool rStatus = false;
            ServiceResponse rStatus = new ServiceResponse();
            StkOrder        summary = new StkOrder();
            StkHeader       ord     = new StkHeader();

            /// ---------------------------------------------------------------------
            //  Order section
            /// ---------------------------------------------------------------------
            ord.OrderType = "stickers";
            XmlNode order = doc.DocumentElement.SelectSingleNode("/order");

            ord.OrderId     = dvs.AttributeValidation_String(order, "orderid", 15);
            ord.OrderNumber = dvs.AttributeValidation_String(order, "ordernum", 15);
            /// ---------------------------------------------------------------------
            //  Account section
            /// ---------------------------------------------------------------------
            XmlNode account = doc.DocumentElement.SelectSingleNode("/order/account");

            ord.AccountId  = dvs.AttributeValidation_String(account, "accountid", 15);
            ord.AccountNum = dvs.AttributeValidation_String(account, "accountnum", 15);
            /// ---------------------------------------------------------------------
            //  Locale Section
            /// ---------------------------------------------------------------------
            XmlNode locale = doc.DocumentElement.SelectSingleNode("/order/locale");

            ord.Language = dvs.AttributeValidation_String(locale, "lang", 5);
            ord.SiteUsed = dvs.AttributeValidation_String(locale, "siteused", 10);
            ord.Currency = dvs.AttributeValidation_String(locale, "currency", 10);
            /// ---------------------------------------------------------------------
            //  profile section
            /// ---------------------------------------------------------------------
            XmlNode profile = doc.DocumentElement.SelectSingleNode("/order/profile");

            ord.VatNum = dvs.AttributeValidation_String(profile, "vatnum", 15);
            ord.Credit = dvs.AttributeValidation_String(profile, "credit", 20);
            /// ---------------------------------------------------------------------
            //  Contact (Order) section
            /// ---------------------------------------------------------------------
            XmlNode contact = doc.DocumentElement.SelectSingleNode("/order/contact");

            ord.Email       = dvs.SingleNodeValidation_Text(contact, "email", 60);
            ord.Title       = dvs.SingleNodeValidation_Text(contact, "title", 20);
            ord.Forename    = dvs.SingleNodeValidation_Text(contact, "forename", 70);
            ord.Surname     = dvs.SingleNodeValidation_Text(contact, "surname", 70);
            ord.CompanyName = dvs.SingleNodeValidation_Text(contact, "company", 300);
            ord.Industry    = dvs.SingleNodeValidation_Text(contact, "industry", 200);
            ord.Source      = dvs.SingleNodeValidation_Text(contact, "source", 50);
            ord.Telephone   = dvs.SingleNodeValidation_Text(contact, "telephone", 30);
            /// ---------------------------------------------------------------------
            //  Address Section - (Cardholder)
            /// ---------------------------------------------------------------------
            XmlNode cardHolder = doc.DocumentElement.SelectSingleNode("/order/address[@type='cardholder']");

            //  ------------------------------------------------------------------
            ord.AddressCardHolderTown     = dvs.SingleNodeValidation_Text(cardHolder, "town", 150);
            ord.AddressCardHolderCounty   = dvs.SingleNodeValidation_Text(cardHolder, "county", 150);
            ord.AddressCardHolderPostCode = dvs.SingleNodeValidation_Text(cardHolder, "postcode", 30);
            ord.AddressCardHolderCountry  = dvs.SingleNodeValidation_Text(cardHolder, "country", 200);
            /// Cardholder Line section within
            XmlNodeList xLt = doc.DocumentElement.SelectNodes("/order/address[@type='cardholder']/line");

            foreach (XmlNode xn in xLt)
            {
                int index = dvs.AttributeValidation_Int(xn, "index");
                switch (index)
                {
                case 1:
                    ord.AddressCardHolderLine1 = xn.InnerText;                  //  300
                    if (ord.AddressCardHolderLine1.Length > 300)
                    {
                        string txt = ord.AddressCardHolderLine1.Substring(0, 300);
                        ord.AddressCardHolderLine1 = txt;
                    }
                    break;

                case 2:
                    ord.AddressCardHolderLine2 = xn.InnerText;                  //  300
                    if (ord.AddressCardHolderLine2.Length > 300)
                    {
                        string txt = ord.AddressCardHolderLine2.Substring(0, 300);
                        ord.AddressCardHolderLine2 = txt;
                    }
                    break;

                default:
                    break;
                }
            }
            /// ----------------------------------------------------------------------
            //  Address Section Process - (Delivery)
            //  ----------------------------------------------------------------------
            XmlNode delivery = doc.DocumentElement.SelectSingleNode("/order/address[@type='delivery']");

            /// -------------------------------------------------------------------
            //ord.AddressDeliveryCompany = SingleNodeValidation_Text(delivery, "company");
            ord.AddressDeliveryTown     = dvs.SingleNodeValidation_Text(delivery, "town", 150);
            ord.AddressDeliveryCounty   = dvs.SingleNodeValidation_Text(delivery, "county", 150);
            ord.AddressDeliveryPostCode = dvs.SingleNodeValidation_Text(delivery, "postcode", 30);
            ord.AddressDeliveryCountry  = dvs.SingleNodeValidation_Text(delivery, "country", 200);
            //  Contact Section within Address section (Delivery type)
            XmlNode delContact = doc.DocumentElement.SelectSingleNode("/order/address[@type='delivery']/contact");

            ord.AddressDeliveryForename = delContact.SelectSingleNode("forename").InnerXml;
            //  Validate AddressDeliveryForename to max 70
            if (ord.AddressDeliveryForename.Length > 70)
            {
                string fname = ord.AddressDeliveryForename.Substring(0, 70);
                ord.AddressDeliveryForename = fname;
            }
            ord.AddressDeliverySurname = delContact.SelectSingleNode("surname").InnerXml;
            //  Validate AddressDeliverySurename to max 70
            if (ord.AddressDeliverySurname.Length > 70)
            {
                string sname = ord.AddressDeliverySurname.Substring(0, 70);
                ord.AddressDeliverySurname = sname;
            }
            ord.AddressDeliveryTelephone = delContact.SelectSingleNode("telephone").InnerXml;
            //  Validate telephone to max 30
            if (ord.AddressDeliveryTelephone.Length > 30)
            {
                string phone = ord.AddressDeliveryTelephone.Substring(0, 30);
                ord.AddressDeliveryTelephone = phone;
            }
            //  Line section within Address section (Delivery type)
            XmlNodeList xnLine = doc.DocumentElement.SelectNodes("/order/address[@type='delivery']/line");

            foreach (XmlNode xi in xnLine)
            {
                int index = dvs.AttributeValidation_Int(xi, "index");
                switch (index)
                {
                case 1:
                    ord.AddressDeliveryLine1 = xi.InnerText;                //  300
                    if (ord.AddressDeliveryLine1.Length > 300)
                    {
                        string txt = ord.AddressDeliveryLine1.Substring(0, 300);
                        ord.AddressDeliveryLine1 = txt;
                    }
                    break;

                case 2:
                    ord.AddressDeliveryLine2 = xi.InnerText;                //  300
                    if (ord.AddressDeliveryLine2.Length > 300)
                    {
                        string txt = ord.AddressDeliveryLine2.Substring(0, 300);
                        ord.AddressDeliveryLine2 = txt;
                    }
                    break;

                default:
                    break;
                }
            }
            /// ----------------------------------------------------------------------
            //  Cart Section
            //  ----------------------------------------------------------------------
            XmlNode cart = doc.DocumentElement.SelectSingleNode("/order/cart");

            ord.CartPrice = dvs.AttributeValidation_Dec(cart, "price");
            /// ------------------------------------------------------------------
            //  Item Section - (n) Items Within Cart
            //  ------------------------------------------------------------------
            XmlNodeList item = doc.DocumentElement.SelectNodes("/order/cart/item");
            /// Order items work area array
            List <StkOrderItem> nItems = new List <StkOrderItem>();

            ///
            foreach (XmlNode itm in item)
            {
                StkOrderItem xItem = new StkOrderItem();
                xItem.ItemProof          = dvs.AttributeValidation_String(itm, "proof", 100);
                xItem.ItemSku            = dvs.AttributeValidation_String(itm, "sku", 30);
                xItem.ItemWhiteBehind    = dvs.AttributeValidation_String(itm, "whitebehind", 30);    //  for clear stickers, whether the vinyl is pre-printed with a white underlay
                xItem.ItemVsize          = dvs.AttributeValidation_Dec(itm, "vsize");                 //  vertical size in mm
                xItem.ItemStyleNum       = dvs.AttributeValidation_String(itm, "stylenum", 30);
                xItem.ItemSimilar        = dvs.AttributeValidation_String(itm, "similar", 30);        //
                xItem.ItemShape          = dvs.AttributeValidation_String(itm, "shape", 30);          //  the specified shape
                xItem.ItemReversePrint   = dvs.AttributeValidation_String(itm, "reverseprint", 30);   //  for window stickers, whether the print is on the inside or outside of the sticker
                xItem.ItemQuantity       = dvs.AttributeValidation_Int(itm, "quantity");              //
                xItem.ItemPrintedWhite   = dvs.AttributeValidation_String(itm, "printedwhite", 30);   //  for window stickers, whether the vinyl has a printed white background
                xItem.ItemPpu            = dvs.AttributeValidation_String(itm, "ppu", 20);
                xItem.ItemNumHoles       = dvs.AttributeValidation_Int(itm, "numholes");              //  number of holes inside a custom-specified shape
                xItem.ItemMaterialOption = dvs.AttributeValidation_String(itm, "materialoption", 30); //  not sure (unused J&A internal field?)
                xItem.ItemMaterial       = dvs.AttributeValidation_String(itm, "material", 30);       //  vinyl or paper, depending on range
                xItem.ItemLines          = dvs.AttributeValidation_Int(itm, "lines");                 //
                xItem.ItemId             = dvs.AttributeValidation_Int(itm, "itemid");
                xItem.ItemIdentical      = dvs.AttributeValidation_String(itm, "identical", 30);
                xItem.ItemHsize          = dvs.AttributeValidation_Dec(itm, "hsize");               //  horizontal size in mm
                xItem.ItemDesignId       = dvs.AttributeValidation_String(itm, "designid", 30);
                xItem.ItemCornerRad      = dvs.AttributeValidation_String(itm, "cornerrad", 30);    //  corner radius in mm
                xItem.ItemColour         = dvs.AttributeValidation_String(itm, "colour", 30);
                xItem.ItemCode           = dvs.AttributeValidation_String(itm, "code", 10);
                xItem.ItemSheets         = dvs.AttributeValidation_Int(itm, "sheets");              //  Added on Jun 26
                xItem.ItemsPerSheet      = dvs.AttributeValidation_Int(itm, "persheet");            //  Added on Jun 29
                /// --------------------------------------------------------------
                //  Names Section - (n) names within Item
                //  --------------------------------------------------------------
                XmlNodeList name = doc.DocumentElement.SelectNodes("/order/cart/item/name");

                //List<ItemNames> lNames = new List<ItemNames>();
                //foreach (XmlNode nme in name)
                //{
                //    /// ----------------------------------------------------------
                //    //  Line Section - (Maximun 7 lines) within name
                //    /// ----------------------------------------------------------
                //    //XmlNodeList line = doc.DocumentElement.SelectNodes("/order/cart/item/name/line");
                //    ItemNames wrkName = new ItemNames();
                //    foreach (XmlNode xn in nme)
                //    {
                //        int index = AttributeValidation_Int(xn, "index");
                //        switch (index)
                //        {
                //            case 1:
                //                wrkName.ItemName1 = FirstChildValidation_Inner(xn);
                //                break;
                //            case 2:
                //                wrkName.ItemName2 = FirstChildValidation_Inner(xn);
                //                break;
                //            case 3:
                //                wrkName.ItemName3 = FirstChildValidation_Inner(xn);
                //                break;
                //            case 4:
                //                wrkName.ItemName4 = FirstChildValidation_Inner(xn);
                //                break;
                //            case 5:
                //                wrkName.ItemName5 = FirstChildValidation_Inner(xn);
                //                break;
                //            case 6:
                //                wrkName.ItemName6 = FirstChildValidation_Inner(xn);
                //                break;
                //            case 7:
                //                wrkName.ItemName7 = FirstChildValidation_Inner(xn);
                //                break;
                //            default:
                //                break;
                //        }
                //    }
                //    /// Add max. lines (index texts) by name to Names List
                //    lNames.Add(wrkName);
                //}
                ///// Save Names List in Item row
                //xItem.names = lNames;
                /// Add Item row to Items List
                nItems.Add(xItem);
            }
            /// ----------------------------------------------------------------------
            /// Discount Section
            /// ----------------------------------------------------------------------
            XmlNode discount = doc.DocumentElement.SelectSingleNode("/order/discount");

            ord.DiscountType  = dvs.AttributeValidation_String(discount, "type", 20);
            ord.DiscountCode  = dvs.AttributeValidation_String(discount, "code", 20);
            ord.DiscountTotal = dvs.AttributeValidation_Dec(discount, "total");
            ord.DiscountValue = dvs.AttributeValidation_Dec(discount, "value");
            /// ----------------------------------------------------------------------
            //  Delivery section
            //  ----------------------------------------------------------------------
            XmlNode xDelivery = doc.DocumentElement.SelectSingleNode("/order/delivery");

            ord.DeliveryTotal     = dvs.AttributeValidation_Dec(xDelivery, "total");
            ord.DeliveryType      = dvs.AttributeValidation_String(xDelivery, "type", 10);
            ord.DeliveryTerritory = dvs.AttributeValidation_String(xDelivery, "territory", 5);
            ord.DeliveryId        = dvs.AttributeValidation_Int(xDelivery, "deliveryid");
            ord.DeliveryEta       = dvs.AttributeValidation_Date(xDelivery, "etd");
            ord.DeliveryEtd       = dvs.AttributeValidation_Date(xDelivery, "eta");
            /// ----------------------------------------------------------------------
            //  Vat Section
            //  ----------------------------------------------------------------------
            XmlNode vat = doc.DocumentElement.SelectSingleNode("/order/vat");

            ord.VatTotal        = dvs.AttributeValidation_Dec(vat, "total");
            ord.VatNumber       = dvs.AttributeValidation_Int(vat, "number");
            ord.VatCountyCode   = dvs.AttributeValidation_String(vat, "countycode", 5);
            ord.VatDistrictRate = dvs.AttributeValidation_Dec(vat, "districtrate");
            ord.VatCityRate     = dvs.AttributeValidation_Dec(vat, "cityrate");
            ord.VatCountyRate   = dvs.AttributeValidation_Dec(vat, "countyrate");
            ord.VatStateRate    = dvs.AttributeValidation_Dec(vat, "staterate");
            ord.VatState        = dvs.AttributeValidation_String(vat, "state", 2);
            ord.VatCounty       = dvs.AttributeValidation_String(vat, "county", 150);
            ord.VatCity         = dvs.AttributeValidation_String(vat, "city", 150);
            ord.VatStaticRate   = dvs.AttributeValidation_Dec(vat, "staticrate");
            ord.VatLiveRate     = dvs.AttributeValidation_Dec(vat, "liverate");
            ord.VatRate         = dvs.AttributeValidation_Dec(vat, "rate");
            /// ----------------------------------------------------------------------
            //  Options Section
            //  ----------------------------------------------------------------------
            XmlNode options = doc.DocumentElement.SelectSingleNode("/order/options");

            ord.OptionsBlindPacking = dvs.AttributeValidation_String(options, "blindpacking", 15);
            ord.OptionsCustRef      = dvs.AttributeValidation_String(options, "custref", 50);
            /// ----------------------------------------------------------------------
            //  Payment Section
            //  ----------------------------------------------------------------------
            XmlNode payment = doc.DocumentElement.SelectSingleNode("/order/payment");

            ord.PaymentUsing = dvs.AttributeValidation_String(payment, "using", 50);
            //  net Section
            XmlNode net = doc.DocumentElement.SelectSingleNode("/order/payment/net");

            ord.PaymentCurrency = dvs.AttributeValidation_String(net, "currency", 5);
            string amt = dvs.FirstChildValidation_Inner(net);

            ord.PaymentAmount = Decimal.Parse(amt);
            //  gross Section
            XmlNode gross = doc.DocumentElement.SelectSingleNode("/order/payment/gross");

            ord.GrossCurrency = gross.Attributes["currency"].Value;
            string grossAmt = dvs.FirstChildValidation_Inner(gross);

            ord.GrossAmount = Decimal.Parse(grossAmt);
            /// ----------------------------------------------------------------------
            /// Serialize object (WebOrder) to Json string
            /// Save Items List in Order Items List (include items / names within / name lines within)
            summary.stkOrderSummary = ord;
            summary.stkOrderItems   = nItems;
            //
            ord.Filename = fName + ".xml";
            string test = Newtonsoft.Json.JsonConvert.SerializeObject(summary);

            //  =========== >
            //DAL.SupportServices.SupportServices wsm = new DAL.SupportServices.SupportServices();
            /// ******************************************************************************
            /// Call Web Service - "WebOrder"
            /// <param name="json2">Include Header serialized + items seialized info.</param>
            /// <param name="fname">File to process name </param>
            /// <param name="type">File Type, determine what service to use (url)</param>
            /// <returns>"rStatus" true if WebService was processed, else false</returns>
            /// Web service url is defined in the App.Config file
            /// ------------------------------------------------------------------------------
            rStatus = wsm.ConsumeWebService(test, fName, syncRow.WebServiceOrders, syncRow);
            //  < ===========
            return(rStatus.IsOk);
        }
Beispiel #23
0
        /// *************************************************************************************************
        /// <summary>
        ///     09/22/2015 16:39 version
        ///     Website-Design Xml File is mapped to Object, then passed to WebServices as a JSON string.
        /// </summary>
        /// <param name="doc">Imported file content read as an XmlDocument</param>
        /// <param name="fName">File name (excluding path section)</param>
        /// <returns>Process status true if procees was completed ok, else false</returns>
        /// -------------------------------------------------------------------------------------------------
        bool IXmlFiles.ProcessWebsiteDesignFiles(XmlDocument doc, string fName, EtlTimer syncRow)
        {
            //WebServiceManager wsm = new WebServiceManager();
            DAL.SupportServices.SupportServices wsm = new DAL.SupportServices.SupportServices();
            WebDesign       des     = new WebDesign();
            ServiceResponse rStatus = new ServiceResponse();

            /// ----------------------------------------------------------------------
            //  Design section
            /// ----------------------------------------------------------------------
            des.OrderType = "nbi";
            XmlNode design = doc.DocumentElement.SelectSingleNode("/design");

            des.StyleNum  = dat.AttributeValidation_String(design, "stylenum", 0);
            des.DesignID  = dat.AttributeValidation_String(design, "designid", 0);
            des.TimeStamp = dat.AttributeValidation_Date(design, "timestamp");
            /// ----------------------------------------------------------------------
            //  Specs Section
            /// ----------------------------------------------------------------------
            XmlNode specs = doc.DocumentElement.SelectSingleNode("/design/specs");

            des.Proof   = dat.AttributeValidation_String(specs, "proof", 0);
            des.lines   = dat.AttributeValidation_String(specs, "lines", 0);
            des.Fitting = dat.AttributeValidation_String(specs, "fitting", 0);
            des.Bar     = dat.AttributeValidation_String(specs, "bar", 0);
            des.Vinyl   = dat.AttributeValidation_String(specs, "vinyl", 0);
            des.Code    = dat.AttributeValidation_String(specs, "code", 0);
            /// ----------------------------------------------------------------------
            //  Background Section
            /// ----------------------------------------------------------------------
            XmlNode background = doc.DocumentElement.SelectSingleNode("/design/background");

            des.Src = dat.AttributeValidation_String(background, "src", 0);
            /// ------dat.----------------------------------------------------------------
            //  Contacdat.t (account) section process
            /// ----------------------------------------------------------------------
            XmlNodeList        frag      = doc.DocumentElement.SelectNodes("/design/fragments/logo");
            WebDesignFragments fragments = new WebDesignFragments();

            foreach (XmlNode logo in frag)
            {
                fragments.Src    = dat.AttributeValidation_String(logo, "src", 0);
                fragments.Top    = dat.AttributeValidation_String(logo, "top", 0);
                fragments.Left   = dat.AttributeValidation_String(logo, "left", 0);
                fragments.Height = dat.AttributeValidation_String(logo, "height", 0);
                fragments.Width  = dat.AttributeValidation_String(logo, "width", 0);
                fragments.Index  = dat.AttributeValidation_Int(logo, "index");
            }
            des.logo = fragments;
            /// ----------------------------------------------------------------------
            //  Address Section Process - (Delivery)
            /// ----------------------------------------------------------------------
            XmlNodeList Text = doc.DocumentElement.SelectNodes("/design/fragments");

            List <WebDesignText> texts = new List <WebDesignText>();

            foreach (XmlNode txt in Text)
            {
                XmlNodeList tNodes = doc.SelectNodes("/design/fragments/text");
                foreach (XmlNode tNode in tNodes)
                {
                    WebDesignText cnt1 = new WebDesignText();
                    //
                    cnt1.Index   = dat.AttributeValidation_Int(tNode, "index");
                    cnt1.Color   = dat.AttributeValidation_String(tNode, "color", 0);
                    cnt1.Size    = dat.AttributeValidation_String(tNode, "size", 0);
                    cnt1.Style   = dat.AttributeValidation_String(tNode, "style", 0);
                    cnt1.Font    = dat.AttributeValidation_String(tNode, "font", 0);
                    cnt1.Y       = dat.AttributeValidation_String(tNode, "y", 0);
                    cnt1.X       = dat.AttributeValidation_String(tNode, "x", 0);
                    cnt1.Content = dat.AttributeValidation_String(tNode, "content", 0);
                    //
                    texts.Add(cnt1);
                }
            }
            des.texts    = texts;
            des.Filename = fName + ".xml";
            string test = Newtonsoft.Json.JsonConvert.SerializeObject(des);

            /// ******************************************************************************
            /// Call Web Service - "WebDesign"
            /// <param name="json2">Include Header serialized + items seialized info.</param>
            /// <param name="fname">File to process name </param>
            /// <param name="type">File Type, determine what service to use (url)</param>
            /// <returns>"rStatus" true if WebService was processed, else false</returns>
            /// Web service url is defined in the App.Config file
            /// ------------------------------------------------------------------------------
            rStatus = wsm.ConsumeWebService(test, fName, syncRow.WebServiceDesigns, syncRow);
            //  <==============
            return(rStatus.IsOk);
        }
Beispiel #24
0
        /// *************************************************************************************************
        /// <summary>
        ///     10/29/2015 08:59 version
        ///     Website-Account Xml File is mapped to Object, then passed to WebServices as a JSON string.
        /// </summary>
        /// <param name="doc">Imported file content read as an XmlDocument</param>
        /// <param name="fName">File name (excluding path section)</param>
        /// <returns>Process status true if procees was completed ok, else false</returns>
        /// -------------------------------------------------------------------------------------------------
        bool IXmlFiles.ProcessWebsiteOrderFiles(XmlDocument doc, string fName, EtlTimer syncRow)
        {
            ServiceResponse rStatus = new ServiceResponse();
            WebOrder        summary = new WebOrder();
            NBIHeader       ord     = new NBIHeader();

            /// ---------------------------------------------------------------------
            //  Order section
            /// ---------------------------------------------------------------------
            ord.OrderType = "nbi";
            XmlNode order = doc.DocumentElement.SelectSingleNode("/order");

            ord.OrderId     = dat.AttributeValidation_String(order, "orderid", 15);             //  int 15
            ord.OrderNumber = dat.AttributeValidation_String(order, "ordernum", 15);            //  int 15
            /// ---------------------------------------------------------------------
            //  Account section
            /// ---------------------------------------------------------------------
            XmlNode account = doc.DocumentElement.SelectSingleNode("/order/account");

            ord.AccountId  = dat.AttributeValidation_String(account, "accountid", 15);          //  int
            ord.AccountNum = dat.AttributeValidation_String(account, "accountnum", 15);         //  int
            /// ---------------------------------------------------------------------
            //  Locale Section
            /// ---------------------------------------------------------------------
            XmlNode locale = doc.DocumentElement.SelectSingleNode("/order/locale");

            ord.Language = dat.AttributeValidation_String(locale, "lang", 5);                   //  5
            ord.SiteUsed = dat.AttributeValidation_String(locale, "siteused", 10);              //  10
            ord.Currency = dat.AttributeValidation_String(locale, "currency", 10);              //  10
            /// ---------------------------------------------------------------------
            //  profile section
            /// ---------------------------------------------------------------------
            XmlNode profile = doc.DocumentElement.SelectSingleNode("/order/profile");

            ord.VatNum = dat.AttributeValidation_String(profile, "vatnum", 15);                 //  int
            ord.Credit = dat.AttributeValidation_String(profile, "credit", 20);                 //  dec
            /// ---------------------------------------------------------------------
            //  Contact (Order) section
            /// ---------------------------------------------------------------------
            XmlNode contact = doc.DocumentElement.SelectSingleNode("/order/contact");

            ord.Email       = dat.SingleNodeValidation_Text(contact, "email", 60);              //  60
            ord.Title       = dat.SingleNodeValidation_Text(contact, "title", 20);              //  20
            ord.Forename    = dat.SingleNodeValidation_Text(contact, "forename", 70);           //  70
            ord.Surname     = dat.SingleNodeValidation_Text(contact, "surname", 70);            //  70
            ord.CompanyName = dat.SingleNodeValidation_Text(contact, "company", 300);           //  300
            ord.Industry    = dat.SingleNodeValidation_Text(contact, "industry", 200);          //  200
            ord.Source      = dat.SingleNodeValidation_Text(contact, "source", 50);             //  50
            ord.Telephone   = dat.SingleNodeValidation_Text(contact, "telephone", 30);          //  30
            /// ---------------------------------------------------------------------
            //  Address Section - (Cardholder)
            /// ---------------------------------------------------------------------
            XmlNode cardHolder = doc.DocumentElement.SelectSingleNode("/order/address[@type='cardholder']");

            //  ------------------------------------------------------------------
            ord.AddressCardHolderTown     = dat.SingleNodeValidation_Text(cardHolder, "town", 150);             //  150
            ord.AddressCardHolderCounty   = dat.SingleNodeValidation_Text(cardHolder, "county", 150);           //  150
            ord.AddressCardHolderPostCode = dat.SingleNodeValidation_Text(cardHolder, "postcode", 30);          //  30
            ord.AddressCardHolderCountry  = dat.SingleNodeValidation_Text(cardHolder, "country", 200);          //  200
            /// Cardholder Line section within
            XmlNodeList xLt = doc.DocumentElement.SelectNodes("/order/address[@type='cardholder']/line");

            foreach (XmlNode xn in xLt)
            {
                int index = dat.AttributeValidation_Int(xn, "index");
                switch (index)
                {
                case 1:
                    ord.AddressCardHolderLine1 = xn.InnerText;                  //  300
                    if (ord.AddressCardHolderLine1.Length > 300)
                    {
                        string txt = ord.AddressCardHolderLine1.Substring(0, 300);
                        ord.AddressCardHolderLine1 = txt;
                    }
                    break;

                case 2:
                    ord.AddressCardHolderLine2 = xn.InnerText;                  //  300
                    if (ord.AddressCardHolderLine2.Length > 300)
                    {
                        string txt = ord.AddressCardHolderLine2.Substring(0, 300);
                        ord.AddressCardHolderLine2 = txt;
                    }
                    break;

                default:
                    break;
                }
            }
            /// ----------------------------------------------------------------------
            //  Address Section Process - (Delivery)
            //  ----------------------------------------------------------------------
            XmlNode delivery = doc.DocumentElement.SelectSingleNode("/order/address[@type='delivery']");

            /// -------------------------------------------------------------------
            ord.AddressDeliveryCompany  = dat.SingleNodeValidation_Text(delivery, "company", 300);  //  300
            ord.AddressDeliveryTown     = dat.SingleNodeValidation_Text(delivery, "town", 150);     //  150
            ord.AddressDeliveryCounty   = dat.SingleNodeValidation_Text(delivery, "county", 150);   //  150
            ord.AddressDeliveryPostCode = dat.SingleNodeValidation_Text(delivery, "postcode", 30);  //  30
            ord.AddressDeliveryCountry  = dat.SingleNodeValidation_Text(delivery, "country", 200);  //  200
            //  Contact Section within Address section (Delivery type)
            XmlNode delContact = doc.DocumentElement.SelectSingleNode("/order/address[@type='delivery']/contact");

            ord.AddressDeliveryForename = delContact.SelectSingleNode("forename").InnerXml;     //  70
            //  Validate AddressDeliveryForename to max 70
            if (ord.AddressDeliveryForename.Length > 70)
            {
                string fname = ord.AddressDeliveryForename.Substring(0, 70);
                ord.AddressDeliveryForename = fname;
            }
            ord.AddressDeliverySurname = delContact.SelectSingleNode("surname").InnerXml;       //  70
            //  Validate AddressDeliverySurename to max 70
            if (ord.AddressDeliverySurname.Length > 70)
            {
                string sname = ord.AddressDeliverySurname.Substring(0, 70);
                ord.AddressDeliverySurname = sname;
            }
            ord.AddressDeliveryTelephone = delContact.SelectSingleNode("telephone").InnerXml;   //  30
            //  Validate Phone number max length is 30
            if (ord.AddressDeliveryTelephone.Length > 30)
            {
                string phone = ord.AddressDeliveryTelephone.Substring(0, 30);
                ord.AddressDeliveryTelephone = phone;
            }
            //  Line section within Address section (Delivery type)
            XmlNodeList xnLine = doc.DocumentElement.SelectNodes("/order/address[@type='delivery']/line");

            foreach (XmlNode xi in xnLine)
            {
                int index = dat.AttributeValidation_Int(xi, "index");
                switch (index)
                {
                case 1:
                    ord.AddressDeliveryLine1 = xi.InnerText;                //  300
                    if (ord.AddressDeliveryLine1.Length > 300)
                    {
                        string txt = ord.AddressDeliveryLine1.Substring(0, 300);
                        ord.AddressDeliveryLine1 = txt;
                    }
                    break;

                case 2:
                    ord.AddressDeliveryLine2 = xi.InnerText;                //  300
                    if (ord.AddressDeliveryLine2.Length > 300)
                    {
                        string txt = ord.AddressDeliveryLine2.Substring(0, 300);
                        ord.AddressDeliveryLine2 = txt;
                    }
                    break;

                default:
                    break;
                }
            }
            /// ----------------------------------------------------------------------
            //  Cart Section
            //  ----------------------------------------------------------------------
            XmlNode cart = doc.DocumentElement.SelectSingleNode("/order/cart");

            ord.CartPrice = dat.AttributeValidation_Dec(cart, "price");
            /// ------------------------------------------------------------------
            //  Item Section - (n) Items Within Cart
            //  ------------------------------------------------------------------
            XmlNodeList item = doc.DocumentElement.SelectNodes("/order/cart/item");
            /// Order items work area array
            List <WebOrderItem> nItems = new List <WebOrderItem>();

            ///
            foreach (XmlNode itm in item)
            {
                WebOrderItem xItem = new WebOrderItem();
                xItem.ItemProof     = dat.AttributeValidation_String(itm, "proof", 100);        //  100
                xItem.ItemSku       = dat.AttributeValidation_String(itm, "sku", 30);           //  30
                xItem.ItemIdentical = dat.AttributeValidation_String(itm, "identical", 30);     //  30
                xItem.ItemSimilar   = dat.AttributeValidation_String(itm, "similar", 30);       //  30
                xItem.ItemStyleNum  = dat.AttributeValidation_String(itm, "stylenum", 30);      //  30
                xItem.ItemId        = dat.AttributeValidation_Int(itm, "itemid");
                xItem.ItemDesignId  = dat.AttributeValidation_String(itm, "designid", 30);      //  30
                xItem.ItemPpu       = dat.AttributeValidation_String(itm, "ppu", 20);           //  20
                xItem.ItemQuantity  = dat.AttributeValidation_Int(itm, "quantity");
                xItem.ItemLines     = dat.AttributeValidation_Int(itm, "lines");
                xItem.ItemFitting   = dat.AttributeValidation_String(itm, "fitting", 50);       //  50
                xItem.ItemBar       = dat.AttributeValidation_String(itm, "bar", 50);           //  50
                xItem.ItemVinyl     = dat.AttributeValidation_String(itm, "vinyl", 50);         //  50
                xItem.ItemCode      = dat.AttributeValidation_String(itm, "code", 10);          //  10
                /// --------------------------------------------------------------
                //  Names Section - (n) names within Item
                //  --------------------------------------------------------------
                List <ItemNames> lNames = new List <ItemNames>();
                int qty = xItem.ItemQuantity;       //  Set the names search limit
                foreach (XmlNode nme in itm)
                {
                    /// ----------------------------------------------------------
                    //  Line Section - (Maximun 7 lines) within name
                    /// ----------------------------------------------------------
                    //XmlNodeList line = doc.DocumentElement.SelectNodes("/order/cart/item/name/line");
                    ItemNames wrkName = new ItemNames();
                    foreach (XmlNode xn in nme)
                    {
                        int index = dat.AttributeValidation_Int(xn, "index");
                        switch (index)
                        {
                        case 1:
                            wrkName.ItemName1 = dat.FirstChildValidation_TextValue(xn);
                            if (wrkName.ItemName1.Length > 100)
                            {
                                string txt = wrkName.ItemName1.Substring(0, 300);
                                wrkName.ItemName1 = txt;
                            }
                            break;

                        case 2:
                            wrkName.ItemName2 = dat.FirstChildValidation_TextValue(xn);
                            if (wrkName.ItemName2.Length > 100)
                            {
                                string txt = wrkName.ItemName2.Substring(0, 300);
                                wrkName.ItemName2 = txt;
                            }
                            break;

                        case 3:
                            wrkName.ItemName3 = dat.FirstChildValidation_TextValue(xn);
                            if (wrkName.ItemName3.Length > 100)
                            {
                                string txt = wrkName.ItemName3.Substring(0, 300);
                                wrkName.ItemName3 = txt;
                            }
                            break;

                        case 4:
                            wrkName.ItemName4 = dat.FirstChildValidation_TextValue(xn);
                            if (wrkName.ItemName4.Length > 100)
                            {
                                string txt = wrkName.ItemName4.Substring(0, 300);
                                wrkName.ItemName4 = txt;
                            }
                            break;

                        case 5:
                            wrkName.ItemName5 = dat.FirstChildValidation_TextValue(xn);
                            if (wrkName.ItemName5.Length > 100)
                            {
                                string txt = wrkName.ItemName5.Substring(0, 300);
                                wrkName.ItemName5 = txt;
                            }
                            break;

                        case 6:
                            wrkName.ItemName6 = dat.FirstChildValidation_TextValue(xn);
                            if (wrkName.ItemName6.Length > 100)
                            {
                                string txt = wrkName.ItemName6.Substring(0, 300);
                                wrkName.ItemName6 = txt;
                            }
                            break;

                        case 7:
                            wrkName.ItemName7 = dat.FirstChildValidation_TextValue(xn);
                            if (wrkName.ItemName7.Length > 100)
                            {
                                string txt = wrkName.ItemName7.Substring(0, 300);
                                wrkName.ItemName7 = txt;
                            }
                            break;

                        default:
                            break;
                        }
                    }
                    /// Add max. lines (index texts) by name to Names List
                    lNames.Add(wrkName);
                    qty = qty - 1;
                    if (qty == 0)
                    {
                        break;
                    }
                }
                /// Save Names List in Item row
                xItem.names = lNames;
                /// Add Item row to Items List
                nItems.Add(xItem);
            }
            /// ----------------------------------------------------------------------
            /// Discount Section
            /// ----------------------------------------------------------------------
            XmlNode discount = doc.DocumentElement.SelectSingleNode("/order/discount");

            ord.DiscountType  = dat.AttributeValidation_String(discount, "type", 20);                  //  20
            ord.DiscountCode  = dat.AttributeValidation_String(discount, "code", 20);                  //  20
            ord.DiscountTotal = dat.AttributeValidation_Dec(discount, "total");
            ord.DiscountValue = dat.AttributeValidation_Dec(discount, "value");
            /// ----------------------------------------------------------------------
            //  Delivery section
            //  ----------------------------------------------------------------------
            XmlNode xDelivery = doc.DocumentElement.SelectSingleNode("/order/delivery");

            ord.DeliveryTotal     = dat.AttributeValidation_Dec(xDelivery, "total");
            ord.DeliveryType      = dat.AttributeValidation_String(xDelivery, "type", 10);          //  10
            ord.DeliveryTerritory = dat.AttributeValidation_String(xDelivery, "territory", 5);      //  5
            ord.DeliveryId        = dat.AttributeValidation_Int(xDelivery, "deliveryid");           //  int
            ord.DeliveryEta       = dat.AttributeValidation_Date(xDelivery, "etd");
            ord.DeliveryEtd       = dat.AttributeValidation_Date(xDelivery, "eta");
            /// ----------------------------------------------------------------------
            //  Vat Section
            //  ----------------------------------------------------------------------
            XmlNode vat = doc.DocumentElement.SelectSingleNode("/order/vat");

            ord.VatTotal        = dat.AttributeValidation_Dec(vat, "total");                        //  dec
            ord.VatNumber       = dat.AttributeValidation_Int(vat, "number");                       //  int
            ord.VatCountyCode   = dat.AttributeValidation_String(vat, "countycode", 5);             //  5
            ord.VatDistrictRate = dat.AttributeValidation_String(vat, "districtrate", 20);          //  20
            ord.VatCityRate     = dat.AttributeValidation_String(vat, "cityrate", 20);              //  20
            ord.VatCountyRate   = dat.AttributeValidation_String(vat, "countyrate", 20);            //  20
            ord.VatStateRate    = dat.AttributeValidation_String(vat, "staterate", 20);             //  20
            ord.VatState        = dat.AttributeValidation_String(vat, "state", 2);                  //  2
            ord.VatCounty       = dat.AttributeValidation_String(vat, "county", 150);               //  150
            ord.VatCity         = dat.AttributeValidation_String(vat, "city", 150);                 //  150
            ord.VatStaticRate   = dat.AttributeValidation_String(vat, "staticrate", 20);            //  20
            ord.VatLiveRate     = dat.AttributeValidation_String(vat, "liverate", 20);              //  20
            ord.VatRate         = dat.AttributeValidation_String(vat, "rate", 20);                  //  20
            /// ----------------------------------------------------------------------
            //  Options Section
            //  ----------------------------------------------------------------------
            XmlNode options = doc.DocumentElement.SelectSingleNode("/order/options");

            ord.OptionsBlindPacking = dat.AttributeValidation_String(options, "blindpacking", 15);  //  int
            ord.OptionsCustRef      = dat.AttributeValidation_String(options, "custref", 50);       //  50
            /// ----------------------------------------------------------------------
            //  Payment Section
            //  ----------------------------------------------------------------------
            XmlNode payment = doc.DocumentElement.SelectSingleNode("/order/payment");

            ord.PaymentUsing    = dat.AttributeValidation_String(payment, "using", 50);             //  50
            ord.PaymentCardType = dat.SingleNodeValidation_Text(payment, "cardtype", 20);           //  Apr13-17    20
            ord.PaymentLastFour = dat.SingleNodeValidation_Text(payment, "lastfour", 4);            //  Apr13-17    4
            //  net Section
            XmlNode net = doc.DocumentElement.SelectSingleNode("/order/payment/net");

            ord.PaymentCurrency = dat.AttributeValidation_String(net, "currency", 5);               //  5
            string amt = dat.FirstChildValidation_Inner(net);

            ord.PaymentAmount = Decimal.Parse(amt);
            //  gross Section
            XmlNode gross = doc.DocumentElement.SelectSingleNode("/order/payment/gross");

            ord.GrossCurrency = gross.Attributes["currency"].Value;                             //  5
            string grossAmt = dat.FirstChildValidation_Inner(gross);

            ord.GrossAmount = Decimal.Parse(grossAmt);
            /// ----------------------------------------------------------------------
            /// Serialize object (WebOrder) to Json string
            /// Save Items List in Order Items List (include items / names within / name lines within)
            summary.nbiOrderSummary = ord;
            summary.nbiOrderItems   = nItems;
            //
            ord.Filename = fName + ".xml";
            //
            string test = Newtonsoft.Json.JsonConvert.SerializeObject(summary);

            //  =========== >
            DAL.SupportServices.SupportServices wsm = new DAL.SupportServices.SupportServices();
            /// ******************************************************************************
            /// Call Web Service - "WebOrder"
            /// <param name="json2">Include Header serialized + items seialized info.</param>
            /// <param name="fname">File to process name </param>
            /// <param name="type">File Type, determine what service to use (url)</param>
            /// <returns>"rStatus" true if WebService was processed, else false</returns>
            /// Web service url is defined in the App.Config file
            /// ------------------------------------------------------------------------------
            rStatus = wsm.ConsumeWebService(test, fName, syncRow.WebServiceOrders, syncRow);
            //rStatus = true;       // use only for testing purposes
            //  < ===========
            return(rStatus.IsOk);
        }
Beispiel #25
0
        /// *************************************************************************************************
        /// <summary>
        ///     09/22/2015 16:39 version
        ///     Website-Account Xml document is mapped to Object, then passed to WebServices as a JSON string.
        /// </summary>
        /// <param name="doc">Imported file content read as an XmlDocument</param>
        /// <param name="fName">File name (excluding path section)</param>
        /// <returns>Process status true if procees was completed ok, else false</returns>
        /// -------------------------------------------------------------------------------------------------
        bool IXmlFiles.ProcessWebsiteAccountFiles(XmlDocument doc, string fName, EtlTimer syncRow)
        {
            ServiceResponse rStatus = new ServiceResponse();
            //WebServiceManager wsm = new WebServiceManager();
            ///  ----------------------------------------------------------------------
            //  Account section
            ///  ----------------------------------------------------------------------            ///
            XmlNode    account = doc.DocumentElement.SelectSingleNode("/account");
            WebAccount ord     = new WebAccount();

            ord.OrderType = "nbi";
            ord.AccountId = dat.AttributeValidation_String(account, "accountid", 20);                   //  20
            ///  ----------------------------------------------------------------------
            //  Locale Section
            ///  ----------------------------------------------------------------------
            XmlNode locale = doc.DocumentElement.SelectSingleNode("/account/locale");

            ord.Language = dat.AttributeValidation_String(locale, "lang", 5);                           //  5
            ord.SiteUsed = dat.AttributeValidation_String(locale, "siteused", 10);                      //  10
            ord.Currency = dat.AttributeValidation_String(locale, "currency", 10);                      //  10
            ///  ----------------------------------------------------------------------
            //  Contact (account) section
            ///  ----------------------------------------------------------------------
            XmlNode contact = doc.DocumentElement.SelectSingleNode("/account/contact");

            ord.Email       = dat.SingleNodeValidation_Text(contact, "email", 60);                      //  60
            ord.Title       = dat.SingleNodeValidation_Text(contact, "title", 20);                      //  20
            ord.Forename    = dat.SingleNodeValidation_Text(contact, "forename", 70);                   //  70
            ord.Surname     = dat.SingleNodeValidation_Text(contact, "surname", 70);                    //  70
            ord.CompanyName = dat.SingleNodeValidation_Text(contact, "company", 300);                   //  300
            ord.Industry    = dat.SingleNodeValidation_Text(contact, "industry", 200);                  //  200
            ord.Telephone   = dat.SingleNodeValidation_Text(contact, "telephone", 30);                  //  30
            ///  ----------------------------------------------------------------------
            //  Address Section Process - (Cardholder)
            ///  ----------------------------------------------------------------------
            XmlNode cardHolder = doc.DocumentElement.SelectSingleNode("/account/address[@type='cardholder']");

            ord.AddressCardHolderTown     = dat.SingleNodeValidation_Text(cardHolder, "town", 150);      //  150
            ord.AddressCardHolderCounty   = dat.SingleNodeValidation_Text(cardHolder, "county", 150);    //  150
            ord.AddressCardHolderPostCode = dat.SingleNodeValidation_Text(cardHolder, "postcode", 30);   //  30
            ord.AddressCardHolderCountry  = dat.SingleNodeValidation_Text(cardHolder, "country", 200);   //  200
            //  Line section within Cardholder address section
            XmlNodeList xLt = cardHolder.SelectNodes("/account/address[@type='cardholder']/line");

            foreach (XmlNode xc in xLt)
            {
                int index = dat.AttributeValidation_Int(xc, "index");
                switch (index)
                {
                case 1:
                    ord.AddressCardHolderLine1 = xc.InnerText;              //  300
                    if (ord.AddressCardHolderLine1.Length > 300)
                    {
                        string txt = ord.AddressCardHolderLine1.Substring(0, 300);
                        ord.AddressCardHolderLine1 = txt;
                    }
                    break;

                case 2:
                    ord.AddressCardHolderLine2 = xc.InnerText;              //  300
                    if (ord.AddressCardHolderLine2.Length > 300)
                    {
                        string txt = ord.AddressCardHolderLine2.Substring(0, 300);
                        ord.AddressCardHolderLine2 = txt;
                    }
                    break;

                default:
                    break;
                }
            }
            ///  ----------------------------------------------------------------------
            //  Address Section - (Delivery)
            ///  ----------------------------------------------------------------------
            XmlNodeList delivery = doc.DocumentElement.SelectNodes("/account/address[@type='delivery']");

            foreach (XmlNode del in delivery)
            {
                /// Contact information within delivery address
                XmlNode delLine = del.SelectSingleNode("/account/address[@type='delivery']/contact");
                ord.AddressDeliveryForename  = dat.SingleNodeValidation_Text(delLine, "forename", 70);      //  70
                ord.AddressDeliverySurname   = dat.SingleNodeValidation_Text(delLine, "surname", 70);       //  70
                ord.AddressDeliveryTelephone = dat.SingleNodeValidation_Text(delLine, "telephone", 30);     //  70
                ///
                ord.AddressDeliveryCompany = dat.SingleNodeValidation_Text(del, "company", 300);            //  300
                /// Line section within Delivery address section
                XmlNodeList xnLine = del.SelectNodes("/account/address[@type='delivery']/line");
                foreach (XmlNode xd in xnLine)
                {
                    int index = dat.AttributeValidation_Int(xd, "index");
                    switch (index)
                    {
                    case 1:
                        ord.AddressDeliveryLine1 = xd.InnerText;                //  300
                        if (ord.AddressDeliveryLine1.Length > 300)
                        {
                            string txt = ord.AddressDeliveryLine1.Substring(0, 300);
                            ord.AddressDeliveryLine1 = txt;
                        }
                        break;

                    case 2:
                        ord.AddressDeliveryLine2 = xd.InnerText;                //  300
                        if (ord.AddressDeliveryLine2.Length > 300)
                        {
                            string txt = ord.AddressDeliveryLine2.Substring(0, 300);
                            ord.AddressDeliveryLine2 = txt;
                        }
                        break;

                    default:
                        break;
                    }
                }
                ord.AddressDeliveryTown     = dat.SingleNodeValidation_Text(del, "town", 150);              //  150
                ord.AddressDeliveryCounty   = dat.SingleNodeValidation_Text(del, "county", 150);            //  150
                ord.AddressDeliveryPostCode = dat.SingleNodeValidation_Text(del, "postcode", 30);           //  30
                ord.AddressDeliveryCountry  = dat.SingleNodeValidation_Text(del, "country", 200);           //  200
            }
            ord.FileName = fName + ".xml";

            string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(ord);

            /// ******************************************************************************
            /// Call Web Service    - "WebAccount"
            /// <param name="json2">Object serialized Json string.</param>
            /// <param name="fname">Xml file name </param>
            /// <param name="type">File Type (WebAccounts) </param>
            /// <returns>"rStatus" true if WebService was processed, else false</returns>
            /// Web service url is defined in the App.Config file
            /// ------------------------------------------------------------------------------
            rStatus = wsm.ConsumeWebService(json2, fName, syncRow.WebServiceAccounts, syncRow);
            //  <==============
            return(rStatus.IsOk);
        }
Beispiel #26
0
        /// <summary>
        ///     G&K Text files provide orders header and items information, each data line distribution [ PO_GK00.....txt ]
        ///     (data type and positioning) will depend in the type of record which is identified by tags
        ///     in the first position of each readed line.
        ///     Data is separated with , * or "," characters.
        ///     This process split data line into an string array and use the elements within the array
        ///     to retreive the corresponding fields. (they will depend in the line type in process)
        /// </summary>
        /// Old system ==> subImportTXTFile / subImportGKOrders
        public bool ProcessGKFiles(string path, string fileName, EtlTimer sync)
        {
            DAL.SupportServices.SupportServices wef = new DAL.SupportServices.SupportServices();

            //  bool resp = false;
            ServiceResponse resp = new ServiceResponse();

            string[] separators = { " , ", "*", "", "" };
            ///
            string line;
            bool   newFile = false;
            //bool newLine = true;
            GKHeader          order = new GKHeader();
            List <OrderItems> list  = new List <OrderItems>();

            /// ------------------------------------------------------------------------------
            /// Read the file and display it line by line.
            /// ------------------------------------------------------------------------------
            try
            {
                System.IO.StreamReader file = new System.IO.StreamReader(path);
                while ((line = file.ReadLine()) != null)
                {
                    line = line.Replace('"', ' ').Replace('-', ' ');
                    ///
                    string[] words = line.Split(separators, StringSplitOptions.None);
                    if (words[0] == "BG")
                    {
                        newFile = true;
                    }
                    string tag = words[0].TrimStart();
                    /// -------------------------------------------------------------------------------
                    /// Process header information
                    /// -------------------------------------------------------------------------------
                    if ((tag == "AAA0") || (tag == "POH0") || (tag == "POH1") && (newFile))
                    {
                        switch (tag)
                        {
                        case "AAA0":
                            string date = words[2].Substring(0, 4) + "-" + words[2].Substring(4, 2) + "-" + words[2].Substring(6, 2) + " " +
                                          words[3].Substring(0, 2) + ":" + words[3].Substring(2, 2) + ":" + words[3].Substring(4, 2);     // ok
                            order.OrderDate = DateTime.ParseExact(date, "yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture);
                            break;

                        case "POH0":
                            order.PO      = words[1];                                                                                   //  ok
                            order.UserID  = words[2];                                                                                   //  ok
                            order.DateReq = words[3].Substring(0, 4) + "-" + words[3].Substring(4, 2) + "-" + words[3].Substring(6, 2); //  ok
                            break;

                        case "POH1":
                            order.ID           = order.PO;      //  ok
                            order.ShippingToID = "";
                            order.Description  = words[1];      //  ok
                            order.UserEmail    = words[2];      //  ok
                            order.UserID       = "";
                            if (order.UserID == "0096")
                            {
                                order.UserID = "0596";
                            }
                            if ((order.UserID == "000000302871") || (order.UserID == "000000302863") || (order.UserID == "000000306101") ||
                                (order.UserID == "000000316854") || (order.UserID == "000000316891"))
                            {
                                order.ShippingViaID = "PL";
                            }
                            else
                            {
                                order.ShippingViaID = "10";
                            }
                            //
                            break;

                        default:
                            break;
                        }
                    }
                    /// -------------------------------------------------------------------------------
                    /// Process order items tags
                    /// -------------------------------------------------------------------------------
                    else if ((tag == "POD0") && (newFile))
                    {
                        //newLine = true;
                        ///
                        LineNo      = Int32.Parse(words[1]);
                        SeqNo       = words[3];
                        Qty         = Int32.Parse(words[6]);
                        EmblemPrice = Int32.Parse(words[7]);
                    }
                    else if ((tag == "POD1") && (newFile))
                    {
                        //complete = true;
                        //newLine = true;
                        OrderItems ordItms = BuildPod0(words, order.UserID);
                        list.Add(ordItms);
                    }
                    /// If this is not a valid file - terminate the process
                    if (!newFile)
                    {
                        throw new Exception();
                    }
                }
                order.items = list;

                string json = Newtonsoft.Json.JsonConvert.SerializeObject(order);
                //Console.WriteLine("Text process ok");
                //Console.ReadLine();
                file.Close();
                /// ******************************************************************************
                /// Call Web Service
                /// <param name="json2">Include Header serialized + items seialized info.</param>
                /// <param name="fname">File to process name </param>
                /// <param name="type">File Type, determine what service to use (url)</param>
                /// <param name="pStatus">Data status</param> Ignore
                /// <returns>"rStatus" true if WebService was processed, else false</returns>
                /// Web service url is defined in the App.Config file
                /// ------------------------------------------------------------------------------
                ///
                resp = wsm.ConsumeWebService(json, fileName, "GKOrders", sync);
                //  <==============
            }
            catch (Exception e)
            {
                /// Process errors
                //Console.WriteLine("Text process error");
                //Console.ReadLine();

                /// error while reading the file
                //process = false;
                resp.IsOk = false;
                ServiceResponse errMsg = new ServiceResponse();
                errMsg.FileType   = "1";    //  Set Nis Type
                errMsg.FileName   = fileName + ".txt";
                errMsg.NISOrderId = "0";
                errMsg.Status     = "Not Processed";
                errMsg.Message    = e.Message + " in line "; // +lineCounter;
                /// Send Message to WebService
                wef.WriteErrorFile(errMsg, sync);
            }

            return(resp.IsOk);
        }
Beispiel #27
0
        DAL.SupportServices.SupportServices wsm = new DAL.SupportServices.SupportServices();  //  Set WebService methods pointer

        /// <summary>
        ///     Process WE text files, built an object, generate a Json string and submit it to the
        ///     webServices. [ WE XML Order.txt ]
        ///     If any processing errors are detected, the corresponding message is send to WebServices
        /// </summary>
        /// <param name="path">The complete path to the file in process</param>
        /// <param name="fileName">File name without the extension</param>
        /// <returns>Process result in a boolean var. if OK (true) else (false) </returns>
        public bool ProcessWEFiles(string path, string fileName, EtlTimer sync)
        {
            bool head = false;       /// Header info detection flag
            bool det  = false;       /// Detail info detection flag
            //bool resp = false;        /// Process final status return flag
            ServiceResponse resp    = new ServiceResponse();
            bool            process = true; /// control that process was completed ok
            ///
            int itemsCounter = 0;           /// Detail items counter
            int lineCounter  = 0;           /// Count the number of rows(records) in file
            ///
            string line;

            string[] separators = { "=", "_" };
            ///
            WEFiles        weFiles = new WEFiles();
            List <WEItems> items   = new List <WEItems>();

            //WriteErrorFile wef = new WriteErrorFile();
            DAL.SupportServices.SupportServices wef = new DAL.SupportServices.SupportServices();
            /// ---------------------------------------------------------------------------
            /// Read the file line by line.
            /// ---------------------------------------------------------------------------
            System.IO.StreamReader file = new System.IO.StreamReader(path);
            try
            {
                while ((line = file.ReadLine()) != null)
                {
                    /// Count lines in file
                    lineCounter++;
                    /// Split input record into string array elements
                    string[] words = line.Split(separators, StringSplitOptions.None);
                    /// -------------------------------------------------------------------
                    /// Only one element found in record <element 0>
                    /// Identify is Header or detail tags come after this element
                    /// -------------------------------------------------------------------
                    if (words.Count() == 1)
                    {
                        if (words[0] == "[Order Header]")
                        {
                            head = true;        /// Set header section detected flag on
                            continue;
                        }
                        else if (words[0] == "[Order Detail]")
                        {
                            det  = true;        /// set Deatil section detected flag on
                            head = false;       /// Header detected off
                            continue;
                        }
                        else if (words[0] == "")
                        {
                            continue;           /// Ignore blank records
                        }
                        throw new Exception("Unrecognized content");
                    }
                    /// -------------------------------------------------------------------
                    /// Two elements found in record <tag name> = <tag value>
                    /// Header flag on. validate against Header tags
                    /// Is not a detail record
                    /// -------------------------------------------------------------------
                    if (head && !det && words.Count() == 2)
                    {
                        /// Build Header object from data file
                        switch (words[0])
                        {
                        case "MacolaUserID":
                            weFiles.MacolaUserID = words[1];
                            break;

                        case "UserEmail":
                            weFiles.UserEmail = words[1].TrimStart();
                            break;

                        case "OrderDate":
                            weFiles.OrderDate = words[1].TrimStart();
                            break;

                        case "PO":
                            weFiles.PO = words[1].TrimStart();
                            break;

                        case "ImportType":
                            weFiles.ImportType = words[1].TrimStart();
                            break;

                        case "TotalItemsNo":
                            if (!string.IsNullOrEmpty(words[1]))
                            {
                                weFiles.TotalItemsNo = Int32.Parse(words[1]);
                            }
                            break;

                        default:
                            //  throw error
                            throw new Exception("Unrecognized header tag name");
                        }
                    }
                    /// -------------------------------------------------------------------
                    /// Three elements found in record:
                    ///     <tag name> = <detail record count> = <tag value>
                    /// Detail flag on. validate against detail tags
                    /// -------------------------------------------------------------------
                    else if (det && words.Count() == 3)
                    {
                        int itm = Int32.Parse(words[1]);
                        if (itm > itemsCounter)
                        {
                            /// Add new empty() line object into Items list
                            /// All new data entry values will be stored in the empty line.
                            /// ============= >
                            items.Add(AddWEItemToList());
                            /// < =============
                            /// Count items in List
                            itemsCounter++;
                        }
                        switch (words[0])
                        {
                        case "Qty":
                            items[itemsCounter - 1].Qty = words[2];
                            break;

                        case "Line1":
                            items[itemsCounter - 1].Line1 = words[2];
                            break;

                        case "Line2":
                            items[itemsCounter - 1].Line2 = words[2];
                            break;

                        case "Line3":
                            items[itemsCounter - 1].Line3 = words[2];
                            break;

                        case "ItemClientCode":
                            items[itemsCounter - 1].ItemClientCode = words[2];
                            break;

                        case "ItemClientCodeDescription":
                            items[itemsCounter - 1].ItemClientCodeDescription = words[2];
                            break;

                        case "ItemWECode":
                            items[itemsCounter - 1].ItemWECode = words[2];
                            break;

                        case "PriorityID":
                            items[itemsCounter - 1].PriorityID = words[2];
                            break;

                        case "Type":
                            items[itemsCounter - 1].Type = words[2];
                            break;

                        case "Instructions1":
                            items[itemsCounter - 1].Instructions1 = words[2];
                            break;

                        case "Instructions2":
                            items[itemsCounter - 1].Instructions2 = words[2];
                            break;

                        case "Instructions3":
                            items[itemsCounter - 1].Instructions3 = words[2];
                            break;

                        case "Instructions4":
                            items[itemsCounter - 1].Instructions4 = words[2];
                            break;

                        default:
                            //  throw error
                            throw new Exception("Unrecognized detail tag name");
                        }
                    }
                    else
                    {
                        /// throw error - unrecognized data line (lineCounter)
                        throw new Exception("Invalid data format");
                    }
                }
            }
            catch (Exception e)
            {
                /// error while reading the file
                process   = false;
                resp.IsOk = false;
                ServiceResponse errMsg = new ServiceResponse();
                errMsg.FileType   = "1";    //  Set Nis Type
                errMsg.FileName   = fileName + ".txt";
                errMsg.NISOrderId = "0";
                errMsg.Status     = "Not Processed";
                errMsg.Message    = e.Message + " in line " + lineCounter;
                /// Send Message to WebService
                wef.WriteErrorFile(errMsg, sync);
            }
            file.Close();
            /// Only if process is completed ok and the number of detail records expected
            /// match the number of records read the object is serialized and send to the
            /// corresponding Web Service
            if (process)
            {
                if (items.Count() == itemsCounter)
                {
                    weFiles.OrderDetail = items;
                    resp.IsOk           = true;
                }
                string json = Newtonsoft.Json.JsonConvert.SerializeObject(weFiles);
                /// ******************************************************************************
                /// Call Web Service
                /// <param name="json2">Include Header serialized + items seialized info.</param>
                /// <param name="fname">File to process name </param>
                /// <param name="type">File Type, determine what service to use (url)</param>
                /// <returns>"rStatus" true if WebService was processed, else false</returns>
                /// Web service url is defined in the App.Config file
                /// ------------------------------------------------------------------------------
                ///
                resp = wsm.ConsumeWebService(json, fileName, "WEOrders", sync);
                //  <==============
            }
            return(resp.IsOk);
        }
        /// *************************************************************************************************
        /// <summary>
        ///     07/27/2017 11:27 version
        ///     NIS Orders process, Order data come as an object splited into order header/detail sections.
        ///     Each section is send to WebServices as a JSON string if header/detail information is complete,
        ///     when detail info.
        ///     All errors are send to a Webservice (Error) and included in the Service log.
        /// </summary>
        /// <param name="doc">Imported order content as a NisTables class</param>
        /// <param name="oNumber">Order number</param>
        /// <param name="fName">EtlTimer sync control data)</param>
        /// <returns>Process status true if procees was completed ok, else false</returns>
        /// -------------------------------------------------------------------------------------------------
        bool INISTables.ProcessNisOrder(NisTables doc, int oNumber, EtlTimer syncRow)
        {
            /// Response from MW api
            ServiceResponse rStatus = new ServiceResponse();

            DAL.SupportServices.SupportServices       wsm = new DAL.SupportServices.SupportServices(); //  Set WebService methods pointer
            DAL.ImportControl.ImportControlRepository icr = new DAL.ImportControl.ImportControlRepository();
            ///  Create error message object and initialice it
            ServiceResponse errMsg = new ServiceResponse();

            errMsg.FileType   = "1";    //  Set Nis Type
            errMsg.FileName   = "NIS Table";
            errMsg.NISOrderId = oNumber.ToString();
            errMsg.Status     = "Not Processed";
            errMsg.Message    = "No items found for this order header";
            /// *********************************************************************************************
            //  Order header section
            /// ---------------------------------------------------------------------------------------------
            string jsonHead = "{ \"nisOrderSummary\":" + Newtonsoft.Json.JsonConvert.SerializeObject(doc.header);

            /// *********************************************************************************************
            ///  Order Detail Section
            ///  --------------------------------------------------------------------------------------------
            /// ===============================================================================
            /// Send Imported files data content to webServices - information must be complete
            /// Order Header + all related Order Items.
            /// -------------------------------------------------------------------------------
            if (doc.items.Count > 0)
            {
                /// Serialize Items list and complete json string for Header and Items
                string json2 = jsonHead + ", \"nisOrderItems\" : " + Newtonsoft.Json.JsonConvert.SerializeObject(doc.items) + "}";
                /// ******************************************************************************
                /// Call Web Service
                /// <param name="json2">        Header/detail object Json serialized string.</param>
                /// <param name="fname">        Xml file name </param>
                /// <param name="syncRow.WebServiceOrders">File Type, route to web service(url)</param>
                /// <param name="syncRow">      EtlTimer control data.
                /// <returns>"rStatus" true if WebService was processed, else false</returns>
                /// *** Web service url is defined in the App.Config file key 'NisOrder'.
                /// ------------------------------------------------------------------------------
                /// ==============> save order data through the defined web service
                rStatus = wsm.ConsumeWebService(json2, oNumber.ToString(), syncRow.WebServiceOrders, syncRow);   //"OrderData", syncRow); //// TEMPORARY UNCOMMENT TO SEND JSON INFO
                ///
                //rStatus.IsOk = true;          /// set order process to ok TEMPORARY, UNCOMMENT IF WEB SERVICE IS USED TO SEND JSON INFO
                ///
                string apiMsg   = "";
                int    resp     = 0;            ///  Order update response
                int    uOption  = 0;
                int    impProb  = 0;
                int    navOrder = 0;
                DAL.ImportControl.ImportControlRepository ikr = new DAL.ImportControl.ImportControlRepository();
                DAL.ImportControl.ImportNISRepository     inr = new DAL.ImportControl.ImportNISRepository();
                //
                if (rStatus.Status == "OK")
                {   //  set order condition to imported
                    apiMsg       = " Imported";
                    uOption      = 1;
                    rStatus.IsOk = true;
                    navOrder     = Convert.ToInt32(rStatus.NISOrderId);
                    ///
                    /// Save processed files log - May16-2017
                    ///
                    int res = ikr.writeImportLog(syncRow.MwEtlTimerId, "NIS", doc.header.HeaderId.ToString());
                }
                else
                {   //  Set order contion to imported with errors.
                    impProb      = 1;
                    apiMsg       = " Not Imported - API errors";
                    rStatus.IsOk = false;
                }
                resp = inr.updNisOrder(oNumber, uOption, impProb, navOrder);   // ************  MUST UPDATE NIS ORDER    *******************
                //
                string ret = ikr.writeSyncLog(1, syncRow.MwEtlTimerId, 1, syncRow.ServiceName, "> " + syncRow.Description + " NIS Order: <" + doc.header.HeaderId + "> " + apiMsg + ".");
                //  <==============
                //  <==============
            }
            else
            {   /// Incomplete order (No order items included and no xls file Name reported in orderHeader)
                jsonHead = jsonHead + " }";
                /// Send Message to WebService
                wsm.WriteErrorFile(errMsg, syncRow);    //// TEMPORARY UNCOMMENT TO SEND JSON INFO
            }
            return(rStatus.IsOk);
        }
        /// *************************************************************************************************
        /// <summary>
        ///     07/06/2017 10:23 version
        ///     Catalog Web Orders process, un-imported web orders are retreived and  mapped to an object (header/detail
        ///     sections).
        ///     Each section is send to WebServices as a JSON string if header/detail information is complete,
        ///     when detail info.
        ///     All errors are send to a Webservice (Error) and included in the Service log.
        /// </summary>
        /// <param name="doc">Imported Web orders</param>
        /// <param name="oNumber">Web Order number</param>
        /// <param name="syncRow">EtlTimer sync control data)</param>
        /// <returns>Process status true if procees was completed ok, else false</returns>
        /// -------------------------------------------------------------------------------------------------
        bool IDesignRequestTables.ProcessDesignRequestOrder(DesignRequest doc, string oNumber, EtlTimer syncRow)
        {
            //bool rStatus = false;                    //  WebService return status (default=false)
            ServiceResponse rStatus = new ServiceResponse();

            Dictionary <string, string> configValues = new Dictionary <string, string>();

            FTPServerIP = ConfigurationManager.AppSettings["FTPServerIP"];              //  configValues[ConfigurationValues.FTP_SERVER_IP];
            FTPUserID   = ConfigurationManager.AppSettings["FTPUserID"];                //  configValues[ConfigurationValues.FTP_USER_ID];
            FTPPassword = ConfigurationManager.AppSettings["FTPPassword"];              //  configValues[ConfigurationValues.FTP_PASSWORD];

            // ClientArtImagesFolderSource = syncRow.ExcelFileFolder;
            ClientArtImagesFolderDestination = syncRow.ProcessedFileFolder;

            ///  Create error message object and initialice it
            ServiceResponse errMsg = new ServiceResponse();

            errMsg.FileType   = "1";    //  Set Nis Type
            errMsg.FileName   = "Catalog Design Request Table";
            errMsg.NISOrderId = oNumber.ToString();
            errMsg.Status     = "Not Processed";
            errMsg.Message    = "Design request not found";
            /// *********************************************************************************************
            //  Design request order
            /// ---------------------------------------------------------------------------------------------
            /// ===============================================================================
            /// Send Imported files data content to webServices - information must be complete
            /// Order Header + all related Order Items.
            /// -------------------------------------------------------------------------------
            if (doc != null)
            {
                /// ******************************************************************************
                /// Call Web Service
                /// <param name="json2">        Header/detail object Json serialized string.</param>
                /// <param name="fname">        Xml file name </param>
                /// <param name="syncRow.WebServiceOrders">File Type, route to web service(url)</param>
                /// <param name="syncRow">      EtlTimer control data.
                /// <returns>"rStatus.IsOk" true if WebService was processed, else false</returns>
                /// *** Web service url is defined in the App.Config file key 'NisOrder'.
                /// ------------------------------------------------------------------------------
                ///
                /// Process design Request image
                ///
                string errorMessage = " ";
                rStatus.IsOk = ProcessDesignRequestImage(doc, out errorMessage); // , errorMessage);
                ///
                string apiMsg = "";
                int    resp   = 0;          //  Order update response
                //
                string json2 = "{ \"WebOrderSummary\":" + Newtonsoft.Json.JsonConvert.SerializeObject(doc) + "}";
                if (rStatus.IsOk)
                {
                    /// ==============> save order data through the defined web service
                    ///  rStatus = wsm.ConsumeWebService(json2, oNumber, syncRow.WebServiceOrders, syncRow);   //"OrderData", syncRow); //// TEMPORARY UNCOMMENT TO SEND JSON INFO
                    /// ------------------------------------------------------------------------------
                    ///     UNCOMMENT IF WEB SERVICE IS USED TO SEND JSON INFO
                    //rStatus.IsOk = true;         /// set order process to ok TEMPORARY,
                    rStatus.NISOrderId = "Nav1234567";
                    /// ------------------------------------------------------------------------------
                    if (rStatus.IsOk)
                    {   //  set order condition to imported
                        apiMsg = " Imported";
                        // resp = idr.updDesignRequest(oNumber, "Imported", 1);
                        if (resp < 1)
                        {
                            apiMsg += " but Design Request status not updated due to DB access errors.";
                        }
                    }
                    else
                    {   //  Set order contion to imported with errors.
                        apiMsg = " Not Imported - API errors" + " Image errors: " + errorMessage;
                    }
                }
                string ret = ikr.writeSyncLog(1, syncRow.MwEtlTimerId, 1, syncRow.ServiceName, "> " + syncRow.Description + " Catalog Web Order: <" + doc.DesignId + "> " + apiMsg + ".");
                //  <==============
            }
            else
            {   /// Incomplete order (No order items included and no xls file Name reported in orderHeader)
                //json2 = json2 + " }";
                /// Send Message to WebService
                wsm.WriteErrorFile(errMsg, syncRow);    //// TEMPORARY UNCOMMENT TO SEND JSON INFO
            }
            return(rStatus.IsOk);
        }
        /// *************************************************************************************************
        /// <summary>
        ///     11/03/2015 10:23 version
        ///     NIS Files process, Xml document mapped to an object and splited into order header/detail
        ///     sections.
        ///     Each section is send to WebServices as a JSON string if header/detail information is complete,
        ///     when detail info. is not included in the xml document, it must have an excel file associated
        ///     with the detail information (Header filename field).
        ///     All errors are send to a Webservice (Error) and included in the Service log.
        /// </summary>
        /// <param name="doc">Imported file content read as an XmlDocument</param>
        /// <param name="fName">File name (excluding path section)</param>
        /// <param name="fName">EtlTimer sync control data)</param>
        /// <returns>Process status true if procees was completed ok, else false</returns>
        /// -------------------------------------------------------------------------------------------------
        bool IXmlFiles.ProcessNisFiles(XmlDocument doc, string fName, EtlTimer syncRow)
        {
            //bool rStatus = false;                    //  WebService return status (default=false)
            ServiceResponse rStatus = new ServiceResponse();

            DAL.SupportServices.SupportServices       wsm = new DAL.SupportServices.SupportServices(); //  Set WebService methods pointer
            DAL.DataValidationServices.DataValidation dvs = new DAL.DataValidationServices.DataValidation();

            ///  Create error message object and initialice it
            ServiceResponse errMsg = new ServiceResponse();

            errMsg.FileType   = "1";    //  Set Nis Type
            errMsg.FileName   = fName + ".xml";
            errMsg.NISOrderId = "0";
            errMsg.Status     = "Not Processed";
            errMsg.Message    = "No items found for this order header";
            /// *********************************************************************************************
            //  Order header section
            /// ---------------------------------------------------------------------------------------------
            XmlNode header = doc.DocumentElement.SelectSingleNode("/Order/OrderHeader");
            Header  head   = new Header();

            ///
            head.HeaderId            = dvs.SingleNodeValidation_Text(header, "ID", 6);
            head.HeaderUserId        = dvs.SingleNodeValidation_Text(header, "userID", 6);
            head.HeaderUserEmail     = dvs.SingleNodeValidation_Text(header, "UserEmail", 60);
            head.HeaderOrderDate     = dvs.SingleNodeValidation_Text(header, "orderDate", 30);
            head.HeaderPO            = dvs.SingleNodeValidation_Text(header, "PO", 25);
            head.HeaderDateRequested = dvs.SingleNodeValidation_Text(header, "dateReq", 30);
            head.HeaderDescription   = dvs.SingleNodeValidation_Text(header, "description", 0);
            head.HeaderShipVia1      = dvs.SingleNodeValidation_Text(header, "shippingViaID", 2);
            head.HeaderShipVia2      = dvs.SingleNodeValidation_Text(header, "shippingViaID2", 2);
            head.HeaderShipToId1     = dvs.SingleNodeValidation_Text(header, "shippingToID", 0);
            head.HeaderShipToId2     = dvs.SingleNodeValidation_Text(header, "shippingToID2", 0);
            head.HeaderComments      = dvs.SingleNodeValidation_Text(header, "comments", 0);
            head.FileName            = dvs.SingleNodeValidation_Text(header, "ItemsFileName", 0);
            head.HeaderSentDate      = dvs.SingleNodeValidation_Text(header, "sentDate", 30);
            ///
            string jsonHead = "{ \"nisOrderSummary\":" + Newtonsoft.Json.JsonConvert.SerializeObject(head);
            /// *********************************************************************************************
            ///  Order Detail Section
            ///  --------------------------------------------------------------------------------------------
            XmlNodeList orders = doc.DocumentElement.SelectNodes("/Order/OrderItems");
            ///
            List <Order> ordList = new List <Order>();
            int          itm     = 1;

            foreach (XmlNode order in orders)
            {
                Order ord = new Order();
                ord.NisOrderId  = itm.ToString();
                ord.Itemid      = dvs.SingleNodeValidation_Text(order, "ID", 6);;
                ord.OrderId     = dvs.SingleNodeValidation_Text(order, "orderID", 6);
                ord.SkuId       = dvs.SingleNodeValidation_Text(order, "SKU_ID", 3);
                ord.LineId      = dvs.SingleNodeValidation_Int(order, "lineID");
                ord.Quantity1   = dvs.SingleNodeValidation_Int(order, "qty1");
                ord.Quantity2   = dvs.SingleNodeValidation_Int(order, "qty2");
                ord.Line1       = dvs.SingleNodeValidation_Text(order, "line1", 40);
                ord.Line2       = dvs.SingleNodeValidation_Text(order, "line2", 40);
                ord.Line3       = dvs.SingleNodeValidation_Text(order, "line3", 40);
                ord.Comment     = dvs.SingleNodeValidation_Text(order, "comment", 100);
                ord.Description = dvs.SingleNodeValidation_Text(order, "description", 0);
                ord.SkuClient   = dvs.SingleNodeValidation_Text(order, "SKU_client", 0);
                ord.SkuWe       = dvs.SingleNodeValidation_Text(order, "SKU_WE", 30);
                ord.AccountCode = dvs.SingleNodeValidation_Text(order, "AccountCode", 0);
                ///
                itm++;
                ordList.Add(ord);
            }
            /// ===========================================================================================
            /// When an Order don't include items, order items must be provided through an xls / xlsx file
            /// indicated in the Header "FileName" field.
            /// If fileName is not indicated/provided, the corresponding order must remain pending in the
            /// problem directory until it can be processed, an entry in the ServiceLog must be generated
            /// to report this situation and a WebService error message is send.
            /// Old system ==> subImportXLSFile
            /// -------------------------------------------------------------------------------------------
            if (ordList.Count == 0)
            {
                if (String.IsNullOrEmpty(head.FileName))
                {
                    /// Incomplete order (No order items included and no xls file Name reported in orderHeader)
                    errMsg.Message = "No items in xml file and no xls file reported in Header (fileName)";
                }
                else
                {
                    /// ===================================================================================================
                    /// read xls file using Header FileName, build order items List and add it to header section.
                    /// ----------------------------------------------------------------------------------------------------
                    //  string path = ConfigurationManager.AppSettings["ExcelFilesDirectory"].ToString() + @"\" + head.FileName;
                    string    path = syncRow.ExcelFileFolder + @"\" + head.FileName;
                    DataTable dt   = ImportProcedure_NIS.ExcelFiles.ImportProcess.ReadExcelFile(path, "Items", "*", head.FileName, false);
                    ///
                    if ((dt == null) || (dt.Rows.Count == 0))
                    {   /// Incomplete order (associated xls file name was not found)
                        errMsg.Message = "Associated xls/xlsx file <" + head.FileName + "> not found";
                        /// -------------------------------------------------------------------------
                    }
                    else
                    {   /// Built items list from xls/xlsx file content
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            string it = Convert.ToString(dt.Rows[i].ItemArray[5]);
                            if (!String.IsNullOrEmpty(it))
                            {
                                /// All empty rows Qty(G) are ignored, when current row is empty the process
                                /// continue. Associated file may have additional filled rows that must be
                                /// included.
                                Order ord = new Order();
                                /// process all existing items
                                ord.NisOrderId = head.HeaderId;         //  Header file name
                                ord.Itemid     = string.Empty;
                                ord.OrderId    = head.HeaderId;
                                ord.SkuId      = (i + 1).ToString();
                                /// Quantity Qty1/Qty2 nodes
                                int  q1;
                                bool n = Int32.TryParse(dt.Rows[i].ItemArray[5].ToString(), out q1);
                                ord.Quantity1 = q1;                                 //  ok
                                ord.Quantity2 = 0;                                  //  ok
                                /// Line Line1-line3 nodes
                                ord.Line1 = dt.Rows[i].ItemArray[2].ToString();     //  ok
                                ord.Line2 = dt.Rows[i].ItemArray[3].ToString();     //  ok
                                ord.Line3 = dt.Rows[i].ItemArray[4].ToString();     //  ok
                                /// This counter must be after storing Line1 .. Line3
                                /// Conts the number of lines included in this row.
                                ord.LineId = 0;
                                if (!string.IsNullOrEmpty(ord.Line1))
                                {
                                    ord.LineId++;
                                }
                                if (!string.IsNullOrEmpty(ord.Line2))
                                {
                                    ord.LineId++;
                                }
                                if (!string.IsNullOrEmpty(ord.Line3))
                                {
                                    ord.LineId++;
                                }
                                ///
                                ord.Comment     = dt.Rows[i].ItemArray[7].ToString(); //  ok
                                ord.Description = "";
                                ord.SkuClient   = dt.Rows[i].ItemArray[1].ToString();
                                ord.SkuWe       = dt.Rows[i].ItemArray[0].ToString();
                                /// Add row in detail list
                                ordList.Add(ord);
                            }
                        }
                    }
                }
            }
            /// ===============================================================================
            /// Send Imported files data content to webServices - information must be complete
            /// Order Header + all related Order Items.
            /// -------------------------------------------------------------------------------
            if (ordList.Count > 0)
            {
                /// Serialize Items list and complete json string for Header and Items
                string json2 = jsonHead + ", \"nisOrderItems\" : " + Newtonsoft.Json.JsonConvert.SerializeObject(ordList) + "}";
                /// ******************************************************************************
                /// Call Web Service
                /// <param name="json2">        Header/detail object Json serialized string.</param>
                /// <param name="fname">        Xml file name </param>
                /// <param name="syncRow.WebServiceOrders">File Type, route to web service(url)</param>
                /// <param name="syncRow">      EtlTimer control data.
                /// <returns>"rStatus" true if WebService was processed, else false</returns>
                /// *** Web service url is defined in the App.Config file key 'NisOrder'.
                /// ------------------------------------------------------------------------------
                /// ==============> save order data through the defined web service
                rStatus = wsm.ConsumeWebService(json2, fName, syncRow.WebServiceOrders, syncRow);   //"OrderData", syncRow);
                //  <==============
            }
            else
            {   /// Incomplete order (No order items included and no xls file Name reported in orderHeader)
                jsonHead = jsonHead + " }";
                /// Send Message to WebService
                rStatus.IsOk = false;
                wsm.WriteErrorFile(errMsg, syncRow);
            }
            return(rStatus.IsOk);
        }