|
- 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;
-
- /*
- 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 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;";
- private static string _workOrderNumber = string.Empty;
- private static List<string> _sqlMessages = new List<string>();
- private static bool _newMachine = 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;
- static async System.Threading.Tasks.Task Main(string[] args)
- {
- _exeDir = Environment.CurrentDirectory;
- SetupDirectories();
- List<ToDo> list = new List<ToDo>();
- var cca = ConfidentialClientApplicationBuilder
- // .Create("1dff6bdb-7009-4d2a-ae0f-9f333a4f182b")
- // .WithClientSecret("VOD8Q~7BI9u4ySU0saesCG87TaEtKSCya5vw6as5")
- // .WithTenantId("1fd06c96-d3a4-45e9-9ed7-bcecb394d277")
- .Create(_keys["AppID"])
- .WithClientSecret(_keys["SecretV"])
- .WithTenantId(_keys["TenentID"])
- .Build();
-
- var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
- try
- {
- 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;
- FindItemsResults<Item> findResults = ewsClient.FindItems(fid, searchFilter, view);
- 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(_exeDir, fAttachment.FileName);
- File.WriteAllBytes(fileAttachmentPath, fAttachment.Content);
- msg.IsRead = true;
- }
- }
- }
- }
- }
- foreach (ToDo import in list)
- {
-
- //Start Importing
- BeginImport(import);
- GetInspectionTypes();
- ReadFile(import);
- }
- foreach (ToDo sendMsg in list)
- {
- EmailMessage msgToSend = new EmailMessage(ewsClient);
- string body = "JDIS File: {0} Work Order:{1} {2}";
- if (sendMsg.Success)
- {
- body = string.Format(body, sendMsg.FileName, sendMsg.WorkOrder, "Was Imported Successfully");
- }
- else
- {
- body = string.Format(body, sendMsg.FileName, sendMsg.WorkOrder, string.Format("Had Errors while importing: {0}", sendMsg.Validation));
- msgToSend.Attachments.AddFileAttachment(Path.Combine(_exeDir, sendMsg.FileName)
-
- }
-
- msgToSend.Subject = sendMsg.FileName;
- msgToSend.ToRecipients.Add(new EmailAddress(sendMsg.Sender));
- msgToSend.CcRecipients.Add(new EmailAddress("mcarman@rpmindustries.com"));
- msgToSend.Body = body;
- msgToSend.SendAndSaveCopy();
- string pathToFile = Path.Combine(_exeDir, sendMsg.FileName);
- if (sendMsg.Success) File.Move(pathToFile, Path.Combine(_exeDir, "Success", sendMsg.FileName));
- else File.Move(sendMsg.FileName, Path.Combine(_exeDir, "Fail", sendMsg.FileName));
- }
- }
- catch (MsalException ex)
- {
- Console.WriteLine($"Error acquiring access token: {ex}");
- }
- catch (Exception ex)
- {
- Console.WriteLine($"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()
- {
- 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()
- {
- InspectionType = new Dictionary<string, int>();
- SqlConnection con = new SqlConnection("Data Source=192.168.0.7;Initial Catalog=Connexion_Brandt;User ID=mobilepmuser;Password=data4techs;");
- con.Open();
- SqlCommand cmd = con.CreateCommand();
- cmd.CommandTimeout = 0;
- cmd.Connection = con;
- cmd.CommandText = "Select ID, [Name] From InspectionType";
- cmd.CommandType = CommandType.Text;
- DataSet ds = new DataSet();
- SqlDataAdapter da = new SqlDataAdapter(cmd);
- da.Fill(ds);
- foreach (DataRow row in ds.Tables[0].Rows)
- {
- InspectionType.Add(row["Name"].ToString(), Convert.ToInt32(row["ID"]));
- }
- ds.Dispose();
- cmd.Dispose();
- con.Close();
- con.Dispose();
-
- }
- 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(_exeDir, todo.FileName);// todo.FileName;
- todo.FileName = file;
- Customer c = new Customer();
- WorkOrder wo = new WorkOrder();
- Equipment eq = new Equipment();
- List<Part> parts = new List<Part>();
-
- 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.WorkOrder = 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(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"))
- {
- Part pt = new Part();
- 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)
- {
- Part p = new Part();
- p.Description = string.Empty;
- p.Qty = string.Empty;
- p.Number = string.Empty;
- parts.Add(p);
-
- }
- static void conn_InfoMsg(object sender, SqlInfoMessageEventArgs e)
- {
- _sqlMessages.Add(e.Message);
- }
-
- foreach (Part 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 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 WorkOrder { get; set; }
- }
- }
|