public void SendEmailMessage(string strMessage) { try { MailMessage mail = new MailMessage(); SmtpClient smtpServer = new SmtpClient(); CFDispatchTrackApplicationSettings loAppSettings = new CFDispatchTrackApplicationSettings(); smtpServer.Host = loAppSettings.Get("SMTPServerAddress"); smtpServer.Port = Convert.ToInt32(loAppSettings.Get("SMTPServerPort")); smtpServer.Credentials = new System.Net.NetworkCredential("barcode1", "Barcode1"); mail.From = new MailAddress(loAppSettings.Get("NotificationEmailAddressFrom")); mail.To.Add(loAppSettings.Get("NotificationEmailAddressTo")); mail.Subject = "RoadNetWebService Interface Program"; mail.Body = strMessage; //smtpServer.EnableSsl = true; smtpServer.Send(mail); smtpServer.Dispose(); } catch (Exception ex) { WriteEventToWindowsLog("RoadNetWebServiceInterface", ex.ToString(), false, 5); } }
private void bgwUpdateDTDrivers_DoWork(object sender, DoWorkEventArgs e) { var lbValidate = false; var tokenSource = new CancellationTokenSource(); try { if (DtSelectedDate < DateTime.Today) { DialogResult lcValidationResult = MessageBox.Show("Are you sure you want to update drivers for a date prior the current date?\r\nPlease press YES to continue.", "Action Confirmation Request", MessageBoxButtons.YesNo); if (lcValidationResult == DialogResult.Yes) { lbValidate = true; } } else { DialogResult lcValidationResult = MessageBox.Show("Drivers information will be send to Dispatch Track for " + DtSelectedDate.ToString("MM/dd/yyyy") + ".\r\nPlease press YES to continue.", "Action Confirmation Request", MessageBoxButtons.YesNo); if (lcValidationResult == DialogResult.Yes) { lbValidate = true; } } if (lbValidate == true) { DataAccess dataAccess = new DataAccess(); string processCode = ProcessCode.DRIVERS.ToString(); int currentProcessId; if (dataAccess.CreateProcess(processCode, out currentProcessId)) { var token = tokenSource.Token; RunProcessLogs(token, processCode, currentProcessId); CFDispatchTrackApplicationSettings loAppSettings = new CFDispatchTrackApplicationSettings(); string apiHost = loAppSettings.Get("DispatchTrackAPIHost"); string apiPort = loAppSettings.Get("DispatchTrackAPIPort"); string apiImportDrivers = loAppSettings.Get("DispatchTrackUpdateDrivers"); string requestDate = DtSelectedDate.ToString("yyyyMMdd"); string url = apiHost + (apiPort.Trim().Length > 0 ? ":" + apiPort : "") + apiImportDrivers + requestDate + "/" + currentProcessId; string reply = NodeAPI.UpdateDriversInformation(url); //MessageBox.Show(reply); MessageBox.Show("Update Drivers process complete."); } else { MessageBox.Show("Error while creating the process."); } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } Thread.Sleep(1000); tokenSource.Cancel(); //this change the value of token.IsCancellationRequested from 'false' to 'true', stopping the while loop in method ProcessLogs }
public void GetValues() { this.txtEmailFrom.Text = loAppSettings.Get("NotificationEmailAddressFrom"); this.txtEmailTo.Text = loAppSettings.Get("NotificationEmailAddressTo"); this.txtDispatchTrackURL.Text = loAppSettings.Get("DispatchTrackAPIHost"); this.txtDispatchTrackPort.Text = loAppSettings.Get("DispatchTrackAPIPort"); this.txtDispatchTrackImportOrder.Text = loAppSettings.Get("DispatchTrackImportOrders"); this.txtDispatchTrackExportOrder.Text = loAppSettings.Get("DispatchTrackExportOrders"); this.txtDispatchTrackGetOrderInfo.Text = loAppSettings.Get("DispatchTrackGetOrdersInfo"); this.txtDispatchTrackUpdateDriver.Text = loAppSettings.Get("DispatchTrackUpdateDrivers"); this.txtDispatchTrackUpdateRouteHist.Text = loAppSettings.Get("DispatchTrackUpdateRouteOHist"); this.txtDispatchTrackDateBeforeExport.Text = loAppSettings.Get("DispatchTrackCheckDataBeforeExporting"); }
public static string UpdateDriversInformation(string url) { CFDispatchTrackApplicationSettings loAppSettings = new CFDispatchTrackApplicationSettings(); try { int connectionTimeOut = int.Parse(loAppSettings.Get("DispatchTrackAPIPortTimeOutMinutes")); HttpClient client = new HttpClient(); client.Timeout = new TimeSpan(0, connectionTimeOut, 0); HttpResponseMessage response = client.GetAsync(url).Result; if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync().Result; dynamic json = JsonConvert.DeserializeObject(result); return(json.message); //string error = json.error; // return error.Trim().Length == 0; } return(response.ReasonPhrase.ToString()); } catch (Exception e) { return(e.Message.ToString()); } }
/// <summary> /// Get full orders information from dispatch track using the route /// http://host:port/dispatchtrack/get/routeinfo/warehouse_id/date/session_id /// </summary> /// <returns></returns> public static object GetFullOrdersDataFromDispatchTrack(string url) { try { CFDispatchTrackApplicationSettings loAppSettings = new CFDispatchTrackApplicationSettings(); int connectionTimeOutMinutes = int.Parse(loAppSettings.Get("DispatchTrackAPIPortTimeOutMinutes")); HttpClient client = new HttpClient(); client.Timeout = new TimeSpan(0, connectionTimeOutMinutes, 0); HttpResponseMessage response = client.GetAsync(url).Result; if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync().Result; dynamic json = JsonConvert.DeserializeObject(result); return(json); } else { return(null); } } catch (Exception e) { return(null); } }
public static bool UpdateRouteOHist(string url) { CFDispatchTrackApplicationSettings loAppSettings = new CFDispatchTrackApplicationSettings(); try { int connectionTimeOut = int.Parse(loAppSettings.Get("DispatchTrackAPIPortTimeOutMinutes")); //value represents the time in minutes HttpClient client = new HttpClient(); client.Timeout = new TimeSpan(0, connectionTimeOut, 0); //1 hour HttpResponseMessage response = client.GetAsync(url).Result; if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync().Result; dynamic json = JsonConvert.DeserializeObject(result); string error = json.error; return(error.Trim().Length == 0); } else { return(false); } } catch (Exception e) { throw e; } }
public static bool UpdateRouteOHistByRoute(string url, string date, string warehouse, string waveid, string processId, List <string> routes) { CFDispatchTrackApplicationSettings loAppSettings = new CFDispatchTrackApplicationSettings(); try { ExportParams postParams = new ExportParams(date, warehouse, waveid, processId, routes.ToArray <string>()); string strPostParams = JsonConvert.SerializeObject(postParams); int connectionTimeOut = int.Parse(loAppSettings.Get("DispatchTrackAPIPortTimeOutMinutes")); //value represents the time in minutes HttpClient client = new HttpClient(); client.Timeout = new TimeSpan(0, connectionTimeOut, 0); //1 hour var content = new StringContent(strPostParams, Encoding.UTF8, "application/json"); HttpResponseMessage response = client.PostAsync(url, content).Result; if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync().Result; dynamic json = JsonConvert.DeserializeObject(result); string error = json.error; return(error.Trim().Length == 0); } else { return(false); } } catch (Exception e) { throw e; } }
//public XDocument Build_DT_XML_AS400BookedStops(string strDate, string strRoutingZone, List<WaveFiltersValues> filtersList, List<int> intWavesList, string warehouseID) //{ // var clsMSWindowsLog = new MSWindowsLogFunctions(); // var appLogFile = new AppLogFile(); // int currentCustomerRecord = 0; // string batchID = ""; // string uniqueOrderID = ""; // string orderDateMainOnly = ""; // string ordersList = ""; // string orderClass = ""; // List<string> orderClassDescription = new List<string>(); // int itemsCounter = 0; // DateTime ordersDate = Convert.ToDateTime(strDate); // DataAccess as400Connection = new DataAccess(); // XDocument xDoc = new XDocument(); // xDoc.Declaration = new XDeclaration("1.0", "UTF-8", null); // XElement ServiceOrders = new XElement("service_orders"); // foreach (int listitem in intWavesList) // { // DateTime dtRouteDate; // string strSessionName = ""; // string strSessionDescription = ""; // DataAccess roadNetWaves = new DataAccess(); // DataTable daSessionMasterChilds = new DataTable(); // DataTable daSessionPreferedRoutes = new DataTable(); // daSessionMasterChilds = roadNetWaves.GetSessionsMasterBySessionID(listitem, 3); // if (daSessionMasterChilds.Rows.Count == 0) // daSessionMasterChilds = roadNetWaves.GetSessionsMasterBySessionID(listitem, 1); // if (daSessionMasterChilds.Rows.Count > 0) // { // foreach (DataRow dtrow in daSessionMasterChilds.Rows) // { // if ((int)dtrow["as400sessionid_fk"] > 0) // { // if ((int)dtrow["adddates"] > 0) // { // dtRouteDate = ordersDate.AddDays((int)dtrow["adddates"]); // } // else // { // dtRouteDate = ordersDate; // } // strSessionName = "TAMARAC-" + strRoutingZone.Replace(' ', '-'); // strSessionDescription = (string)dtrow["sessionname"]; // daSessionPreferedRoutes = roadNetWaves.GetPreferedRouteBySessionID((int)dtrow["sessionid_pk"], 2); // List<dynamic> dynlist = new List<dynamic>(); // foreach (DataRow dtrow2 in daSessionPreferedRoutes.Rows) // { // dynlist.Add(dtrow2); // } // AS400GetRteDtaMain.getrtedtaResult iEBookedStops = new AS400GetRteDtaMain.getrtedtaResult(); // iEBookedStops = as400Connection.GetRoutingDataFromAS400APIRouteiMaster(dtRouteDate, Convert.ToInt32(dtrow["as400sessionid_fk"]), strRoutingZone, filtersList, warehouseID); // if (iEBookedStops.P_RESPONSE.SUCCESSFUL == "Y") // { // batchID = iEBookedStops.P_RESPONSE.BATCHID; // if (iEBookedStops.P_RESPONSE.CUSTOMERS.Length > 0) // { // myLogger.ProcessLog(1, string.Format("Building DispatchTrack XML for Delivery Date: {0} Orders: {1}", dtRouteDate.ToString("MM/dd/yyyy"), iEBookedStops.P_RESPONSE.CUSTOMERS.Length)); // currentCustomerRecord = 0; // XElement Invoice; // XElement Customer; // XElement Notes; // XElement Extra; // XElement CustomFields; // XElement Items; // XNamespace empNM = "urn:lst-emp:emp"; // foreach (AS400GetRteDtaMain.customerT customer in iEBookedStops.P_RESPONSE.CUSTOMERS) // { // if (iEBookedStops.P_RESPONSE.CUSTOMERS.Length > currentCustomerRecord) { // Customer = new XElement("customer", // new XElement("customer_id", customer.CUSTOMERID), // new XElement("first_name", customer.FIRSTNAME), // new XElement("last_name", customer.LASTNAME), // new XElement("email", customer.EMAIL), // new XElement("phone1", Convert.ToInt64(customer.PHONE1)!=0? customer.PHONE1: ""), // new XElement("phone2", Convert.ToInt64(customer.PHONE2) != 0 ? customer.PHONE2 : ""), // new XElement("phone3", Convert.ToInt64(customer.PHONE3) != 0 ? customer.PHONE3 : ""), // new XElement("address1", customer.ADDRESS1), // new XElement("address2", customer.ADDRESS2), // new XElement("city", customer.CITY), // new XElement("state", customer.STATE), // new XElement("zip", customer.ZIP5.Trim() + (customer.ZIP4.Trim() != ""? ("-"+ customer.ZIP4.Trim()) : "")), // new XElement("latitude", customer.GEOCODEX), // new XElement("longitute", customer.GEOCODEY) // ); // Notes = new XElement("notes"); // XElement NotesItems; // var notescnt = 0; // if (customer.COMMENTS.COMMENT1.Trim().Length > 1) // { // NotesItems = new XElement("note", // new XAttribute("created_at", ""), // new XAttribute("author", ""), // customer.COMMENTS.COMMENT1 // ); // Notes.Add(NotesItems); // notescnt++; // } // if (customer.COMMENTS.COMMENT2.Trim().Length > 1) // { // NotesItems = new XElement("note", // new XAttribute("created_at", ""), // new XAttribute("author", ""), // customer.COMMENTS.COMMENT2 // ); // Notes.Add(NotesItems); // notescnt++; // } // if (customer.COMMENTS.COMMENT3.Trim().Length > 1) // { // NotesItems = new XElement("note", // new XAttribute("created_at", ""), // new XAttribute("author", ""), // customer.COMMENTS.COMMENT3 // ); // Notes.Add(NotesItems); // notescnt++; // } // if (customer.COMMENTS.COMMENT4.Trim().Length > 1) // { // NotesItems = new XElement("note", // new XAttribute("created_at", ""), // new XAttribute("author", ""), // customer.COMMENTS.COMMENT4 // ); // Notes.Add(NotesItems); // notescnt++; // } // Notes.Add(new XAttribute("count", notescnt)); // CustomFields = new XElement("custom_fields"); // Items = new XElement("items"); // XElement ItemElement; // ordersList = ""; // orderClass = ""; // orderClassDescription.Clear(); // orderDateMainOnly = ""; // AS400GetRteDtaMain.orderT order = new AS400GetRteDtaMain.orderT(); // if (order.INVOICE != 0) // { // string uniqueOrderToPull = ""; // uniqueOrderID = order.UNIQUEORDERID.ToString().Trim(); // if (uniqueOrderID.Length > 7) // uniqueOrderToPull = uniqueOrderID; // else // { // uniqueOrderToPull = uniqueOrderID.Substring(0, 2) + order.INVOICE.ToString().Trim().PadLeft(7,'0') + uniqueOrderID.Substring(uniqueOrderID.Length - 7, 7); // } // if (orderDateMainOnly == "") // orderDateMainOnly = DateTime.ParseExact(order.INVOICEDATE.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture).ToString("yyy-MM-dd"); // ordersList += (ordersList.Trim().Length > 0 ? "," : "") + order.INVOICE.ToString().Trim(); // orderClass += order.INVOICETYPE.ToString().Trim(); // orderClassDescription.Add(CFBusinessLogic.GetOrderClassDescription(order.INVOICETYPE.ToString().Trim())); // AS400GetRteDtaDetail.getrtedetResult iEBookedStopsDetail = new AS400GetRteDtaDetail.getrtedetResult(); // iEBookedStopsDetail = as400Connection.GetRoutingDataFromAS400APIRouteiDetail(uniqueOrderToPull, batchID); // if (iEBookedStopsDetail.P_RESPONSE.SUCCESSFUL == "Y") // { // if (iEBookedStopsDetail.P_RESPONSE.RECORDCOUNT > 0) // { // itemsCounter = 0; // foreach (AS400GetRteDtaDetail.itemT item in iEBookedStopsDetail.P_RESPONSE.ITEMS) // { // if (iEBookedStopsDetail.P_RESPONSE.RECORDCOUNT > itemsCounter) // { // ItemElement = new XElement("item", // new XElement("sale_sequence", item.INVOICELINE), // new XElement("number", order.INVOICE), // new XElement("item_id", item.ITEM), // new XElement("serial_number", item.SERIAL), // new XElement("description", item.DESCRIPTION), // new XElement("quantity", item.QUANTITY), // new XElement("location", item.WAREHOUSE), // new XElement("cube", item.CUBES), // new XElement("setup_time", item.SKUASSEMBLYTIME), // new XElement("weight", item.WEIGHT), // new XElement("price", item.UNITPRICE), // new XElement("countable", 1), // new XElement("store_code", order.STORE) // ); // Items.Add(ItemElement); // itemsCounter++; // } // else // break; // } // } // } // } // else // { // orderClass += "0"; // } // Extra = new XElement("extra", // new XElement("RoutePos", customer.CUSTOM.ZONEPOSITION), // new XElement("AS400Routes", customer.CUSTOM.ZONE), // new XElement("WaveID", strRoutingZone), // new XElement("oClass", orderClass), // new XElement("Invoice1_OrderClass", (orderClassDescription.Count > 0 ? orderClassDescription[0].ToString() : "")), // new XElement("Invoice2_OrderClass", orderClassDescription.Count > 1 ? orderClassDescription[1].ToString() : ""), // new XElement("Invoice3_OrderClass", orderClassDescription.Count > 2 ? orderClassDescription[2].ToString() : "") // ); // //Extra.Add(Extra2); // DateTime deliveryDate = DateTime.ParseExact(customer.CUSTOM.ZONEDATE.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture); // Invoice = new XElement("service_order", // new XElement("number", uniqueOrderID), // new XElement("account", strSessionName), // new XElement("service_type", CFBusinessLogic.GetOrderTypeDescription(orderClass)), // new XElement("description", strSessionDescription), // Customer, // Notes, // Items, // new XElement("pre_reqs", ordersList), // new XElement("amount", 0.00), // new XElement("cod_amount", 0.00), // new XElement("service_unit", strRoutingZone), // new XElement("delivery_date", deliveryDate.ToString("yyy-MM-dd")), // new XElement("request_delivery_date", deliveryDate.ToString("yyy-MM-dd")), // new XElement("driver_id", ""), // new XElement("truck_id", ""), // new XElement("origin", "04"), // new XElement("stop_number", 0), // new XElement("stop_time", ""), // new XElement("service_time", customer.SERVICETIME), // new XElement("request_time_window_start", deliveryDate.ToString("yyy-MM-dd") + " " + customer.CUSTOM.TIMEWINDOWSTART.ToString("00:00")), // new XElement("request_time_window_end", deliveryDate.ToString("yyy-MM-dd") + " " + customer.CUSTOM.TIMEWINDOWEND.ToString("00:00")), // new XElement("delivery_time_window_start", deliveryDate.ToString("yyy-MM-dd") + " " + customer.CUSTOM.TIMEWINDOWSTART.ToString("00:00")), // new XElement("delivery_time_window_end", deliveryDate.ToString("yyy-MM-dd") + " " + customer.CUSTOM.TIMEWINDOWEND.ToString("00:00")), // new XElement("delivery_charge", 0.00), // new XElement("taxes", 0.00), // new XElement("store_code", ""), // Extra, // CustomFields // ); // ServiceOrders.Add(Invoice); // currentCustomerRecord++; // } // } // } // else // { // myLogger.ProcessLog(1, string.Format("No order(s) sent to DispatchTrack for delivery date: {0}", dtRouteDate)); // } // } // else // { // myLogger.ProcessLog(1, string.Format("Error calling AS400 Import Routing Webservice.")); // clsMSWindowsLog.SendEmailMessage(string.Format("Error calling AS400 Import Routing Webservice.")); // } // } // } // } // } // xDoc.Add(ServiceOrders); // return xDoc; //} //public XDocument Build_DT_XML_AS400BookedStopsSingleOrderMode(string strDate, string strRoutingZone, List<WaveFiltersValues> filtersList, List<int> intWavesList, string warehouseID) //{ // var clsMSWindowsLog = new MSWindowsLogFunctions(); // var appLogFile = new AppLogFile(); // int currentCustomerRecord = 0; // string batchID = ""; // string uniqueOrderID = ""; // string orderMainOrder = ""; // string orderMainStore = ""; // string ordersList = ""; // string orderClass = ""; // string orderType = ""; // string orderStockDisp = ""; // int itemsCounter = 0; // DateTime ordersDate = Convert.ToDateTime(strDate); // DataAccess as400Connection = new DataAccess(); // XDocument xDoc = new XDocument(); // xDoc.Declaration = new XDeclaration("1.0", "UTF-8", null); // XElement ServiceOrders = new XElement("service_orders"); // foreach (int listitem in intWavesList) // { // DateTime dtRouteDate; // string strSessionName = ""; // string strSessionDescription = ""; // DataAccess roadNetWaves = new DataAccess(); // DataTable daSessionMasterChilds = new DataTable(); // DataTable daSessionPreferedRoutes = new DataTable(); // daSessionMasterChilds = roadNetWaves.GetSessionsMasterBySessionID(listitem, 3); // if (daSessionMasterChilds.Rows.Count == 0) // daSessionMasterChilds = roadNetWaves.GetSessionsMasterBySessionID(listitem, 1); // if (daSessionMasterChilds.Rows.Count > 0) // { // foreach (DataRow dtrow in daSessionMasterChilds.Rows) // { // if ((int)dtrow["as400sessionid_fk"] > 0) // { // if ((int)dtrow["adddates"] > 0) // { // dtRouteDate = ordersDate.AddDays((int)dtrow["adddates"]); // } // else // { // dtRouteDate = ordersDate; // } // strSessionName = "TAMARAC-" + strRoutingZone.Replace(' ', '-'); // strSessionDescription = (string)dtrow["sessionname"]; // daSessionPreferedRoutes = roadNetWaves.GetPreferedRouteBySessionID((int)dtrow["sessionid_pk"], 2); // List<dynamic> dynlist = new List<dynamic>(); // foreach (DataRow dtrow2 in daSessionPreferedRoutes.Rows) // { // dynlist.Add(dtrow2); // } // AS400GetRteDtaMain.getrtedtaResult iEBookedStops = new AS400GetRteDtaMain.getrtedtaResult(); // iEBookedStops = as400Connection.GetRoutingDataFromAS400APIRouteiMaster(dtRouteDate, Convert.ToInt32(dtrow["as400sessionid_fk"]), strRoutingZone, filtersList, warehouseID); // if (iEBookedStops.P_RESPONSE != null && iEBookedStops.P_RESPONSE.SUCCESSFUL == "Y") // { // batchID = iEBookedStops.P_RESPONSE.BATCHID; // if (iEBookedStops.P_RESPONSE.CUSTOMERS.Length > 0) // { // myLogger.ProcessLog(1, string.Format("Building DispatchTrack XML for Session: {0} - Delivery Date: {1} - Orders: {2}", strSessionDescription, dtRouteDate.ToString("MM/dd/yyyy"), iEBookedStops.P_RESPONSE.CUSTOMERS.Length)); // currentCustomerRecord = 0; // XElement Invoice; // XElement Customer; // XElement Notes; // XElement Extra; // XElement CustomFields; // XElement Items; // XNamespace empNM = "urn:lst-emp:emp"; // foreach (AS400GetRteDtaMain.customerT customer in iEBookedStops.P_RESPONSE.CUSTOMERS) // { // if (iEBookedStops.P_RESPONSE.CUSTOMERS.Length > currentCustomerRecord) // { // DateTime deliveryDate = DateTime.ParseExact(customer.CUSTOM.ZONEDATE.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture); // XElement ItemElement; // orderClass = ""; // orderType = ""; // orderMainOrder = ""; // orderMainStore = ""; // AS400GetRteDtaMain.orderT order = customer.ORDER; // if (order.INVOICE != 0) // { // Items = new XElement("items"); // string uniqueOrderToPull = ""; // uniqueOrderID = order.INVOICE.ToString().Trim(); // if (uniqueOrderID.Length > 7) // uniqueOrderToPull = uniqueOrderID; // else // { // uniqueOrderToPull = deliveryDate.ToString("yyMMdd") + "-" + order.INVOICE.ToString().Trim().PadLeft(6, '0'); // } // orderMainOrder = order.MASTERORDERID.ToString(); // orderMainStore = order.MASTERSTORE.ToString(); // ordersList = order.INVOICE.ToString().Trim(); // orderClass = order.INVOICETYPE.ToString().Trim(); // orderStockDisp = order.STOCKDISPOSITION.ToString().Trim(); // orderType = CFBusinessLogic.GetOrderClassDescription(orderClass); // AS400GetRteDtaDetail.getrtedetResult iEBookedStopsDetail = new AS400GetRteDtaDetail.getrtedetResult(); // iEBookedStopsDetail = as400Connection.GetRoutingDataFromAS400APIRouteiDetail(uniqueOrderToPull, batchID); // if (iEBookedStopsDetail.P_RESPONSE.SUCCESSFUL == "Y") // { // if (iEBookedStopsDetail.P_RESPONSE.ITEMS.Length > 0) // { // itemsCounter = 0; // foreach (AS400GetRteDtaDetail.itemT item in iEBookedStopsDetail.P_RESPONSE.ITEMS) // { // if (iEBookedStopsDetail.P_RESPONSE.ITEMS.Length > itemsCounter) // { // if (order.INVOICE == iEBookedStopsDetail.P_RESPONSE.INVOICE) // { // ItemElement = new XElement("item", // new XElement("sale_sequence", item.INVOICELINE), // new XElement("number", order.INVOICE), // new XElement("item_id", item.ITEM), // new XElement("serial_number", item.SERIAL), // new XElement("description", item.DESCRIPTION), // new XElement("quantity", item.QUANTITY), // new XElement("location", item.WAREHOUSE), // new XElement("cube", item.CUBES), // new XElement("setup_time", item.SKUASSEMBLYTIME), // new XElement("weight", item.WEIGHT), // new XElement("price", item.UNITPRICE), // new XElement("countable", 1), // new XElement("store_code", order.STORE) // ); // Items.Add(ItemElement); // itemsCounter++; // } // } // else // break; // } // } // } // Customer = new XElement("customer", // new XElement("customer_id", customer.CUSTOMERID), // new XElement("first_name", customer.FIRSTNAME), // new XElement("last_name", customer.LASTNAME), // new XElement("email", customer.EMAIL), // new XElement("phone1", customer.PHONE1 != "" ? customer.PHONE1 : ""), // new XElement("phone2", customer.PHONE2 != "" ? customer.PHONE2 : ""), // new XElement("phone3", customer.PHONE3 != "" ? customer.PHONE3 : ""), // new XElement("address1", customer.ADDRESS1), // new XElement("address2", customer.ADDRESS2), // new XElement("city", customer.CITY), // new XElement("state", customer.STATE), // new XElement("zip", customer.ZIP5.Trim()), // + (customer.ZIP4.Trim() != "" ? ("-" + customer.ZIP4.Trim()) : "")), // new XElement("longitute", customer.GEOCODEX), // new XElement("latitude", customer.GEOCODEY) // ); // Notes = new XElement("notes"); // XElement NotesItems; // var notescnt = 0; // if (customer.COMMENTS.COMMENT1.Trim().Length > 1) // { // NotesItems = new XElement("note", // new XAttribute("created_at", ""), // new XAttribute("author", ""), // customer.COMMENTS.COMMENT1 // ); // Notes.Add(NotesItems); // notescnt++; // } // if (customer.COMMENTS.COMMENT2.Trim().Length > 1) // { // NotesItems = new XElement("note", // new XAttribute("created_at", ""), // new XAttribute("author", ""), // customer.COMMENTS.COMMENT2 // ); // Notes.Add(NotesItems); // notescnt++; // } // if (customer.COMMENTS.COMMENT3.Trim().Length > 1) // { // NotesItems = new XElement("note", // new XAttribute("created_at", ""), // new XAttribute("author", ""), // customer.COMMENTS.COMMENT3 // ); // Notes.Add(NotesItems); // notescnt++; // } // if (customer.COMMENTS.COMMENT4.Trim().Length > 1) // { // NotesItems = new XElement("note", // new XAttribute("created_at", ""), // new XAttribute("author", ""), // customer.COMMENTS.COMMENT4 // ); // Notes.Add(NotesItems); // notescnt++; // } // Notes.Add(new XAttribute("count", notescnt)); // CustomFields = new XElement("custom_fields"); // //Items = new XElement("items"); // Extra = new XElement("extra", // new XElement("RoutePos", customer.CUSTOM.ZONEPOSITION), // new XElement("AS400Routes", customer.CUSTOM.ZONE), // new XElement("WaveID", strRoutingZone), // new XElement("OrderType", orderType.ToString()), // new XElement("MainStopOrder", orderMainOrder.ToString()) // ); // Invoice = new XElement("service_order", // new XElement("number", uniqueOrderToPull), // new XElement("account", strSessionName), // new XElement("service_type", CFBusinessLogic.GetOrderTypeDescription(orderClass, orderStockDisp)), // new XElement("description", strSessionDescription), // Customer, // Notes, // Items, // new XElement("pre_reqs", ""), // new XElement("amount", 0.00), // new XElement("cod_amount", 0.00), // new XElement("service_unit", ""), // new XElement("delivery_date", deliveryDate.ToString("yyy-MM-dd")), // new XElement("request_delivery_date", deliveryDate.ToString("yyy-MM-dd")), // new XElement("driver_id", ""), // new XElement("truck_id", ""), // new XElement("origin", "04"), // new XElement("stop_number", 0), // new XElement("stop_time", ""), // new XElement("service_time", customer.CUSTOM.MINUTESATSTOP), // new XElement("request_time_window_start", deliveryDate.ToString("yyy-MM-dd") + " " + customer.CUSTOM.TIMEWINDOWSTART.ToString("00:00")), // new XElement("request_time_window_end", deliveryDate.ToString("yyy-MM-dd") + " " + customer.CUSTOM.TIMEWINDOWEND.ToString("00:00")), // new XElement("delivery_time_window_start", deliveryDate.ToString("yyy-MM-dd") + " " + customer.CUSTOM.TIMEWINDOWSTART.ToString("00:00")), // new XElement("delivery_time_window_end", deliveryDate.ToString("yyy-MM-dd") + " " + customer.CUSTOM.TIMEWINDOWEND.ToString("00:00")), // new XElement("delivery_charge", 0.00), // new XElement("taxes", 0.00), // new XElement("store_code", ""), // Extra, // CustomFields // ); // ServiceOrders.Add(Invoice); // currentCustomerRecord++; // } // } // } // } // else // { // myLogger.ProcessLog(1, string.Format("No order(s) sent to DispatchTrack for Session: {0} - Delivery Date: {1}", strSessionDescription, dtRouteDate)); // } // } // else // { // myLogger.ProcessLog(1, string.Format("Error calling AS400 Import Routing Webservice - Session: {0}", strSessionDescription)); // clsMSWindowsLog.SendEmailMessage(string.Format("Error calling AS400 Import Routing Webservice. - Session: {0}", strSessionDescription)); // } // } // } // } // } // xDoc.Add(ServiceOrders); // return xDoc; //} public int SendDataTo_DT_API(int sendmode, XDocument xmldocument) { CFDispatchTrackApplicationSettings loAppSettings = new CFDispatchTrackApplicationSettings(); int retValue = 0; dynamic postURL; string credentials = ""; if (sendmode == 1) { //Batch Mode postURL = @loAppSettings.Get("DispatchTrackURLImportBatch"); } else { postURL = @loAppSettings.Get("DispatchTrackURLImportSingle"); } credentials = "code=" + loAppSettings.Get("DispatchTrackCode") + "&api_key=" + loAppSettings.Get("DispatchTrackAPIKey") + "&data="; try { // Create a request using a URL that can receive a post. WebRequest request = WebRequest.Create(postURL); // Set the Method property of the request to POST. request.Method = "POST"; // A long time out request.Timeout = 1000000; //read the xml file into a string prior to encoding and converting to byte array string datatopost = ToStringWithDeclaration(xmldocument); //now urlencode the xml file datatopost = System.Web.HttpUtility.UrlEncode(datatopost); //now concatenate the urlencoded xml file with the non url encoded credentials string credentials = credentials + datatopost; // Create POST data and convert it to a byte array. byte[] byteArray = Encoding.UTF8.GetBytes(credentials); // Set the ContentType property of the WebRequest. request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. WebResponse response = request.GetResponse(); // Display the status. Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Write to the file WriteResponseStream(ref responseFromServer); // Clean up the streams. reader.Close(); dataStream.Close(); response.Close(); Object obj = ObjectToXML(responseFromServer, typeof(DTResponse)); myLogger.ProcessLog(1, string.Format("DispatchTrack Server Response: {0}", responseFromServer)); retValue = 1; } catch (Exception ex) { string msg = ex.ToString(); myLogger.ProcessLog(1, string.Format("Error Exception: {0}", ex.ToString())); WriteResponseStream(ref msg); } return(retValue); }
private void bgwImportOrders_DoWork(object sender, DoWorkEventArgs e) { var lbValidate = false; var tokenSource = new CancellationTokenSource(); if (DtSelectedDate < DateTime.Today) { DialogResult lcValidationResult = MessageBox.Show("Are you sure you want to request AS400 orders for a date prior current date?", "Action Confirmation Request", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, MessageBoxOptions.ServiceNotification); if (lcValidationResult == DialogResult.Yes) { lbValidate = true; } } else { lbValidate = true; } DataAccess dataAccess = new DataAccess(); try { bool stopExport; if (dataAccess.CheckWaveExportedtoAS400Already(DtSelectedDate, importingWaveDesc) == "BAD") { DialogResult lcValidationRes = MessageBox.Show("WARNING - WARNING - WARNING\n\nThe orders for the selected Date and Wave have been exported to the AS400 already.\n\nContinuing the process will add - change - delete data in/from Dispatch Track that is not included in this batch.\n\nAre you sure you want to procedd?\n\nPress 'Yes' to continue if you are sure that is correct, 'No' to cancel export process.", "WARNING - Action Confirmation Request", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, MessageBoxOptions.ServiceNotification); stopExport = (lcValidationRes != DialogResult.Yes); if (stopExport) { lbValidate = false; } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); lbValidate = false; } if (lbValidate == true) { try { bool stopExport; if (dataAccess.CheckLockStatus(DtSelectedDate, importingWave)) { DialogResult lcValidationRes = MessageBox.Show("Orders for selected wave/date has been exported to Dispatch Track before.\\nPlease make sure routes and time windows are locked in Dispatch Track before exporting again.\\nPress 'Yes' to continue if routes are locked, 'No' to cancel export process and check out routes in Dispatch Track.", "Action Confirmation Request", MessageBoxButtons.YesNo); stopExport = (lcValidationRes != DialogResult.Yes); if (stopExport) { lbValidate = false; } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); lbValidate = false; } } if (lbValidate == true) { try { string processCode = ProcessCode.IMPORT.ToString(); int currentProcessId; if (dataAccess.CreateProcess(processCode, out currentProcessId)) { var token = tokenSource.Token; RunProcessLogs(token, processCode, currentProcessId); bgwImportOrders.ReportProgress(20); cmdImportOrders.Enabled = false; Cursor.Current = Cursors.WaitCursor; CFDispatchTrackApplicationSettings loAppSettings = new CFDispatchTrackApplicationSettings(); string apiHost = loAppSettings.Get("DispatchTrackAPIHost"); string apiPort = loAppSettings.Get("DispatchTrackAPIPort"); string apiImportOrders = ""; string url = ""; string date = DtSelectedDate.ToString("yyyyMMdd"); string warehouseId = int.Parse(sessionsValues.First(cdr => cdr["sessionid_pk"].ToString() == importingWave)["cfwh_id"].ToString()).ToString(); //string warehouseId = ((int)Enum.Parse(typeof(Warehouse), Warehouse.TAMARAC.ToString())).ToString(); apiImportOrders = loAppSettings.Get("DispatchTrackImportOrders"); //if (this.chkNoRegularInvoices.Checked == false) // url = apiHost + ":" + apiPort + apiImportOrders + warehouseId + "/" + date + "/" + importingWave + "/ALL/" + currentProcessId; //else // url = apiHost + ":" + apiPort + apiImportOrders + warehouseId + "/" + date + "/" + importingWave + "/NRI/" + currentProcessId ; if (chkNoRegularInvoices.Checked) { url = apiHost + (apiPort.Trim().Length > 0 ? ":" + apiPort : "") + apiImportOrders + warehouseId + "/" + date + "/" + importingWave + "/NRI/" + currentProcessId; } else if (chkOnlyTransfers.Checked) { url = apiHost + (apiPort.Trim().Length > 0 ? ":" + apiPort : "") + apiImportOrders + warehouseId + "/" + date + "/" + importingWave + "/TRA/" + currentProcessId; } else { url = apiHost + (apiPort.Trim().Length > 0 ? ":" + apiPort : "") + apiImportOrders + warehouseId + "/" + date + "/" + importingWave + "/ALL/" + currentProcessId; } bgwImportOrders.ReportProgress(25); HttpResponseMessage aSyncResponse; bool res = NodeAPI.UploadOrdersData(url, out aSyncResponse); Cursor.Current = Cursors.Default; Thread.Sleep(1000); if (!res) { tokenSource.Cancel(); MessageBox.Show("Unsuccessful call to node.js api. Reason Phrase: " + aSyncResponse.ReasonPhrase); } else { bgwImportOrders.ReportProgress(100); tokenSource.Cancel(); MessageBox.Show("Orders successfully imported."); } } else { tokenSource.Cancel(); MessageBox.Show("Error while creating the process."); } } catch (Exception error) { //MessageBox.Show(error.ToString()); //MessageBox.Show(error.Message.ToString()); //MessageBox.Show("No Orders Found to Import"); tokenSource.Cancel(); MessageBox.Show("No Orders Found to Import", "Import Orders from AS400", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); //Text, caption } } //Thread.Sleep(1000); //tokenSource.Cancel(); //this change the value of token.IsCancellationRequested from 'false' to 'true', stopping the while loop in method ProcessLogs tokenSource.Dispose(); }
/// <summary> /// Return dictionary with route, order and item info /// </summary> /// <param name="url">API endpoint url</param> /// <param name="dictRes">This is an output parameter that brings back routes, orders and items info </param> /// <returns></returns> public static bool GetOrdersDataFromDispatchTrack(string url, out Dictionary <string, Dictionary <Stop, List <string> > > dictRes, out List <string> invalidRoutes, out List <string> invalidGeoCodes, out Dictionary <Tuple <double, double>, List <Tuple <string, string> > > repeatedGeoCodes, out int totalRoutes, out int totalStops, out int totalOrders) { CFDispatchTrackApplicationSettings loAppSettings = new CFDispatchTrackApplicationSettings(); decimal latitudeFrom; decimal latitudeTo; decimal longitudeFrom; decimal longitudeTo; decimal.TryParse(loAppSettings.Get("FloridaLatitudeFrom"), out latitudeFrom); decimal.TryParse(loAppSettings.Get("FloridaLatitudeTo"), out latitudeTo); decimal.TryParse(loAppSettings.Get("FloridaLongitudeFrom"), out longitudeFrom); decimal.TryParse(loAppSettings.Get("FloridaLongitudeTo"), out longitudeTo); dictRes = new Dictionary <string, Dictionary <Stop, List <string> > >(); invalidRoutes = new List <string>(); invalidGeoCodes = new List <string>(); string[] auxArray; repeatedGeoCodes = new Dictionary <Tuple <double, double>, List <Tuple <string, string> > >(); totalRoutes = 0; totalStops = 0; totalOrders = 0; try { HttpClient client = new HttpClient(); client.Timeout = new TimeSpan(1, 0, 0); //1 hour HttpResponseMessage response = client.GetAsync(url).Result; if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync().Result; dynamic json = JsonConvert.DeserializeObject(result); string currentRoute = ""; string currentOrder = ""; string currentItem = ""; string currentItemQuantity = ""; double currentLatitude; double currentLongitude; int currentStop; Tuple <double, double> currentTuple; Tuple <string, string> currentTupleRteInfo; Stop currentStopStruct; var lastRoute = ""; var lastStop = 0; foreach (var route in json.data) { currentRoute = route.routeID; currentRoute = currentRoute.Trim(); currentStop = route.stopSeqID; currentOrder = route.uniqueOrderID; if (lastRoute != currentRoute) { lastRoute = currentRoute; totalStops = totalStops + lastStop; lastStop = currentStop; } else { if (lastStop < currentStop) { lastStop = currentStop; } } //check route value has the right format if (currentRoute.Length != 2 && !invalidRoutes.Contains(currentRoute)) { invalidRoutes.Add(currentRoute); } //get geocodes and routes information currentLatitude = route.orderDetails.customer.First.latitude.First; currentLongitude = route.orderDetails.customer.First.longitude.First; currentTuple = new Tuple <double, double>(currentLatitude, currentLongitude); currentTupleRteInfo = new Tuple <string, string>(currentRoute, currentRoute + "/" + currentStop + "/" + currentOrder); if (repeatedGeoCodes.ContainsKey(currentTuple)) { if (repeatedGeoCodes[currentTuple].Where(r => currentTupleRteInfo.Item1 == r.Item1).Count() == 0) { repeatedGeoCodes[currentTuple].Add(currentTupleRteInfo); } } else { repeatedGeoCodes.Add(currentTuple, new List <Tuple <string, string> >() { currentTupleRteInfo }); } string customerName = route.orderDetails.customer.First.first_name.First; string customerLastname = route.orderDetails.customer.First.last_name.First; if (Math.Abs((decimal)currentLatitude) > Math.Abs(latitudeFrom) || Math.Abs((decimal)currentLatitude) < Math.Abs(latitudeTo) || Math.Abs((decimal)currentLongitude) > Math.Abs(longitudeFrom) || Math.Abs((decimal)currentLongitude) < Math.Abs(longitudeTo)) { invalidGeoCodes.Add(currentOrder); } auxArray = currentOrder.Split(new char[] { '-' }); currentOrder = auxArray[auxArray.Length - 1].Trim(); if (!dictRes.ContainsKey(currentRoute)) { dictRes.Add(currentRoute, new Dictionary <Stop, List <string> >()); totalRoutes++; } currentStopStruct = new Stop(currentStop, currentOrder, customerName + " " + customerLastname); dictRes[currentRoute].Add(currentStopStruct, new List <string>()); totalOrders++; if (route.orderDetails.items != null) { try { foreach (var item in route.orderDetails.items[0].item) //this structure looks weird but that's how JSON.Net parses the coming JSON { currentItem = item.item_id.First; currentItemQuantity = item.quantity.First; dictRes[currentRoute][currentStopStruct].Add(currentItem + " (" + currentItemQuantity + ")"); } } catch (Exception e) { MessageBox.Show(e.ToString()); } } else { dictRes[currentRoute][currentStopStruct].Add("No Items"); } } //add laststop for last record in json totalStops = totalStops + lastStop; //filter geocode tuples in more than one route repeatedGeoCodes = repeatedGeoCodes.Where(t => t.Value.Count > 1).ToDictionary(t => t.Key, t => t.Value); return(true); } else { return(false); } } catch (Exception e) { //dictRes = new Dictionary<string, Dictionary<Stop, List<string>>>(); //invalidRoutes = new List<string>(); //repeatedGeoCodes = new Dictionary<Tuple<double, double>, List<string>>(); //return false; throw e; } }
public static bool CheckDataInDTBeforeExporting(string url, out List <string> notInAS400, out List <string> zoneChanged, out List <string> positionChanged, out List <string> notComing, out List <string> importedNotComing) { CFDispatchTrackApplicationSettings loAppSettings = new CFDispatchTrackApplicationSettings(); int connectionTimeOutMinutes = int.Parse(loAppSettings.Get("DispatchTrackAPIPortTimeOutMinutes")); notInAS400 = new List <string>(); zoneChanged = new List <string>(); positionChanged = new List <string>(); notComing = new List <string>(); importedNotComing = new List <string>(); string currentInvoice = ""; try { HttpClient client = new HttpClient(); client.Timeout = new TimeSpan(0, connectionTimeOutMinutes, 0); //1 hour HttpResponseMessage response = client.GetAsync(url).Result; if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync().Result; dynamic json = JsonConvert.DeserializeObject(result); string error = json.error; if (error.Trim().Length == 0) { if (json.data != null) { if (json.data.noAS400 != null) { foreach (var currentInv in json.data.noAS400) { currentInvoice = currentInv; notInAS400.Add(currentInvoice); } } if (json.data.zoneChanged != null) { foreach (var currentInv in json.data.zoneChanged) { currentInvoice = currentInv; zoneChanged.Add(currentInvoice); } } if (json.data.posChanged != null) { foreach (var currentInv in json.data.posChanged) { currentInvoice = currentInv; positionChanged.Add(currentInvoice); } } if (json.data.expectedNotComing != null) { foreach (var currentInv in json.data.expectedNotComing) { currentInvoice = currentInv; notComing.Add(currentInvoice); } } if (json.data.importedNotComing != null) { foreach (var currentInv in json.data.importedNotComing) { currentInvoice = currentInv; importedNotComing.Add(currentInvoice); } } } return(true); } else { throw new Exception(error.Trim()); } } else { return(false); } } catch (Exception e) { throw e; } }