/* UPDATE ZLASTSYNC set lastSync = "23/01/2020 4:49:41 AM" * where Mapping_ID not in (SELECT ID FROM ZMAPPING WHERE TYPE IN ("API") ); * DELETE FROM ZQUEUE; */ public static bool RunSQLLiteCmd(string token, Zmapping cmd) { using (var db = new ZudelloContext()) { try { //Exceute the custom command db.Database.ExecuteSqlCommand(cmd.Body); db.SaveChanges(); //Remove custom command from database FK var lastSyncQuery = db.Zlastsync.Where(z => z.MappingId == cmd.Id).FirstOrDefault(); var mappingTbl = db.Zmapping.Where(z => z.uuid == cmd.uuid); foreach (Zmapping sqlQuery in mappingTbl) { //Dont need to remove as its never added into sync table // db.Remove(lastSyncQuery); // db.SaveChanges(); db.Remove(sqlQuery); db.SaveChanges(); //Send delete request to Zudello to remove from mappings table Console.WriteLine(ZudelloLogin.DeleteMapping(token, cmd.uuid)); } return(true); } catch (Exception ex) { return(false); } } }
public static Dictionary <int, Zmapping> getBody() { Dictionary <int, Zmapping> myMappings = new Dictionary <int, Zmapping>(); using (var db = new ZudelloContext()) { var MapID = db.Zmapping.Where(i => i.IsOutgoing == 1).OrderBy(k => k.ProcessOrder).ToList(); foreach (var mappings in MapID) { Zmapping Data = new Zmapping() { DocType = mappings.DocType, Body = mappings.Body, Section = mappings.Section, Id = mappings.Id }; myMappings.Add(mappings.Id, Data); } return(myMappings); } }
public static GpMappingAndDatabase GetMappingAndDatabase(string Type = "", string connectionId = "") { GpMappingAndDatabase mapDb = new GpMappingAndDatabase(); using (var db = new ZudelloContext()) { var myConnectionID = db.Zconnections.Where(c => c.ConnectionUuid == connectionId).FirstOrDefault(); var MapID = db.Zmapping.Where(i => i.DocType == Type && i.IsOutgoing == 0 && i.connection_id == myConnectionID.Id); int count = MapID.Count(); if (count > 1) { return(null); // if there is the same mapping in the connection will return null hehe } foreach (var id in MapID) { mapDb.Id = myConnectionID.Id; mapDb.InitialCatalog = myConnectionID.InitialCatalog; mapDb.DataSource = myConnectionID.DataSource; mapDb.IntergrationType = myConnectionID.IntergrationType; mapDb.mappingID = id.Id; return(mapDb); } } return(null); }
public static Dictionary <int, Zmapping> getBody() { Dictionary <int, Zmapping> myMappings = new Dictionary <int, Zmapping>(); using (var db = new ZudelloContext()) { int i = 0; var MapID = db.Zmapping.Where(c => c.IsOutgoing == 1).ToList(); foreach (var mappings in MapID.OrderBy(c => c.ProcessOrder).ThenByDescending(l => l.connection_id)) { Zmapping Data = new Zmapping() { DocType = mappings.DocType, Body = mappings.Body, Section = mappings.Section, database = mappings.database, Id = mappings.Id, connection_id = mappings.connection_id }; myMappings.Add(i, Data); i++; } return(myMappings); } }
public static async Task SetSyncTable() { using (var db = new ZudelloContext()) { var toSet = (from zm in db.Zmapping join zs in db.Zlastsync on zm.Id equals zs.MappingId into r from zs in r.DefaultIfEmpty() where zs == null select zm).ToList(); foreach (var s in toSet) { Zlastsync lastSyncTable = new Zlastsync(); lastSyncTable.MappingId = s.Id; if (s.Type == "API") { lastSyncTable.LastSync = "2000-11-20T05:55:29.000Z"; } else { lastSyncTable.LastSync = DateTime.UtcNow.AddYears(-100).ToString(); } db.Add(lastSyncTable); db.SaveChanges(); Console.WriteLine(String.Format("Sync Table Updated:{0}, {1} ", s.DocType, s.Type)); } } }
public static void SaveToDB(string kfiName, string jsonBody) { using (var db = new ZudelloContext()) { //db.Files.Add() // db.Zfiles.Add(new Zfiles { JsonData = jsonBody }); db.SaveChanges(); } }
public static void SaveToDBQueue(string rawJson, int type, string status, GpMappingAndDatabase map) { using (var db = new ZudelloContext()) { db.Zqueue.Add(new Zqueue { Body = rawJson, MappingId = type, Status = status, ConnectionId = map.Id }); db.SaveChanges(); } }
public static AttacheConfiguration GetAttacheSettings() { AttacheConfiguration config = new AttacheConfiguration(); using (var db = new ZudelloContext()) { var myConfig = db.Zsettings.Where(s => s.Key == "AttacheSettings").FirstOrDefault(); AttacheConfiguration C = JsonConvert.DeserializeObject <AttacheConfiguration>(myConfig.Value); config = C; } return(config); }
public static ConnectionUuid GetZudelloQueueConnection() { ConnectionUuid config = new ConnectionUuid(); using (var db = new ZudelloContext()) { var myConfig = db.Zsettings.Where(s => s.Key == "ZudelloConnectionUuid").FirstOrDefault(); ConnectionUuid C = JsonConvert.DeserializeObject <ConnectionUuid>(myConfig.Value); config = C; } return(config); }
public static ZudelloInitalSettings GetZudelloSettings() { ZudelloInitalSettings config = new ZudelloInitalSettings(); using (var db = new ZudelloContext()) { var myConfig = db.Zsettings.Where(s => s.Key == "ZudelloSettings").FirstOrDefault(); ZudelloInitalSettings C = JsonConvert.DeserializeObject <ZudelloInitalSettings>(myConfig.Value); config = C; } return(config); }
public static void RunResponse(ConcurrentDictionary <int, ProccessResponse> successDictionary) { string Token = ZudelloLogin.Login(); List <Zconnections> teams = new List <Zconnections>(); using (var db = new ZudelloContext()) { //Maybe hash the records teams = db.Zconnections.ToList(); } foreach (var update in successDictionary) { int counter = 0; //think there is a bug with duplicate invoices trying to be processed. ProccessResponse pr = successDictionary.Values.FirstOrDefault(); if (pr.Team == null) { continue; } string success = "Succuess"; string msg = pr.Information; Response sendHome = new Response(); sendHome.body = pr.Information; sendHome.status = 200; sendHome.uuid = pr.SyncHistryUuid; if (pr.Successful == false) { sendHome.status = 500; } string body = JsonConvert.SerializeObject(sendHome); try { Console.WriteLine(ZudelloLogin.SendProcessResponse(Token, body, pr.Team)); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Message); Console.WriteLine(ex.InnerException); } } }
public static FirstLoginBody ZudelloCredetials() { FirstLoginBody config = new FirstLoginBody(); using (var db = new ZudelloContext()) { var myConfig = db.Zsettings.Where(s => s.Key == "ZudelloCredetials").FirstOrDefault(); FirstLoginBody C = JsonConvert.DeserializeObject <FirstLoginBody>(myConfig.Value); config = C; } return(config); }
public static async Task AttacheResponseSender() { string token = ZudelloLogin.Login(); ResponseZudello ResponseStatus = new ResponseZudello(); using (var db = new ZudelloContext()) { var queueList = db.Zqueue.Where(i => i.Status == "Success" && (i.ResponseSent == 0)).ToList(); try { foreach (var l in queueList) { ResponseObject successList = new ResponseObject(); dynamic Body = JObject.Parse(l.Body); successList.body = "Success"; successList.uuid = Body.uuid; successList.queueid = l.Id; successList.status = 200; ResponseStatus.data.Add(successList); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("Master Data"); } foreach (var data in ResponseStatus.data) { string responseBody = JsonConvert.SerializeObject(data); HttpStatusCode Response = ZudelloLogin.SendProcessResponse(token, responseBody); if (Response == HttpStatusCode.OK) { var updateSent = db.Zqueue.Where(i => i.Id == data.queueid).FirstOrDefault(); updateSent.ResponseSent = 1; db.SaveChanges(); } } db.Dispose(); } }
public static bool InQueue(int?mappingId, string toSearch) { using (var db = new ZudelloContext()) { //Maybe hash the records var MapID = db.Zqueue.Where(i => i.MappingId == mappingId && i.Body.Contains(toSearch)); int count = MapID.Count(); db.DisposeAsync(); if (count > 0) { return(true); } else { return(false); } } }
public static bool CheckForMasterData() { bool masterData = false; using (var db = new ZudelloContext()) { //var query = db.Zqueue.Where(a => a.Ztype > 10 && a.Sucess == 0 || a.Sucess == null).Count(); var query = 1; if (query > 0) { masterData = true; } return(masterData); } }
public static string fetchconnection(int connection_id) { //Method used to return the queue string try { using (var db = new ZudelloContext()) { var connectionID = db.Zconnections.Where(s => s.Id == connection_id).FirstOrDefault(); return("'" + connectionID.ConnectionUuid.ToString() + "'"); } } catch (Exception ex) { Console.WriteLine(ex.Message); return("was an Issue with connection ID"); } }
public static string LastSync(int mappingId, string pattern = "yyyy-MM-dd HH:mm:ss") { try { using (var db = new ZudelloContext()) { var lastSync = db.Zlastsync.Where(s => s.MappingId == mappingId).FirstOrDefault(); DateTime dateTime = DateTime.Parse(lastSync.LastSync); return("'" + dateTime.ToString(pattern) + "'"); } } catch (Exception ex) { Console.WriteLine(ex.Message); return("was an Issue with last Sync"); } }
public static ConnectionUp CheckSqlLiteConnection() { ConnectionUp up = new ConnectionUp(); try { using (var db = new ZudelloContext()) { db.Database.CanConnect(); up.status = true; // status.Add(true, "Connection Up"); return(up); } } catch (Exception ex) { up.status = false; up.exMessage = ex.Message; return(up); } }
public static ExoMappingAndDB GetMappingAndDatabase(string Type = "", string connectionId = "") { ExoMappingAndDB mapDb = new ExoMappingAndDB(); using (var db = new ZudelloContext()) { var myConnectionID = db.Zconnections.Where(c => c.ConnectionUuid == connectionId).FirstOrDefault(); var MapID = db.Zmapping.Where(i => i.DocType == Type && i.IsOutgoing == 0 && i.connection_id == myConnectionID.Id); int count = 0; try { count = MapID.Count(); } catch { } if (count > 1) { return(null); } foreach (var id in MapID) { mapDb.Id = myConnectionID.Id; mapDb.InitialCatalog = myConnectionID.InitialCatalog; mapDb.DataSource = myConnectionID.DataSource; mapDb.IntergrationType = myConnectionID.IntergrationType; mapDb.mappingID = id.Id; return(mapDb); } db.DisposeAsync(); } return(null); }
public static List <HealthSync> HealthSyncCheck() { List <HealthSync> hs = new List <HealthSync>(); try { using (var db = new ZudelloContext()) { var queueStatus = (from p in db.Zlastsync join c in db.Zmapping on p.MappingId equals c.Id select new { p, c }).ToList(); foreach (var status in queueStatus) { try { HealthSync hsObj = new HealthSync(); hsObj.docType = status.c.DocType; hsObj.type = status.c.Type; hsObj.LastSync = status.p.LastSync; hsObj.lastID = status.p.lastID; hs.Add(hsObj); } catch { } } return(hs); } } catch (Exception ex) { HealthSync hsObj = new HealthSync(); hsObj.exMessage = ex.Message; return(hs); } }
public static int?GetMappingTypeID(string Type = "") { using (var db = new ZudelloContext()) { var MapID = db.Zmapping.Where(i => i.DocType == Type && i.IsOutgoing == 0); int count = MapID.Count(); if (count > 1) { return(null); } foreach (var id in MapID) { // Console.WriteLine("Found ID"); return(id.Id); } } return(null); }
public static void RunSuccessUpdate(ConcurrentDictionary <int, ProccessResponse> successDictionary) { foreach (var update in successDictionary) { ProccessResponse pr = successDictionary.Values.FirstOrDefault(); int counter = 0; string success = "Succuess"; string msg = pr.Information; if (pr.Successful == false) { success = "Failed"; } using (var db = new ZudelloContext()) { var queue = db.Zqueue.Where(i => i.Id == update.Key).FirstOrDefault(); queue.Status = success; queue.Exception = msg; db.SaveChangesAsync(); counter++; //Maybe add in logic later if all is not updated then handel errors. db.DisposeAsync(); } } }
public static List <QueueHealth> QueueHealthCheck() { List <QueueHealth> qh = new List <QueueHealth>(); try { using (var db = new ZudelloContext()) { var queueStatus = from p in db.Zqueue group p by p.Status into g select new { status = g.Key, count = g.Count() }; foreach (var status in queueStatus) { QueueHealth statusObj = new QueueHealth(); statusObj.status = status.status; statusObj.count = status.count; qh.Add(statusObj); } return(qh); } } catch (Exception ex) { QueueHealth statusObj = new QueueHealth(); statusObj.exMessage = ex.Message; qh.Add(statusObj); return(qh); } }
public static bool updateQueue(string queueId, string status) { try { int id = 0; if (Int32.TryParse(queueId, out id)) { using (var db = new ZudelloContext()) { var queueUpdate = db.Zqueue.Where(i => i.Id == id).FirstOrDefault(); queueUpdate.Status = status; db.SaveChanges(); return(true); } } return(false); } catch (Exception ex) { return(false); } }
public static int?SaveToDBQueue(string rawJson, int type, string status, ExoMappingAndDB map, int?linkedId = null) { try { using (var db = new ZudelloContext()) { var res = db.Zqueue.Add(new Zqueue { Body = rawJson, MappingId = type, Status = status, ConnectionId = map.Id, Queue_Id = linkedId }); db.SaveChanges(); db.DisposeAsync(); return(res.Entity.Id); } } catch (Exception ex) { return(null); } }
public static void PushGpDataToZudello() { string Token = ZudelloLogin.Login(); SQLCredentials ConnectionString = new SQLCredentials(); Dictionary <int, string> Connection = ConnectionString.ConnectionStringBuilder(); /**** * * Add threading into here for the foreach loop * will need to chunk based on amount of connections */ //get the query from mappings table foreach (var Mappings in getBody()) { //bool isXml = false; //Get the SQL statement string mySql = Mappings.Value.Body; //Get the Mappings dynamic zudelloObject = Mappings.Value; string SQLQuery = GpTools.RenderToSql(mySql, zudelloObject); //if (mySql.Contains("XML PATH")) isXml = true; #warning make this in config also for process method string cmd = SQLQuery; //Open SQL connection and run the SQL query //Get connection details by Key ID SqlConnection con = new SqlConnection(Connection[Mappings.Value.connection_id]); SqlCommand SelectCommand = new SqlCommand(cmd, con); // SqlDataReader myreader; con.Open(); var jsonResult = new StringBuilder(); var myreader = SelectCommand.ExecuteReader(); if (!myreader.HasRows) { //if there is no data then close connection and next loop con.Close(); continue; } else { while (myreader.Read()) { jsonResult.Append(myreader.GetValue(0).ToString()); } dynamic obj; //Console.WriteLine(jsonResult); obj = JsonConvert.DeserializeObject <ExpandoObject>(jsonResult.ToString()); foreach (var ObjectType in obj) { foreach (var dataValues in ObjectType.Value) { MyQueueObject dataWrapper = new MyQueueObject(); dataWrapper.data = dataValues; string data = JsonConvert.SerializeObject(dataWrapper); Console.WriteLine(data); Console.WriteLine(ZudelloLogin.SendToZudelloQueue(Token, data)); } } //Update last sync time for this mapping ID using (var db = new ZudelloContext()) { var lastSync = db.Zlastsync.Where(s => s.MappingId == Mappings.Value.Id).FirstOrDefault(); lastSync.LastSync = DateTime.Now.ToString(); db.SaveChanges(); } } con.Close(); } }
public static async Task PushExoDataToZudello() { string Token = ZudelloLogin.Login(); SQLCredentials ConnectionString = new SQLCredentials(); Dictionary <int, string> Connection = ConnectionString.ConnectionStringBuilder(); /**** * * Add threading into here for the foreach loop * will need to chunk based on amount of connections */ //get the query from mappings table Dictionary <int, Zmapping> MappingsBody = getBody(); int numberOfLogicalCores = Environment.ProcessorCount; List <Thread> threads = new List <Thread>(numberOfLogicalCores); int sizeOfOneChunk = (MappingsBody.Count / numberOfLogicalCores) + 1; ConcurrentBag <string> cb = new ConcurrentBag <string>(); ConcurrentBag <int> cbMaps = new ConcurrentBag <int>(); for (int i = 0; i < numberOfLogicalCores; i++) { int ab = i; var thr = new Thread( () => { try { int count = 0; Dictionary <int, Zmapping> MappingsChunked = MappingsBody.Skip(ab * sizeOfOneChunk) .Take(sizeOfOneChunk).ToDictionary(p => p.Key, p => p.Value); foreach (var Mappings in MappingsChunked) { bool isXMl = true; //Get the SQL statement string mySql = Mappings.Value.Body; //Get the Mappings dynamic zudelloObject = Mappings.Value; string SQLQuery = ExoTools.RenderToSql(mySql, zudelloObject); #warning make this in config also for process method string cmd = SQLQuery; //Open SQL connection and run the SQL query //Get connection details by Key ID SqlConnection con = new SqlConnection(Connection[Mappings.Value.connection_id]); SqlCommand SelectCommand = new SqlCommand(cmd, con); // SqlDataReader myreader; con.Open(); if (cmd.ToLower().Contains("for xml")) { isXMl = true; } if (String.IsNullOrEmpty(cmd)) { continue; } var jsonResult = new StringBuilder(); var xmlConvert = new StringBuilder(); //SelectCommand.CommandText = cmd; var myreader = SelectCommand.ExecuteReader(); if (!myreader.HasRows) { //if there is no data then close connection and next loop con.Close(); con.Dispose(); continue; } else { while (myreader.Read()) { jsonResult.Append(myreader.GetValue(0).ToString()); } //Console.WriteLine(jsonResult); dynamic obj = ""; string ConvertedXml = ""; if (isXMl == true) { ConvertedXml = ExoTools.ZudelloXMLConverter(jsonResult.ToString()); // string ConvertedXml = ExoTools.ZudelloXMLConverter(jsonResult.ToString()); obj = JsonConvert.DeserializeObject <ExpandoObject>(ConvertedXml); } else { obj = JsonConvert.DeserializeObject <ExpandoObject>(jsonResult.ToString()); } foreach (var ObjectType in obj) { //not sure why .Value is causing error but not affecting build foreach (var dataValues in ObjectType.Value) { string data = ""; if (isXMl == true) { data = JsonConvert.SerializeObject(dataValues); } else { MyQueueObject dataWrapper = new MyQueueObject(); dataWrapper.data = dataValues; data = JsonConvert.SerializeObject(dataWrapper); } // add to concurrent bag cb.Add(data); count++; // Console.WriteLine(data); } } cbMaps.Add(Mappings.Value.Id); } con.Close(); con.Dispose(); } } catch (Exception ex) { } } ); threads.Add(thr); } foreach (var thread in threads) { thread.Start(); } foreach (var thread in threads) { thread.Join(); } threads.Clear(); int sizeOfOneChunkQueue = (cb.Count / numberOfLogicalCores) + 1; for (int x = 0; x < numberOfLogicalCores; x++) { int abx = x; var SendToQueuethr = new Thread( () => { try { int count = 0; List <string> queuedBag = cb.Skip(abx * sizeOfOneChunkQueue) .Take(sizeOfOneChunkQueue).ToList(); foreach (var Mappings in queuedBag) { Console.WriteLine(ZudelloLogin.SendToZudelloQueue(Token, Mappings)); } } catch (Exception ex) { } }); threads.Add(SendToQueuethr); } foreach (var qthread in threads) { qthread.Start(); } foreach (var qthread in threads) { qthread.Join(); } /* * List<Task> bagConsumeTasks = new List<Task>(); * int itemsInBag = 0; * while (!cb.IsEmpty) * { * bagConsumeTasks.Add(Task.Run(() => * { * string item; * if (cb.TryTake(out item)) * { * * Console.WriteLine(ZudelloLogin.SendToZudelloQueue(Token, item)); * itemsInBag++; * } * })); * } */ // Task.WaitAll(bagConsumeTasks.ToArray()); foreach (int id in cbMaps) { using (var db = new ZudelloContext()) { var lastSync = db.Zlastsync.Where(s => s.MappingId == id).FirstOrDefault(); lastSync.LastSync = DateTime.Now.ToString(); db.SaveChanges(); db.DisposeAsync(); } } }
public static bool Hash(string Json, int mappingId) { string sSourceData; byte[] tmpSource; byte[] tmpHash; bool bEqual = false; sSourceData = Json; //Create a byte array from source data tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData); //Compute hash based on source data tmpHash = new MD5CryptoServiceProvider().ComputeHash(tmpSource); List <byte[]> sent = new List <byte[]>(); using (var db = new ZudelloContext()) { var HashLog = (from a in db.Zhashlog where a.MappingId == mappingId select a); Zhashlog h = new Zhashlog(); if (HashLog.Count() < 1) { h.MappingId = mappingId; h.Hash = tmpHash; db.Add(h); db.SaveChanges(); } else { foreach (var hash in HashLog) { sent.Add(hash.Hash); } foreach (var hsh in sent) { if (hsh.Length == tmpHash.Length) { int i = 0; while ((i < hsh.Length) && (hsh[i] == tmpHash[i])) { i += 1; } if (i == hsh.Length) { bEqual = true; } } } if (bEqual == false) { Console.WriteLine("The two hash values are not the same"); Zhashlog ha = new Zhashlog(); ha.MappingId = mappingId; ha.Hash = tmpHash; db.Add(ha); db.SaveChanges(); Console.WriteLine("hash Added"); return(bEqual); } else { Console.WriteLine("Values are the same"); return(bEqual); } } } return(bEqual); }
public static List <ErrorData> KfiErrorGetter() { List <ErrorData> errList = new List <ErrorData>(); try { using (var db = new ZudelloContext()) { //Get a list of all failed items. var failureQueue = db.Zqueue.Where(i => i.Status == "Failure").Select(s => s.Id).ToList(); //Get a List of all .eer Files AttacheConfiguration FolderNames = ZudelloSetup.GetAttacheSettings(); var Fdir = FolderNames.AttacheInbox + "Failure"; DirectoryInfo d = new DirectoryInfo(Fdir); FileInfo[] Files = d.GetFiles("*.err"); List <string> err = new List <string>(); foreach (FileInfo file in Files) { ErrorData errData = new ErrorData(); //Check if failed item is part of queue try { int index1 = file.FullName.LastIndexOf('_'); string queueId = Regex.Match(file.FullName.Substring(index1), @"\d+").Value; // Convert to int to check int id = 0; Int32.TryParse(queueId, out id); if (failureQueue.Contains(id)) { //Send to Zudello this error File. errData.errorFile = File.ReadAllText(file.FullName); // Console.WriteLine(File.ReadAllText(file.FullName)); FileInfo[] originalKfi = d.GetFiles(String.Format("*_{0}.kfi", id.ToString())); //Get the Original KFI //Console.WriteLine(File.ReadAllText(originalKfi.FirstOrDefault().FullName)); try { errData.originalFile = File.ReadAllText(originalKfi.FirstOrDefault().FullName); // Console.ReadLine(); } catch (Exception ex) { //If we cannot locate original errData.originalFile = ex.Message; } //Bool check to confirm error file was sent to zudello. var updateQuery = db.Zqueue.Where(i => i.Id == id).FirstOrDefault(); errData.body = JsonConvert.DeserializeObject(updateQuery.Body); updateQuery.Status = "ZudelloReview"; db.SaveChanges(); errList.Add(errData); } else { //Next Item already been sent to Zudello continue; } } catch (Exception ex) { return(errList); } } return(errList); } } catch (Exception ex) { return(errList); } }
public static string OrderSelect(dynamic data, int type = 0) { //Dictionary<int, Zmapping> orders = AttacheFetchData.getBody(); string query = ""; using (var db = new ZudelloContext()) { var body = db.Zmapping.Where(i => i.DocType == "PURCHASING::RECEIVE:QUERY").FirstOrDefault(); query = body.Body; } dynamic myObj = JsonConvert.DeserializeObject <ExpandoObject>(query); string myQuery = ""; string myLineQuery = ""; if (type == 0) { myQuery = myObj.HDR_QUERY.ToString(); myLineQuery = myObj.LINE_QUERY.ToString(); } else { //Invoice line type required different query myQuery = myObj.HDR_QUERY_INVOICE.ToString(); myLineQuery = myObj.LINE_QUERY_INVOICE.ToString(); } // Loop through and get the data.Receive IDs. Dictionary <int, LineReceipting> lineReceipting = new Dictionary <int, LineReceipting>(); List <string> internalDocNbr = new List <string>(); try { int i = 0; foreach (var id in data.document.lines) { foreach (var nbr in id.receive) { LineReceipting LineData = new LineReceipting(); if (!internalDocNbr.Contains(nbr.remote_order_id.ToString())) { internalDocNbr.Add(nbr.remote_order_id.ToString()); LineData.internalNbr = nbr.remote_order_id.ToString(); LineData.lineNbr = nbr.line.ToString(); #warning Taken out for general testing // LineData.poNbr = nbr.number.ToString(); LineData.receiptQty = nbr.qty.ToString(); } i = i + 1; lineReceipting.Add(i + 1, LineData); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } string accountCode = data.document.supplier.code.ToUpper(); string poNbr = String.Join(", ", internalDocNbr.ToArray()); //Hdr myQuery = myQuery.Replace("{po_number}", poNbr); myQuery = myQuery.Replace("{account_code}", accountCode); //Lines myLineQuery = myLineQuery.Replace("{po_number}", poNbr); //Query to get HDR DataSet orderData = AttacheFetchData.GetDataSet(myQuery); List <string> Sequence = new List <string>(); foreach (DataTable dt in orderData.Tables) { foreach (DataRow dr in dt.Rows) { foreach (DataColumn dc in dt.Columns) { Sequence.Add(dr[dc.ColumnName].ToString()); } } } //Query to get lines DataSet lineOrderData = AttacheFetchData.GetDataSet(myLineQuery); // List<string> LineSequence = new List<string>(); //Might need to put this as its own Function where uesr can specific the sequence ie ,,,,,,,,,20,204, or extra. List <object[]> MyLineSequence = new List <object[]>(); foreach (DataTable dt in lineOrderData.Tables) { foreach (DataRow dr in dt.Rows) { //Add to array MyLineSequence.Add(dr.ItemArray); } } StringBuilder lineSequence = new StringBuilder(); foreach (var obj in MyLineSequence) { //Get the sequence to return, looking at dictionary to comapre. foreach (var dic in lineReceipting) { if (dic.Value.internalNbr == obj[1].ToString() && dic.Value.lineNbr == obj[2].ToString()) { lineSequence.Append(dic.Value.receiptSeq.Replace("0", dic.Value.receiptQty.ToString())); //not sure if this is needed, but still works? lineReceipting.Remove(dic.Key); break; } else { lineSequence.Append(dic.Value.receiptSeq); break; } } } // Console.ReadLine(); StringBuilder upSequence = new StringBuilder(); int lineUp = MyLineSequence.Count(); for (int i = 0; i < lineUp; i++) { upSequence.Append("<UP>"); } // string lineValues //Maybe walk object in scribian //or here need to now use ,,,0<F9> if not part of receipt. //Maybe put in query. string returnSequence = String.Join("", Sequence.ToArray()); Console.WriteLine(returnSequence); Console.ReadLine(); returnSequence = returnSequence + "<F9>" + upSequence.ToString() + lineSequence.ToString(); Console.WriteLine(returnSequence); return(returnSequence); }