|
- using System.Collections.Generic;
- using System;
- using System.Text;
- using System.Threading.Tasks;
- using Microsoft.Identity.Client;
- using Microsoft.Exchange.WebServices.Data;
- using System.IO;
- using System.Data;
- using System.Data.SqlClient;
- using System.Reflection;
- using jdis_import.RESTObjects;
- using System.Linq;
- using System.Net;
-
- /*
- Secret Value up-8Q~y46~JyQZjJlsAJ-zpXpglpmuPIJ1Gx3a2O
- Secret ID cba04a6c-a233-4646-909b-b50921edbe1c
- Client ID 489776b1-ee79-4b14-bc44-9f6bf47332db
- Object ID c7647074-edb6-4e8e-8a01-a1ed924fdae9
- Tenant ID 1fd06c96-d3a4-45e9-9ed7-bcecb394d277
- */
-
- namespace jdis_import
- {
- class Program
- {
- private static JSONSetting _settings;
- private static string _os, _logDir, _logFile, _successDir, _failureDir, _downloadDir;
- private static bool _runAPI = true;
- private static RESTService _rservice;
- private static List<User> _users;
- private static Priority _priority;
- private static Reason _reason;
- private static Status _status;
- private static List<Equipment> _machines;
- private static List<Customer> _customers;
- private static List<Make> _makes;
- private static List<Product> _products;
- private static List<Model> _models;
- private static List<InspectionType> _inspectionTypes;
- private static List<Template> _templates;
- private static string _exeDir;
- private static bool _log = true;
- private static string _connection = "Data Source=192.168.0.7;Initial Catalog=Connexion_Brandt;User ID=mobilepmuser;Password=data4techs;Encrypt=No;TrustServerCertificate=true;Persist Security Info=True;";
- private static string _workOrderNumber = string.Empty;
- private static List<string> _sqlMessages = new List<string>();
- private static bool _newMachine = false;
- private static bool _newMake = false;
- private static bool _newModel = false;
- private static bool _newCustomer = false;
- private static bool _quoted = false;
- public static string ExeDir { get { return _exeDir; } }
- private static Dictionary<string, string> _keys = new Dictionary<string, string>() { { "SecretV", "up-8Q~y46~JyQZjJlsAJ-zpXpglpmuPIJ1Gx3a2O" }, { "SecretID", "cba04a6c-a233-4646-909b-b50921edbe1c" }, { "ObjectId", "c7647074-edb6-4e8e-8a01-a1ed924fdae9" }, { "TenentID", "1fd06c96-d3a4-45e9-9ed7-bcecb394d277" }, { "AppID", "489776b1-ee79-4b14-bc44-9f6bf47332db" } };
- public static Dictionary<string, int> InspectionType;
-
- private static Customer CreateNewCustomer(CustomerImport c, ToDo todo)
- {
- Customer cust = new Customer();
- cust.Name = c.Name;
- cust.Address = c.Addr1;
- cust.Address2 = c.Addr2;
- cust.City = c.City;
- cust.State = c.State;
- cust.CreateDate = DateTime.Now;
- cust.CreateUserID = -1;
- cust.UpdateDate = DateTime.Now;
- cust.UpdateUserID = -1;
- cust.IsActive = true;
- cust.Number = c.Number;
- cust.ZipCode = c.Zip;
- string json = Serialize.ToJson<Customer>(cust);
- cust = _rservice.PostRest<Customer>(json, "customers.svc");
- return cust;
- }
- private static Model CreateNewModel(Product defaultP, EquipmentImport eq, ToDo todo)
- {
- Model mdl = new Model();
- //Find the Make and assign the default Product
- mdl.Name = eq.Model.Trim();
- mdl.IsActive = true;
- mdl.CreateDate = DateTime.Now;
- mdl.CreateUserID = -1;
- mdl.UpdateDate = DateTime.Now; ;
- mdl.UpdateUserID = -1;
- mdl.Product = defaultP;
- Make mk = (from x in _makes where x.Name.Trim() == eq.Make.Trim() select x).FirstOrDefault();
- if (mk == null)
- {
- //Create new Make
- mk.Name = eq.Make.Trim();
- mk.CreateDate = DateTime.Now;
- mk.CreateUserID = -1;
- mk.UpdateDate = DateTime.Now;
- mk.UpdateUserID = -1;
- mk.IsActive = true;
- mk.Description = eq.Make.Trim();
- string mkJson = Serialize.ToJson<Make>(mk);
- mk = _rservice.PostRest<Make>(mkJson, "makes.svc");
-
- }
- mdl.Make = mk;
- string json = Serialize.ToJson<Model>(mdl);
- mdl = _rservice.PostRest<Model>(json, "models.svc");
- return mdl;
- }
- private static Equipment CreateNewMachine(EquipmentImport eq, Model mdl, Customer cust, ToDo todo)
- {
- Equipment newMachine = new Equipment();
- newMachine.Model = mdl;
- newMachine.Make = mdl.Make;
- newMachine.Product = mdl.Product;
- newMachine.BarcodeID = null;
- newMachine.CreateDate = DateTime.Now;
- newMachine.UpdateDate = DateTime.Now;
- newMachine.UpateUserID = -1;
- newMachine.CreateUserID = -1;
- newMachine.Description = eq.SerialNumber;
- newMachine.IsActive = true;
- newMachine.LastServiceDate = null;
- newMachine.Location = null;
- newMachine.ManufacturerYear = "2000";
- newMachine.MeterReading = eq.MeterReading;
- newMachine.Number = eq.EquipmentNumber;
- newMachine.Odometer = null;
- newMachine.SerialNumber = eq.SerialNumber;
- newMachine.Customer = cust;
- string eqJson = Serialize.ToJson<Equipment>(newMachine);
- newMachine = _rservice.PostRest<Equipment>(eqJson, "Equipments.svc");
- return newMachine;
- }
- public static void APIPush(CustomerImport c, WorkOrderImport wo, List<PartImport> parts, EquipmentImport eq, ToDo todo)
- {
- Equipment machine = new Equipment();
- Model mdl = _models.Find(x => x.Name.Trim() == eq.Model.Trim());
- Product defaultP = _products.Find(x => x.ID == 14);
- //Customer cust = new Customer();
- Customer cust = IsNewCustomer(c.Name);
- if (cust == null)
- cust = CreateNewCustomer(c, todo);
- List<Equipment> equipment = IsNewMachine(eq.SerialNumber);
- _newMachine = equipment.Count == 0;
- if (_newMachine)
- {
- bool isNewModel = mdl == null;
- if (isNewModel)
- {
- string sModel = eq.Model.Trim().Substring(0, eq.Model.Length - 1);
- mdl = (from x in _models where x.Name.Contains(sModel) orderby x.ID select x).LastOrDefault();
- if (mdl == null)
- mdl = CreateNewModel(defaultP, eq, todo);
- else
- machine = CreateNewMachine(eq, mdl, cust, todo);
- }
- else
- {
- machine = CreateNewMachine(eq, mdl, cust, todo);
- }
- }
- else
- {
- machine = equipment.FindAll(x => x.SerialNumber == eq.SerialNumber).LastOrDefault();
- machine.Customer = cust;
-
- }
- //Find the Template
- Template template = _templates.Find(x => x.InspectionLevel.ID == Convert.ToInt32(wo.InspectionLevel) && x.InspectionType.ID == Convert.ToInt32(wo.InspectionType) && x.Name == eq.Model);
- if (template == null)
- {
- //Search by model prefix and get the last one
- string prefix = eq.Model.Trim();
- prefix = prefix.Substring(0, prefix.Length - 1);
- template = (from x in _templates where x.InspectionLevel.ID == Convert.ToInt32(wo.InspectionLevel) && x.InspectionType.ID == Convert.ToInt32(wo.InspectionType) && x.Name.Contains(prefix) orderby x.ID select x).LastOrDefault();
- if (template == null || template.ID == 0)
- {
- todo.Success = false;
- todo.Validation = todo.Validation + " No template for this model.";
- }
-
- }
- User user = _users.Find(x => x.Number == wo.TechnicianUserID.Trim());
- WorkOrder workorder = new WorkOrder();
- workorder.Number = wo.Number;
-
- workorder.Technician = user;
- workorder.Reason = _reason;
- workorder.Priority = _priority;
- workorder.Status = _status;
- workorder.CreateDate = DateTime.Now;
- workorder.CreateUserID = -1;
- workorder.Equipment = machine;
- workorder.Customer = cust;
- workorder.MeterReading = Convert.ToDecimal(eq.MeterReading);
- workorder.ScheduledStartDate = wo.OpnDt;
- workorder.ScheduledEndDate = wo.OpnDt.AddDays(1d);
- workorder.UpdateDate = DateTime.Now;
- workorder.UpdateUserID = -1;
- string woJson = Serialize.ToJson<WorkOrder>(workorder);
- //Console.WriteLine("WorkOrder Object");
- //Console.WriteLine();
- //Console.WriteLine(woJson);
- JDISLog.WriteToLog(_logFile, string.Format("Creating Work Order: {0}", workorder.Number));
- workorder = _rservice.PostRest<WorkOrder>(woJson, "workorders.svc");
- if (template == null || template.ID == 0)
- {
- todo.Validation = todo.Validation + Environment.NewLine + string.Format("Work Order {0} was created but there is no template matching model # {1}", workorder.Number, mdl.Name);
- todo.Success = false;
- }
- else
- {
- JDISLog.WriteToLog(_logFile, String.Format("Creating Inspections for Workorder {0}", workorder.Number));
- Dictionary<string, string> tps = new Dictionary<string, string>();
- tps.Add("create", string.Format("{0}/{1}/{2}", template.ID, workorder.ID, -1));
- Inspection i = _rservice.RestGet<Inspection>(true, "inspections.svc", tps);
- tps["create"] = string.Format("{0}/{1}/{2}", 1691, workorder.ID, -1);
- Inspection sta = _rservice.RestGet<Inspection>(true, "inspections.svc", tps);
- if (i != null && i.ID != 0)
- {
- todo.Success = true;
- }
- }
-
- }
- private static Customer IsNewCustomer(string name)
- {
- List<Customer> list = _customers.FindAll(x => x.Name.Trim() == name.Trim());
- if (list.Count > 1)
- return list.LastOrDefault();
- else if (list.Count == 1)
- return list[0];
- else return null;
-
-
- }
- private static List<Equipment> IsNewMachine(string serial)
- {
- Dictionary<string, string> ps = new Dictionary<string, string>();
- ps.Add("search", serial);
-
- _machines = _rservice.RestGet<Equipment>("equipments.svc", ps);
-
- return _machines;
- }
- private static void ListsAndDefaults()
- {
- _rservice = new RESTService();
- _rservice.BaseUrl = _settings.Prelub.ActiveService;
- _customers = _rservice.RestGet<Customer>("customers.svc");
- _makes = _rservice.RestGet<Make>("makes.svc");
- _products = _rservice.RestGet<Product>("products.svc");
- _models = _rservice.RestGet<Model>("models.svc");
- _inspectionTypes = _rservice.RestGet<InspectionType>("inspectionTypes.svc");
- _templates = _rservice.RestGet<Template>("templates.svc");
- _users = _rservice.RestGet<User>("users.svc");
- _status = new Status();
- _status.ID = 1;
- _status.Name = "Open";
- _priority = new Priority();
- _priority.ID = 3;
- _priority.Name = "Medium";
- _reason = new Reason();
- _reason.ID = 9;
- _reason.Name = "Cust. Request";
- _reason.IsActive = true;
- _reason.CreateDate = new DateTime(2013, 10, 1, 9, 23, 7);
- _reason.CreateUserID = -1;
- _reason.UpdateDate = new DateTime(2013, 10, 1, 9, 23, 7);
- _reason.UpdateUserID = -1;
- }
- static async System.Threading.Tasks.Task IsLocalNetwork()
- {
- var client = new System.Net.Http.HttpClient();
- try
- {
- var result = await client.GetAsync(_settings.Prelub.Check);
- _settings.Prelub.ActiveService = _settings.Prelub.LocalService;
- }
- catch
- {
- _settings.Prelub.ActiveService = _settings.Prelub.RemoteService;
- }
- }
- static async System.Threading.Tasks.Task Main(string[] args)
- {
- _settings = JSONMethods.GetSettings();
- await IsLocalNetwork();
-
-
- if (IsWindows()) _os = "Windows";
- else if (IsMacOS()) _os = "Mac";
- else if (IsLinux()) _os = "Linux";
- SetupDirectories();
- JDISLog.Begin(_logFile);
- ListsAndDefaults();
-
- //Console.WriteLine("Web APIs have loaded.");
- JDISLog.WriteToLog(_logFile, string.Format("Default data loaded..... {0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()));
- _exeDir = Environment.CurrentDirectory;
-
- List<ToDo> list = new List<ToDo>();
- var cca = ConfidentialClientApplicationBuilder
- .Create(_keys["AppID"])
- .WithClientSecret(_keys["SecretV"])
- .WithTenantId(_keys["TenentID"])
- .Build();
-
- var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
- try
- {
- //Console.WriteLine("Connecting To Exchange.");
- JDISLog.WriteToLog(_logFile, string.Format("Connectiong to Exchange Server....{0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()));
- var authResult = await cca.AcquireTokenForClient(ewsScopes)
- .ExecuteAsync();
-
- // Configure the ExchangeService with the access token
- var ewsClient = new ExchangeService();
- ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
- ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
- ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "cmobile@prelub.com");
- Mailbox mb = new Mailbox("connexionmobile@rpmindustries.org");
- FolderId fid = new FolderId(WellKnownFolderName.Inbox, mb);
- List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
- string[] filters = "Brandt Import;BRANDT IMPORT;brandt import;TEST Brandt".Split(';');
- foreach (string s in filters)
- searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, s));
-
- SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());
- ItemView view = new ItemView(100);
-
- view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);
- view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
- view.Traversal = ItemTraversal.Shallow;
- //Console.WriteLine("Line 90: Finding emails.");
-
- FindItemsResults<Item> findResults = ewsClient.FindItems(fid, searchFilter, view);
- List<EmailMessage> messages = new List<EmailMessage>();
- foreach (EmailMessage message in findResults.Items)
- {
- message.Load();
- if (!message.IsRead)
- messages.Add(message);
- }
- JDISLog.WriteToLog(_logFile, string.Format("Found {0} emails", messages.Count));
- foreach (EmailMessage msg in findResults.Items)
- {
- msg.Load();
- if (!msg.IsRead)
- {
- if (msg.HasAttachments)
- {
- foreach (Attachment attachment in msg.Attachments)
- {
- attachment.Load();
- if (attachment is FileAttachment)
- {
- ToDo todo = new ToDo();
- todo.Sender = msg.Sender.Address;
-
- todo.SenderName = msg.Sender.Name;
- todo.FileName = attachment.Name;
- list.Add(todo);
- //Download File
- FileAttachment fAttachment = attachment as FileAttachment;
- string fileAttachmentPath = Path.Combine(_downloadDir, fAttachment.Name);
- File.WriteAllBytes(fileAttachmentPath, fAttachment.Content);
- msg.IsRead = true;
- msg.Update(ConflictResolutionMode.AlwaysOverwrite);
- }
- }
- }
- }
- }
- //Console.WriteLine("Beginning Import.");
- JDISLog.WriteToLog(_logFile, string.Format("Importing JDIS files....{0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongDateString()));
- foreach (ToDo import in list)
- {
-
- BeginImport(import);
- GetInspectionTypes();
- ReadFile(import);
- }
- foreach (ToDo sendMsg in list)
- {
- EmailMessage msgToSend = new EmailMessage(ewsClient);
- JDISLog.WriteToLog(_logFile, string.Format("Sending Message to: {0}\r\nFor Work Order: {1}\r\nJDIS File: {2}", sendMsg.Sender, sendMsg.WorkOrderNumber, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim()));
- string body = "JDIS File: {0} Work Order:{1} {2}";
- if (sendMsg.Success)
- {
- body = string.Format(body, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim(), sendMsg.WorkOrderNumber, "Was Imported Successfully");
- }
- else
- {
- body = string.Format(body, sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1).Trim(), sendMsg.WorkOrderNumber, string.Format("Had Errors while importing: {0}", sendMsg.Validation));
- msgToSend.Attachments.AddFileAttachment(Path.Combine(_downloadDir, sendMsg.FileName));
-
- }
- string fileNameOnly = sendMsg.FileName.Substring(sendMsg.FileName.LastIndexOf("/") + 1);
- msgToSend.Subject = fileNameOnly;
- msgToSend.ToRecipients.Add(new EmailAddress(sendMsg.Sender));
- msgToSend.CcRecipients.Add(new EmailAddress("mcarman@rpmindustries.com"));
- msgToSend.Body = body;
- msgToSend.SendAndSaveCopy();
- string pathToFile = Path.Combine(_downloadDir, sendMsg.FileName);
- if (sendMsg.Success) File.Move(pathToFile, Path.Combine(_successDir, fileNameOnly));
- else File.Move(sendMsg.FileName, Path.Combine(_failureDir, fileNameOnly));
- }
- }
- catch (MsalException ex)
- {
- //Console.WriteLine($"Error acquiring access token: {ex}");
- JDISLog.WriteToLog(_logFile, $"Error acquiring access token: {ex}");
- }
- catch (Exception ex)
- {
- //Console.WriteLine($"Error: {ex}");
- JDISLog.WriteToLog(_logFile, $"Error: {ex}");
- }
-
- if (System.Diagnostics.Debugger.IsAttached)
- {
- Console.WriteLine("Hit any key to exit...");
- Console.ReadKey();
- }
-
-
-
- }
-
- public static void BeginImport(ToDo todo)
- {
- XMLData.BuildIntervalLookup();
- }
- private static void SetupDirectories()
- {
- OS os = new OS();
- switch (_os)
- {
- case "Windows":
- os = _settings.OSs.Find(x => x.Name == "WINDOWS");
- _logDir = os.Log.Replace("/", "\\");
- _logFile = Path.Combine(os.Log.Replace("/", "\\"), "jdis.log");
- _successDir = os.Success.Replace("/", "\\");
- _failureDir = os.Fail.Replace("/", "\\");
- _downloadDir = os.Temp.Replace("/", "\\");
- break;
- case "Mac":
- os = _settings.OSs.Find(x => x.Name == "OSX");
- _logDir = os.Log;
- _logFile = Path.Combine(os.Log, "jdis.log");
- _successDir = os.Success;
- _failureDir = os.Fail;
- _downloadDir = os.Temp;
- break;
- case "Linux":
- os = _settings.OSs.Find(x => x.Name == "LINUX");
- _logDir = os.Log;
- _logFile = Path.Combine(os.Log, "jdis.log");
- _successDir = os.Success;
- _failureDir = os.Fail;
- _downloadDir = os.Temp;
- break;
- default:
- break;
- }
- if (!Directory.Exists(_logDir)) Directory.CreateDirectory(_logDir);
- if (!Directory.Exists(_failureDir)) Directory.CreateDirectory(_failureDir);
- if (!Directory.Exists(_successDir)) Directory.CreateDirectory(_successDir);
- //string path = Path.Combine(_exeDir, "Success");
- //if (!Directory.Exists(path))
- // Directory.CreateDirectory(path);
- //path = Path.Combine(_exeDir, "Fail");
- //if (!Directory.Exists(path))
- // Directory.CreateDirectory(path);
- //path = Path.Combine(_exeDir, "Log");
- //if (!Directory.Exists(path))
- // Directory.CreateDirectory(path);
- }
- public static void GetInspectionTypes()
- {
-
- List<InspectionType> list = _rservice.RestGet<InspectionType>("inspectiontypes.svc");
- InspectionType = new Dictionary<string, int>();
- foreach (InspectionType t in list)
- {
- InspectionType.Add(t.Name, t.ID);
- }
-
- }
- private static string frmtString
- {
- get
- {
- if (_quoted) return "\"{0}\"";
- else return "{0}";
- }
- }
- private static List<string> WriteFileToText(string file)
- {
- List<string> list = new List<string>();
- string txt = string.Empty;
- using (StreamReader sr = new StreamReader(file))
- {
- txt = sr.ReadToEnd().Trim();
- txt = txt.Replace("\r\r\r", "");
- txt = txt.Replace("\r\r", "");
- txt = txt.Replace("\r", "");
- sr.Close();
- }
- string[] array = txt.Trim().Split('\n');
- list.AddRange(array);
- return list;
- }
- private static DateTime DateFormatter(string d, bool hastime = true)
- {
- string month, day, year, time;
-
- DateTime dt = new DateTime();
- if (d.IndexOf("JAN") != -1)
- {
- month = "01";
- d = d.Replace("JAN", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("FEB") != -1)
- {
- month = "02";
- d = d.Replace("FEB", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("MARCH") != -1)
- {
- month = "03";
- d = d.Replace("MARCH", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("MAR") != -1)
- {
- month = "03";
- d = d.Replace("MAR", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("APRIL") != -1)
- {
- month = "04";
- d = d.Replace("APRIL", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("APR") != -1)
- {
- month = "04";
- d = d.Replace("APR", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
-
- else if (d.IndexOf("MAY") != -1)
- {
- month = "05";
- d = d.Replace("MAY", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("JUNE") != -1)
- {
- month = "06";
- d = d.Replace("JUNE", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("JUN") != -1)
- {
- month = "06";
- d = d.Replace("JUN", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("JULY") != -1)
- {
- month = "07";
- d = d.Replace("JULY", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("JUL") != -1)
- {
- month = "07";
- d = d.Replace("JUL", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("AUG") != -1)
- {
- month = "08";
- d = d.Replace("AUG", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("SEPT") != -1)
- {
- month = "09";
- d = d.Replace("SEPT", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("SEP") != -1)
- {
- month = "09";
- d = d.Replace("SEP", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("OCT") != -1)
- {
- month = "10";
- d = d.Replace("OCT", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("0CT") != -1)
- {
- month = "10";
- d = d.Replace("0CT", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else if (d.IndexOf("NOV") != -1)
- {
- month = "11";
- d = d.Replace("NOV", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- else
- {
- month = "12";
- d = d.Replace("DEC", "|");
- day = d.Substring(0, d.IndexOf("|"));
- year = d.Substring(d.IndexOf("|") + 1, 4);
- if (hastime)
- time = d.Substring(d.IndexOf(":") - 3 + 2);
- else time = "00:00:00.000";
-
- string date = string.Format("{0}-{1}-{2} {3}", year, month, day, time);
- dt = DateTime.Parse(date);
- }
- return dt;
- }
- private static void ReadFile(ToDo todo)
- {
- string file = Path.Combine(_downloadDir, todo.FileName);// todo.FileName;
- todo.FileName = file;
- CustomerImport c = new CustomerImport();
- WorkOrderImport wo = new WorkOrderImport();
- EquipmentImport eq = new EquipmentImport();
- List<PartImport> parts = new List<PartImport>();
-
- //Console.WriteLine("Line 306: " + file);
- //Console.WriteLine("Line 307: " + file);
- string filemove = string.Empty;
- string filetxt = string.Empty;
- string inspectionLevel = string.Empty;
- bool isSpecial = false;
- StringBuilder specialInstructions = new StringBuilder();
- int line = 1;
- try
- {
- List<string> filelines = WriteFileToText(file);
- for (int i = filelines.Count - 1; i >= 0; i--)
- {
- if (string.IsNullOrEmpty(filelines[i])) filelines.RemoveAt(i);
- }
- string[] lines = filelines.ToArray();
-
- foreach (string s in lines)
- {
-
- string currentline = s.Trim().Replace("'", "''");
- if (currentline.Contains("Page") && currentline.Substring(78).Trim() != "1")
- line = 18;
- if (currentline.Contains("Page") && currentline.Substring(78).Trim() == "1")
- line = 1;
-
- switch (line)
- {
- case 1:
- string strDate = currentline.Substring(5, currentline.IndexOf("*") - 6);
- strDate = strDate.Trim();
- strDate.Replace(" ", " ");
- wo.CreateDate = DateFormatter(strDate);
- break;
- case 2:
- string strWONum = currentline.Substring(currentline.IndexOf("Work Order") + 10, 12);
- strWONum = strWONum.Trim();
- wo.Number = strWONum;
- todo.WorkOrderNumber = strWONum;
- _workOrderNumber = strWONum;
- string strSeg = currentline.Substring(currentline.IndexOf("Seg.") + 4, 25);
- strSeg = strSeg.Trim();
- wo.Segment = strSeg;
- string strODate = currentline.Substring(currentline.IndexOf("Opn Dt") + 6);
- strODate = strODate.Trim();
- wo.OpnDt = DateFormatter(strODate, false);
- break;
- case 5:
- c.Name = currentline.Substring(3, 25);
- c.Number = currentline.Substring(38, 10);
- break;
- case 6:
- c.Addr1 = currentline.Substring(3, 25);
- break;
- case 7:
- c.Addr2 = currentline.Substring(3, 25);
- break;
- case 8:
- int comma = currentline.IndexOf(",");
- int length = currentline.Length - 3;
-
- c.City = (comma == -1) ? "" : currentline.Substring(3, comma - 3);
- c.State = currentline.Substring(currentline.IndexOf(",") + 2, 2);
- c.Zip = currentline.Substring(comma + 5, 7);
- break;
- case 11:
- eq.Make = currentline.Substring(0, 8).Trim();
- eq.Model = currentline.Substring(8, 14).Trim();
- eq.SerialNumber = currentline.Substring(22, 22).Trim();
- eq.EquipmentNumber = currentline.Substring(42, 16).Trim();
- eq.MeterReading = currentline.Substring(60, 7).Trim();
- eq.MID = CSVObject.MachineExists(eq.SerialNumber, _connection);
- if (eq.MID == 0) _newMachine = true;
- break;
- default:
- break;
- }
-
- if (line > 14)
- {
- if (currentline.EndsWith(" T"))
- {
- if (currentline.Contains("PM LEVEL"))
- {
- isSpecial = false;
- }
- else if (currentline.Contains("PM INTERVAL"))
- {
- isSpecial = false;
- string pminterval = currentline.Substring(currentline.IndexOf(":") + 2);
- pminterval = pminterval.Substring(0, pminterval.IndexOf(" ")).Trim();
- if (XMLData.IntervalLookup.ContainsKey(pminterval)) wo.InspectionLevel = XMLData.IntervalLookup[pminterval].ToString();
- if (!string.IsNullOrEmpty(wo.InspectionLevel)) wo.InspectionInterval = pminterval;
- string strService = currentline.Substring(currentline.IndexOf(":") + 2);
- strService = strService.Substring(strService.IndexOf(" ") + 1).Trim();
- strService = strService.Substring(0, strService.IndexOf(" ") + 1).Trim();
- if (strService.IndexOf(" ") > 0)
- strService = strService.Substring(0, strService.IndexOf(" ")).Trim();
- if (InspectionType.ContainsKey(strService))
- wo.InspectionType = InspectionType[strService].ToString();
- else wo.InspectionType = InspectionType["PM"].ToString();
- string codeanddescriptionoriginal = currentline.Substring(currentline.IndexOf(":") + 2);
- codeanddescriptionoriginal = codeanddescriptionoriginal.Substring(0, codeanddescriptionoriginal.IndexOf(" T") - 3).Trim();
- wo.CodeAndDescriptionOriginal = codeanddescriptionoriginal;
- }
- else if (currentline.Contains("EMPID"))
- {
- isSpecial = false;
- string empid = currentline.Substring(currentline.IndexOf(":") + 2);
- empid = empid.Substring(0, empid.IndexOf(" ")).Trim();
- wo.TechnicianUserID = empid;
- }
- else if (currentline.Contains("PROMISE DATE"))
- {
- isSpecial = false;
- string promisedate = currentline.Substring(currentline.IndexOf(":") + 2);
- promisedate = promisedate.Substring(0, promisedate.IndexOf(" ")).Trim();
- wo.ScheduledStartDate = DateFormatter(promisedate, false);
- }
- else if (currentline.Contains("SPECIAL INSTRUCTIONS"))
- {
- isSpecial = true;
- string special = currentline.Substring(currentline.IndexOf(":") + 2);
- special = special.Substring(0, special.IndexOf(" T") - 1).Trim();
- specialInstructions.Append(special);
- }
- else
- {
- if (isSpecial)
- {
- string addspecial = currentline.Substring(0, currentline.IndexOf(" T") - 1).Trim();
- specialInstructions.Append(string.Format(" {0}", addspecial));
- }
- }
- }
- else
- {
-
- isSpecial = false;
- int qty = 0;
-
- if (currentline.Length > 0)
- {
- string input = currentline.Substring(0, (currentline.IndexOf(" ") == -1) ? 1 : currentline.IndexOf(" ")).Trim();
- if (int.TryParse(input, out qty))
- {
- if (qty < 100 && !currentline.Contains("HR"))
- {
- PartImport pt = new PartImport();
- string sline = currentline.Substring(19).Trim();
- //pt.Description = currentline.Substring(34, 14);
- pt.Number = sline.Substring(0, sline.IndexOf(" "));
- sline = sline.Substring(sline.IndexOf(" ")).Trim();
- pt.Description = sline.Substring(0, sline.IndexOf(" ")).Trim();
- pt.Qty = currentline.Substring(0, currentline.IndexOf(" ")).Trim();
- parts.Add(pt);
- }
- }
- }
-
- }
- }
- line++;
- }
-
- if (wo.ScheduledStartDate == DateTime.MinValue) wo.ScheduledStartDate = DateTime.Now;
- List<CSVObject> list = new List<CSVObject>();
- List<CSVObject> exceptions = new List<CSVObject>();
- if (parts.Count == 0)
- {
- PartImport p = new PartImport();
- p.Description = string.Empty;
- p.Qty = string.Empty;
- p.Number = string.Empty;
- parts.Add(p);
-
- }
- //Put API Integration here
- if (_runAPI)
- {
- APIPush(c, wo, parts, eq, todo);
- }
- else
- {
- static void conn_InfoMsg(object sender, SqlInfoMessageEventArgs e)
- {
- _sqlMessages.Add(e.Message);
- }
-
- foreach (PartImport prt in parts)
- {
- CSVObject obj = new CSVObject();
- obj.Address = string.Format(frmtString, c.Addr1.Trim());
- obj.Address2 = string.Format(frmtString, c.Addr2.Trim());
- obj.City = string.Format(frmtString, c.City.Trim());
- obj.State = string.Format(frmtString, c.State.Trim());
- obj.CustomerName = string.Format(frmtString, c.Name.Trim());
- obj.CustomerNumber = string.Format(frmtString, c.Number.Trim());
- obj.DBSWorkOrderNumber = string.Format(frmtString, wo.Number.Trim());
- obj.EquipmentNumber = string.Format(frmtString, eq.EquipmentNumber.Trim());
- obj.Make = string.Format(frmtString, eq.Make.Trim());
- obj.MeterReading = string.Format(frmtString, eq.MeterReading.Trim());
- obj.Model = string.Format(frmtString, eq.Model.Trim());
- obj.PartNumber = string.Format(frmtString, prt.Number.Trim());
- obj.PartNumberDescription = string.Format(frmtString, prt.Description.Trim());
- obj.Quantity = string.Format(frmtString, prt.Qty.Trim());
- obj.SegmentNumber = string.Format(frmtString, wo.Segment.Trim());
- obj.SerialNumber = string.Format(frmtString, eq.SerialNumber.Trim());
- obj.ZipCode = string.Format(frmtString, c.Zip.Trim());
- obj.CodeAndDescription = string.Format(frmtString, wo.InspectionLevel.Trim());
- obj.SpecialInstructions = specialInstructions.ToString();
- obj.CodeAndDescriptionOriginal = string.Format(frmtString, wo.CodeAndDescriptionOriginal);
- obj.ContractTypeCode = string.Format(frmtString, "");
- obj.DateActualStart = string.Format(frmtString, wo.CreateDate);
- obj.FamilyCode = string.Format(frmtString, "");
- obj.FamilyDescription = string.Format(frmtString, "");
- obj.JobSiteContactName = string.Format(frmtString, "");
- obj.JobSiteContactPhone = string.Format(frmtString, "");
- obj.LastServiceDate = string.Format(frmtString, "");
- obj.PriorityCode = string.Format(frmtString, "");
- obj.ReferenceDocNumber = string.Format(frmtString, "");
- obj.ServiceTech = string.Format(frmtString, wo.TechnicianUserID);
- obj.StoreDescription = string.Format(frmtString, "");
- obj.Store = string.Format(frmtString, "");
- obj.TechName = string.Format(frmtString, "");
- obj.Year = string.Format(frmtString, "");
- obj.ScheduledStartDate = string.Format(frmtString, wo.ScheduledStartDate.ToString("yyyy-MM-dd hh:mm:ss"));
- obj.InspectionType = string.Format(frmtString, wo.InspectionType.ToString());
- obj.Validate();
-
-
- if (string.IsNullOrEmpty(obj.SerialNumber))
- {
- exceptions.Add(obj);
- //throw new ApplicationException("Serial Number is missing.");
- }
- else list.Add(obj);
- if (list.Count == 0)
- {
- StringBuilder sbException = new StringBuilder();
- foreach (CSVObject csvobj in exceptions)
- foreach (PropertyInfo pi in csvobj.GetType().GetProperties())
- {
- sbException.AppendLine(string.Format("{0}: {1}", pi.Name, pi.GetValue(csvobj, null)));
- }
- throw new ApplicationException(string.Format("Object Validation Error\r\n{0}", sbException.ToString()));
- }
- }
-
- filemove = Path.Combine("Success", file);// string.Format("{0}\\{1}\\{2}", _currentDir, _settings["SUCCESSDIR"], file);
- try
- {
- SqlConnection conn = new SqlConnection(_connection);
- conn.Open();
- string errorstr = CSVObject.WriteToDB(list, conn);
- conn.Close();
- conn.Dispose();
- if (!string.IsNullOrEmpty(errorstr)) throw new ApplicationException(errorstr);
- SqlCommand cmd = new SqlCommand("usp_DoImport", new SqlConnection(_connection));
- cmd.CommandTimeout = 0;
- SqlParameter sqlReturn = cmd.Parameters.Add("@b", SqlDbType.Int);
- sqlReturn.Direction = ParameterDirection.ReturnValue;
- cmd.Connection.Open();
- cmd.Connection.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMsg);
- cmd.Connection.FireInfoMessageEventOnUserErrors = true;
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.ExecuteNonQuery();
- if (Convert.ToInt32(cmd.Parameters["@b"].Value) != 0)
- throw new Exception("Error happend in the do import");
- cmd.Connection.Close();
- cmd.Dispose();
- conn.Dispose();
- SqlCommand delcmd = new SqlCommand("Delete Results_Brandt", new SqlConnection(_connection));
- delcmd.CommandTimeout = 0;
- delcmd.Connection.Open();
- delcmd.CommandType = CommandType.Text;
- try
- {
-
- delcmd.ExecuteNonQuery();
- }
- catch (Exception dex)
- {
- throw new Exception(dex.Message);
- }
- delcmd.Connection.Close();
- delcmd.Dispose();
- }
- catch (Exception exSql)
- {
- string msg = exSql.Message;
- string logmsg = string.Format("Date: {0} Error: {1}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"), exSql.Message);
- WriteToLog(logmsg);
- todo.Validation = exSql.Message + " " + _workOrderNumber;
- filemove = Path.Combine("Fail", todo.FileName);
- //File.Move(todo.FileName, filemove);
- //MailSvc.SendResponse(msg, _workOrderNumber);
-
- }
- Console.WriteLine("Line 584: " + filemove);
- if (File.Exists(filemove)) File.Delete(filemove);
- //File.Move(file, filemove);
- if (_log)
- {
- string successmsg = string.Format("Success Date: {0} File Name: {1} Work Order #: {2}{3}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"), file, _workOrderNumber, "********************************");
- WriteToLog(successmsg);
- if (exceptions.Count > 0)
- {
- foreach (CSVObject csvobj in exceptions)
- {
- string csvmsg = string.Format("Null Serial# Exception Date: {0} File Name: {1} Work Order #: {2}{3}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"), file, _workOrderNumber, "********************************");
- WriteToLog(csvmsg);
- }
- }
- if (_sqlMessages.Count > 0)
- {
- WriteToLog("***********************SQL Messages************************");
- foreach (string sqlmessg in _sqlMessages)
- WriteToLog(sqlmessg);
- WriteToLog("*********************End SQL Messages**********************");
- }
- }
- using (SqlConnection doublecheck = new SqlConnection(_connection))
- {
- SqlCommand cmddoublecheck = doublecheck.CreateCommand();
- cmddoublecheck.Connection.Open();
- cmddoublecheck.CommandTimeout = 0;
- cmddoublecheck.CommandText = string.Format("Select MAX(ID) from WorkOrder where Number = '{0}'", wo.Number);
- cmddoublecheck.CommandType = CommandType.Text;
- int rslt = (cmddoublecheck.ExecuteScalar() == DBNull.Value ? 0 : (int)cmddoublecheck.ExecuteScalar());
-
-
-
- cmddoublecheck.Dispose();
- if (rslt > 0)
- {
- cmddoublecheck.CommandText = string.Format("Select ID from Inspection where workorderid = {0}", rslt);
- rslt = (cmddoublecheck.ExecuteScalar() == DBNull.Value ? 0 : (int)cmddoublecheck.ExecuteScalar());
- if (rslt > 0)
- {
- todo.Success = true;
- //MailSvc.SendResponse("Work Order was imported successfully.", wo.Number);
- }
- else
- {
- //string noTemplate = string.Format("Work Order was created successfully. However, it appears there is no template for this model: {0}", eq.Model);
- todo.Validation = todo.Validation + "\r\n" + string.Format("Work Order was created successfully. However, it appears there is no template for this model: {0}", eq.Model);
- todo.Success = false;
- }
- }
- else
- {
- todo.Validation = todo.Validation + "\r\n" + string.Format("Failed to import work order {0}", wo.Number);//)
- }
- //MailSvc.SendResponse(string.Format("Failed to import work order {0}.", wo.Number), wo.Number);
- }
- }
- //Console.ReadLine();
-
-
- }
- catch (Exception ex)
- {
-
- string exMesg = string.Empty;
- try
- {
- exMesg = string.Format("Date: {0} Error: {1}\r\nError occured in line # {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"), ex.Message, line);
- }
- catch (Exception exSend)
- {
- Console.Write(exSend.Message);
-
- }
- WriteToLog(exMesg);
-
- filemove = Path.Combine("Fail", file);//, file);
-
-
-
- try
- {
- Console.WriteLine("Line 634: " + file);
- Console.WriteLine("Line 635: " + filemove);
- //File.Move(file, filemove);
- }
- catch (Exception moveExcept)
- {
- Console.WriteLine(moveExcept.Message);
- }
- todo.Success = false;
- todo.Validation = todo.Validation + "\r\n" + string.Format("Failed to import work order {0}. Error: {1}", wo.Number, exMesg);
- //MailSvc.SendResponse(string.Format("Failed to import work order {0}. Error: {1}", wo.Number, exMesg), wo.Number, filemove);
- }
- }
- private static void CreateLogFile(string logfile)
- {
- using (StreamWriter sw = File.CreateText(logfile))
- {
- sw.WriteLine("******************************************");
- sw.WriteLine("****************IMPORT LOG****************");
- sw.WriteLine("******************************************");
- }
- }
-
- public static void WriteToLog(string message, string sqlmessage = "")
- {
- string logfile = Path.Combine("Log", "log.log");
- if (!File.Exists(logfile))
- {
- CreateLogFile(logfile);
- }
- using (StreamWriter sw = File.AppendText(logfile))
- {
- sw.WriteLine(message);
- if (!string.IsNullOrEmpty(sqlmessage))
- sw.WriteLine(sqlmessage);
- }
- }
-
-
- public static bool IsWindows() =>
- System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows);
-
- public static bool IsMacOS() =>
- System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX);
-
- public static bool IsLinux() =>
- System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux);
- }
-
- public class ToDo
- {
- private bool _success = false;
- public bool Success { get { return _success; } set { _success = value; } }
- public string Sender { get; set; }
- public string SenderName { get; set; }
- public string FileName { get; set; }
- public string Validation { get; set; }
-
- public string WorkOrderNumber { get; set; }
- }
- }
|