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); } }
/// ***************************************************************************************** /// 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); } }
/// ***************************************************************************************** /// 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); } }
/// ***************************************************************************************** /// 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> /// 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); }
/// ******************************************************************************************* /// <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 + "."); }
/// ************************************************************************************************* /// <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> /// 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); }
/// ************************************************************************************************* /// <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); }
/// ************************************************************************************** /// 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); } }