Esempio n. 1
0
 // ===========
 // Constructor
 // ===========
 public ISPOSTrnStockTransferInController(Forms.TrnIntegrationForm form, String actDate)
 {
     trnIntegrationForm = form;
     activityDate       = actDate;
 }
        // =================
        // Send Disbursement
        // =================
        public async void SendDisbursement(Forms.TrnIntegrationForm trnIntegrationForm, String userCode, String file, String domain)
        {
            trnIntegrationForm.folderMonitoringLogMessages("\r\n\nOpening File: " + file + " \r\n\n");

            List <Entities.FolderMonitoringTrnDisbursement> newDisbursements = new List <Entities.FolderMonitoringTrnDisbursement>();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            String jsonData = "";

            // ========
            // Cleaning
            // ========
            trnIntegrationForm.folderMonitoringLogMessages("\r\n\nCleaning Disbursement... (0%) \r\n\n");
            while (true)
            {
                try
                {
                    String deleteTemporaryDisbursementTask = await DeleteTemporaryDisbursement(domain);

                    if (!deleteTemporaryDisbursementTask.Equals("Clean Successful..."))
                    {
                        trnIntegrationForm.folderMonitoringLogMessages(deleteTemporaryDisbursementTask);
                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                        trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                        Thread.Sleep(5000);
                    }
                    else
                    {
                        trnIntegrationForm.folderMonitoringLogMessages("CVIntegrationLogOnce");

                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\nCleaning Disbursement... (100%) \r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Clean Successful!" + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                        break;
                    }
                }
                catch (Exception e)
                {
                    trnIntegrationForm.folderMonitoringLogMessages("Error: " + e.Message + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                    trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                    Thread.Sleep(5000);
                }
            }

            // ================
            // Reading CSV Data
            // ================
            trnIntegrationForm.folderMonitoringLogMessages("Reading CSV Data... (0%) \r\n\n");
            while (true)
            {
                newDisbursements = new List <Entities.FolderMonitoringTrnDisbursement>();

                try
                {
                    if (SysFileControl.IsCurrentFileClosed(file))
                    {
                        Int32 count = 0;

                        using (StreamReader dataStreamReader = new StreamReader(file))
                        {
                            dataStreamReader.ReadLine();
                            while (dataStreamReader.Peek() >= 0)
                            {
                                count += 1;

                                List <String> data = dataStreamReader.ReadLine().Split(',').ToList();
                                newDisbursements.Add(new Entities.FolderMonitoringTrnDisbursement
                                {
                                    BranchCode      = data[0],
                                    CVDate          = data[1],
                                    SupplierCode    = data[2],
                                    Payee           = data[3],
                                    PayType         = data[4],
                                    BankCode        = data[5],
                                    Remarks         = data[6],
                                    ManualCVNumber  = data[7],
                                    CheckNumber     = data[8],
                                    CheckDate       = data[9],
                                    IsCrossCheck    = Convert.ToBoolean(data[10]),
                                    IsClear         = Convert.ToBoolean(data[11]),
                                    UserCode        = userCode,
                                    CreatedDateTime = data[12],
                                    LineBranchCode  = data[13],
                                    AccountCode     = data[14],
                                    ArticleCode     = data[15],
                                    RRNumber        = data[16],
                                    ManualRRNumber  = data[17],
                                    Particulars     = data[18],
                                    Amount          = Convert.ToDecimal(data[19]),
                                    No = count
                                });

                                journalDate = Convert.ToDateTime(data[1]);
                            }
                        }

                        trnIntegrationForm.folderMonitoringLogMessages("CVIntegrationLogOnce");

                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\nReading CSV Data... (100%) \r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Read Successful!" + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                        break;
                    }
                    else
                    {
                        trnIntegrationForm.folderMonitoringLogMessages("Error: File: " + file + " is currently open. \r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                        trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                        Thread.Sleep(5000);
                    }
                }
                catch (Exception e)
                {
                    trnIntegrationForm.folderMonitoringLogMessages("Error: " + e.Message + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                    trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                    Thread.Sleep(5000);
                }
            }

            if (newDisbursements.Any())
            {
                // =========================
                // Checking Muliple CV Dates
                // =========================
                trnIntegrationForm.folderMonitoringLogMessages("Checking Multiple CV Dates... (0%) \r\n\n");
                while (true)
                {
                    try
                    {
                        var groupedCVDates = from d in newDisbursements group d by d.CVDate into g select g.Key;

                        var CVDates = from d in groupedCVDates.ToList() select d;
                        if (CVDates.Count() > 1)
                        {
                            trnIntegrationForm.folderMonitoringLogMessages("Checking Error: Cannot integrate multiple CV Dates. \r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                            trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                            Thread.Sleep(5000);
                        }
                        else
                        {
                            trnIntegrationForm.folderMonitoringLogMessages("CVIntegrationLogOnce");

                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\nChecking Multiple CV Dates... (100%) \r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("Check Successful!" + "\r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        trnIntegrationForm.folderMonitoringLogMessages("Error: " + e.Message + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                        trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                        Thread.Sleep(5000);
                    }
                }

                Boolean post = false;

                // =======
                // Sending
                // =======
                trnIntegrationForm.folderMonitoringLogMessages("Sending Disbursement... (0%) \r\n\n");
                while (true)
                {
                    try
                    {
                        Decimal percentage = 0;

                        Boolean send = false;
                        Int32   skip = 0;

                        for (Int32 i = 1; i <= newDisbursements.Count(); i++)
                        {
                            if (i % 100 == 0)
                            {
                                jsonData = serializer.Serialize(newDisbursements.Skip(skip).Take(100));
                                skip     = i;

                                send       = true;
                                percentage = Convert.ToDecimal((Convert.ToDecimal(skip) / Convert.ToDecimal(newDisbursements.Count())) * 100);
                            }
                            else
                            {
                                if (i == newDisbursements.Count())
                                {
                                    if (newDisbursements.Count() <= 100)
                                    {
                                        jsonData = serializer.Serialize(newDisbursements);
                                    }
                                    else
                                    {
                                        jsonData = serializer.Serialize(newDisbursements.Skip(skip).Take(i - skip));
                                    }

                                    send       = true;
                                    percentage = Convert.ToDecimal((Convert.ToDecimal(i) / Convert.ToDecimal(newDisbursements.Count())) * 100);
                                }
                            }

                            if (send)
                            {
                                while (true)
                                {
                                    try
                                    {
                                        String insertTemporaryDisbursementTask = await InsertTemporaryDisbursement(domain, jsonData);

                                        if (!insertTemporaryDisbursementTask.Equals("Send Successful..."))
                                        {
                                            trnIntegrationForm.folderMonitoringLogMessages(insertTemporaryDisbursementTask);
                                            trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                                            trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                                            Thread.Sleep(5000);
                                        }
                                        else
                                        {
                                            trnIntegrationForm.folderMonitoringLogMessages("CVIntegrationLogOnce");
                                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\nSending Disbursement... (" + Math.Round(percentage, 2) + "%) \r\n\n");

                                            if (i == newDisbursements.Count())
                                            {
                                                trnIntegrationForm.folderMonitoringLogMessages("Send Successful!" + "\r\n\n");
                                                trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");
                                            }

                                            break;
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        trnIntegrationForm.folderMonitoringLogMessages("Sending Error: " + e.Message + "\r\n\n");
                                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                                        trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                                        Thread.Sleep(5000);
                                    }
                                }

                                send = false;
                            }
                        }

                        post = true;
                        break;
                    }
                    catch (Exception e)
                    {
                        trnIntegrationForm.folderMonitoringLogMessages("Error: " + e.Message + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                        trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                        Thread.Sleep(5000);
                    }
                }

                // =======
                // Posting
                // =======
                if (post)
                {
                    trnIntegrationForm.folderMonitoringLogMessages("Posting Disbursement... (0%) \r\n\n");
                    while (true)
                    {
                        try
                        {
                            var groupedDisbursements = from d in newDisbursements
                                                       group d by new
                            {
                                d.BranchCode,
                                d.ManualCVNumber
                            } into g
                            select g.Key;

                            var disbursements = from d in groupedDisbursements.ToList() select d;
                            if (disbursements.Any())
                            {
                                Decimal percentage = 0;
                                Int32   count      = 0;

                                foreach (var disbursement in disbursements.ToList())
                                {
                                    count     += 1;
                                    percentage = Convert.ToDecimal((Convert.ToDecimal(count) / Convert.ToDecimal(disbursements.Count())) * 100);

                                    while (true)
                                    {
                                        try
                                        {
                                            String postDisbursementTask = await PostDisbursement(domain, disbursement.BranchCode, disbursement.ManualCVNumber);

                                            if (!postDisbursementTask.Equals("Post Successful..."))
                                            {
                                                trnIntegrationForm.folderMonitoringLogMessages(postDisbursementTask);
                                                trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                                                trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                                                Thread.Sleep(5000);
                                            }
                                            else
                                            {
                                                trnIntegrationForm.folderMonitoringLogMessages("CVIntegrationLogOnce");
                                                trnIntegrationForm.folderMonitoringLogMessages("\r\n\nPosting Disbursement... (" + Math.Round(percentage, 2) + "%) \r\n\n");

                                                if (count == disbursements.Count())
                                                {
                                                    trnIntegrationForm.folderMonitoringLogMessages("Post Successful!" + "\r\n\n");
                                                    trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                                                    String jDate  = journalDate.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture);
                                                    String apiURL = "http://" + domain + "/api/folderMonitoring/journal/" + jDate + "/CV";

                                                    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(apiURL);
                                                    httpWebRequest.Method = "GET";
                                                    httpWebRequest.Accept = "application/json";

                                                    HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                                                    using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
                                                    {
                                                        var result = streamReader.ReadToEnd();
                                                        JavaScriptSerializer js = new JavaScriptSerializer();
                                                        Entities.FolderMonitoringTrnJournal sumUpJournal = (Entities.FolderMonitoringTrnJournal)js.Deserialize(result, typeof(Entities.FolderMonitoringTrnJournal));

                                                        if (sumUpJournal != null)
                                                        {
                                                            trnIntegrationForm.folderMonitoringLogMessages("Date: " + sumUpJournal.JournalDate + "\r\n\n");
                                                            trnIntegrationForm.folderMonitoringLogMessages("Total Debit: " + sumUpJournal.TotalDebitAmount + "\r\n\n");
                                                            trnIntegrationForm.folderMonitoringLogMessages("Total Credit: " + sumUpJournal.TotalCreditAmount + "\r\n\n");
                                                            trnIntegrationForm.folderMonitoringLogMessages("Balance: " + sumUpJournal.TotalBalance + "\r\n\n");
                                                            trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");
                                                        }
                                                    }
                                                }

                                                break;
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            trnIntegrationForm.folderMonitoringLogMessages("Posting Error: " + e.Message + "\r\n\n");
                                            trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                                            trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                                            Thread.Sleep(5000);
                                        }
                                    }
                                }
                            }

                            break;
                        }
                        catch (Exception e)
                        {
                            trnIntegrationForm.folderMonitoringLogMessages("Error: " + e.Message + "\r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                            trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                            trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                            Thread.Sleep(5000);
                        }
                    }
                }
            }
            else
            {
                trnIntegrationForm.folderMonitoringLogMessages("Erorr: Data Source Empty \r\n\n");
                trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");
            }

            // =============
            // Move CSV File
            // =============
            trnIntegrationForm.folderMonitoringLogMessages("Moving Disbursement File... (0%) \r\n\n");
            while (true)
            {
                try
                {
                    String settingsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Settings.json");
                    using (StreamReader trmRead = new StreamReader(settingsPath))
                    {
                        JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                        Entities.SysSettings sysSettings          = javaScriptSerializer.Deserialize <Entities.SysSettings>(trmRead.ReadToEnd());

                        String executingUser = WindowsIdentity.GetCurrent().Name;

                        DirectorySecurity securityRules = new DirectorySecurity();
                        securityRules.AddAccessRule(new FileSystemAccessRule(executingUser, FileSystemRights.Read, AccessControlType.Allow));
                        securityRules.AddAccessRule(new FileSystemAccessRule(executingUser, FileSystemRights.FullControl, AccessControlType.Allow));

                        if (!Directory.Exists(sysSettings.FolderForSentFiles + "\\CV_" + DateTime.Now.ToString("yyyyMMdd") + "\\"))
                        {
                            DirectoryInfo createDirectoryCVCSV = Directory.CreateDirectory(sysSettings.FolderForSentFiles + "\\CV_" + DateTime.Now.ToString("yyyyMMdd") + "\\", securityRules);
                        }

                        String folderForSentFiles = sysSettings.FolderForSentFiles + "\\CV_" + DateTime.Now.ToString("yyyyMMdd") + "\\";
                        File.Move(file, folderForSentFiles + "CV_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".csv");
                    }

                    trnIntegrationForm.folderMonitoringLogMessages("CVIntegrationLogOnce");

                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\nMoving Disbursement File... (100%) \r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("Move Successful!" + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                    break;
                }
                catch (Exception e)
                {
                    trnIntegrationForm.folderMonitoringLogMessages("Moving File Error: " + e.Message + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                    trnIntegrationForm.folderMonitoringLogMessages("\r\n\n");

                    trnIntegrationForm.folderMonitoringLogMessages("Retrying...\r\n\n");

                    Thread.Sleep(5000);
                }
            }
        }
Esempio n. 3
0
 // ===========
 // Constructor
 // ===========
 public ISPOSTrnSalesReturnController(Forms.TrnIntegrationForm form)
 {
     trnIntegrationForm = form;
 }
 // ===========
 // Constructor
 // ===========
 public ISPOSTrnReceivingReceiptController(Forms.TrnIntegrationForm form, String actDate)
 {
     trnIntegrationForm = form;
     activityDate       = actDate;
 }
 // ===========
 // Constructor
 // ===========
 public ISPOSTrnCollectionController(Forms.TrnIntegrationForm form)
 {
     trnIntegrationForm = form;
 }
 // ===========
 // Constructor
 // ===========
 public ISPOSMstItemController(Forms.TrnIntegrationForm form, String actDate)
 {
     trnIntegrationForm = form;
     activityDate       = actDate;
 }
Esempio n. 7
0
        // ==================
        // Send Sales Invoice
        // ==================
        public async void SendSalesInvoice(Forms.TrnIntegrationForm trnIntegrationForm, String domain, String salesDate, Int32 terminalId)
        {
            List <Entities.FolderMonitoringTrnSalesInvoice> newSalesInvoices = new List <Entities.FolderMonitoringTrnSalesInvoice>();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            String jsonData = "";

            List <Int32> collectionIds = new List <Int32>();

            String defaultReferenceNumberTimeStamp = DateTime.Now.ToString("yyyyMMddHHmmss");
            String salesTimeStamp = Convert.ToDateTime(salesDate).ToLongDateString();

            // ========================
            // Get Integration Settings
            // ========================
            var settings = from d in posdb.SysSettings select d;

            if (settings.Any())
            {
                String branchCode = settings.FirstOrDefault().BranchCode;
                String userCode   = settings.FirstOrDefault().UserCode;

                // =============
                // Getting Sales
                // =============
                trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\nGetting Sales Data... (0%) \r\n\n");
                while (true)
                {
                    newSalesInvoices = new List <Entities.FolderMonitoringTrnSalesInvoice>();

                    try
                    {
                        var collections = from d in posdb.TrnCollections
                                          where d.CollectionDate == Convert.ToDateTime(salesDate) &&
                                          d.TerminalId == terminalId &&
                                          d.SalesId != null &&
                                          d.PostCode == null &&
                                          d.IsLocked == true &&
                                          d.IsCancelled == false
                                          select d;

                        if (collections.Any())
                        {
                            foreach (var collection in collections)
                            {
                                if (collectionIds.Contains(collection.Id) == false)
                                {
                                    collectionIds.Add(collection.Id);
                                }

                                var salesLines = from d in posdb.TrnSalesLines
                                                 where d.SalesId == collection.SalesId
                                                 select d;

                                if (salesLines.Any())
                                {
                                    String defaultManualSINumber = collection.MstTerminal.Terminal + "-" + defaultReferenceNumberTimeStamp;

                                    var groupedSalesLines = from d in salesLines
                                                            group d by new
                                    {
                                        d.TrnSale.MstCustomer.CustomerCode,
                                        d.MstItem.BarCode,
                                        d.MstItem.MstUnit.Unit,
                                        d.MstItem.Price,
                                        d.NetPrice,
                                        d.DiscountAmount,
                                    } into g
                                        select new
                                    {
                                        g.Key.CustomerCode,
                                        g.Key.BarCode,
                                        g.Key.Unit,
                                        Quantity = g.Sum(s => s.Quantity),
                                        g.Key.Price,
                                        g.Key.DiscountAmount,
                                        g.Key.NetPrice,
                                        Amount = g.Sum(s => s.Amount)
                                    };

                                    if (groupedSalesLines.ToList().Any())
                                    {
                                        Int32 count = 0;

                                        foreach (var groupedSalesLine in groupedSalesLines.ToList())
                                        {
                                            count += 1;

                                            newSalesInvoices.Add(new Entities.FolderMonitoringTrnSalesInvoice
                                            {
                                                BranchCode        = branchCode,
                                                SIDate            = salesDate,
                                                CustomerCode      = groupedSalesLine.CustomerCode,
                                                ManualSINumber    = defaultManualSINumber,
                                                DocumentReference = collection.MstTerminal.Terminal,
                                                Remarks           = "Sales for " + salesTimeStamp,
                                                UserCode          = userCode,
                                                CreatedDateTime   = salesDate,
                                                ItemCode          = groupedSalesLine.BarCode,
                                                Particulars       = defaultManualSINumber,
                                                Unit           = groupedSalesLine.Unit,
                                                Quantity       = groupedSalesLine.Quantity,
                                                Price          = groupedSalesLine.Price,
                                                DiscountAmount = groupedSalesLine.DiscountAmount,
                                                NetPrice       = groupedSalesLine.NetPrice,
                                                Amount         = groupedSalesLine.Amount,
                                                No             = count
                                            });
                                        }
                                    }
                                }
                            }

                            var groupedNewSalesInvoices = from d in newSalesInvoices
                                                          group d by new
                            {
                                d.ManualSINumber,
                                d.DocumentReference,
                                d.CustomerCode,
                                d.Remarks,
                                d.ItemCode,
                                d.Unit,
                                d.Price,
                                d.NetPrice,
                                d.DiscountAmount,
                            } into g
                                select new
                            {
                                g.Key.ManualSINumber,
                                g.Key.DocumentReference,
                                g.Key.CustomerCode,
                                g.Key.Remarks,
                                g.Key.ItemCode,
                                g.Key.Unit,
                                Quantity = g.Sum(s => s.Quantity),
                                g.Key.Price,
                                g.Key.DiscountAmount,
                                g.Key.NetPrice,
                                Amount = g.Sum(s => s.Amount)
                            };

                            if (groupedNewSalesInvoices.Any())
                            {
                                newSalesInvoices = new List <Entities.FolderMonitoringTrnSalesInvoice>();

                                Int32 count = 0;

                                foreach (var groupedNewSalesInvoice in groupedNewSalesInvoices.ToList())
                                {
                                    count += 1;

                                    newSalesInvoices.Add(new Entities.FolderMonitoringTrnSalesInvoice
                                    {
                                        BranchCode        = branchCode,
                                        SIDate            = salesDate,
                                        CustomerCode      = groupedNewSalesInvoice.CustomerCode,
                                        ManualSINumber    = groupedNewSalesInvoice.ManualSINumber,
                                        DocumentReference = groupedNewSalesInvoice.DocumentReference,
                                        Remarks           = groupedNewSalesInvoice.Remarks,
                                        UserCode          = userCode,
                                        CreatedDateTime   = salesDate,
                                        ItemCode          = groupedNewSalesInvoice.ItemCode,
                                        Particulars       = groupedNewSalesInvoice.ManualSINumber,
                                        Unit           = groupedNewSalesInvoice.Unit,
                                        Quantity       = groupedNewSalesInvoice.Quantity,
                                        Price          = groupedNewSalesInvoice.Price,
                                        DiscountAmount = groupedNewSalesInvoice.DiscountAmount,
                                        NetPrice       = groupedNewSalesInvoice.NetPrice,
                                        Amount         = groupedNewSalesInvoice.Amount,
                                        No             = count
                                    });
                                }
                            }
                        }

                        trnIntegrationForm.manualSalesIntegrationLogMessages("ManualSIIntegrationLogOnce");

                        trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\nGetting Sales Data... (100%) \r\n\n");
                        trnIntegrationForm.manualSalesIntegrationLogMessages("Get Successful!" + "\r\n\n");
                        trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");

                        break;
                    }
                    catch (Exception e)
                    {
                        trnIntegrationForm.manualSalesIntegrationLogMessages("Error: " + e.Message + "\r\n\n");
                        trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                        trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");

                        trnIntegrationForm.manualSalesIntegrationLogMessages("Retrying...\r\n\n");

                        Thread.Sleep(5000);
                    }
                }

                if (newSalesInvoices.Any())
                {
                    // ========
                    // Cleaning
                    // ========
                    trnIntegrationForm.manualSalesIntegrationLogMessages("Cleaning Temporary Sales... (0%) \r\n\n");
                    while (true)
                    {
                        try
                        {
                            String deleteTemporarySalesInvoiceTask = await DeleteTemporarySalesInvoice(domain);

                            if (!deleteTemporarySalesInvoiceTask.Equals("Clean Successful..."))
                            {
                                trnIntegrationForm.manualSalesIntegrationLogMessages(deleteTemporarySalesInvoiceTask);
                                trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");

                                trnIntegrationForm.manualSalesIntegrationLogMessages("Retrying...\r\n\n");

                                Thread.Sleep(5000);
                            }
                            else
                            {
                                trnIntegrationForm.manualSalesIntegrationLogMessages("ManualSIIntegrationLogOnce");

                                trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\nCleaning Temporary Sales... (100%) \r\n\n");
                                trnIntegrationForm.manualSalesIntegrationLogMessages("Clean Successful!" + "\r\n\n");
                                trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");

                                break;
                            }
                        }
                        catch (Exception e)
                        {
                            trnIntegrationForm.manualSalesIntegrationLogMessages("Error: " + e.Message + "\r\n\n");
                            trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                            trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");

                            trnIntegrationForm.manualSalesIntegrationLogMessages("Retrying...\r\n\n");

                            Thread.Sleep(5000);
                        }
                    }

                    Boolean post = false;

                    // =======
                    // Sending
                    // =======
                    trnIntegrationForm.manualSalesIntegrationLogMessages("Sending Sales... (0%) \r\n\n");
                    while (true)
                    {
                        try
                        {
                            Decimal percentage = 0;

                            Boolean send = false;
                            Int32   skip = 0;

                            for (Int32 i = 1; i <= newSalesInvoices.Count(); i++)
                            {
                                if (i % 100 == 0)
                                {
                                    jsonData = serializer.Serialize(newSalesInvoices.Skip(skip).Take(100));
                                    skip     = i;

                                    send       = true;
                                    percentage = Convert.ToDecimal((Convert.ToDecimal(skip) / Convert.ToDecimal(newSalesInvoices.Count())) * 100);
                                }
                                else
                                {
                                    if (i == newSalesInvoices.Count())
                                    {
                                        if (newSalesInvoices.Count() <= 100)
                                        {
                                            jsonData = serializer.Serialize(newSalesInvoices);
                                        }
                                        else
                                        {
                                            jsonData = serializer.Serialize(newSalesInvoices.Skip(skip).Take(i - skip));
                                        }

                                        send       = true;
                                        percentage = Convert.ToDecimal((Convert.ToDecimal(i) / Convert.ToDecimal(newSalesInvoices.Count())) * 100);
                                    }
                                }

                                if (send)
                                {
                                    while (true)
                                    {
                                        try
                                        {
                                            String insertTemporarySalesInvoiceTask = await InsertTemporarySalesInvoice(domain, jsonData);

                                            if (!insertTemporarySalesInvoiceTask.Equals("Send Successful..."))
                                            {
                                                trnIntegrationForm.manualSalesIntegrationLogMessages(insertTemporarySalesInvoiceTask);
                                                trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");

                                                trnIntegrationForm.manualSalesIntegrationLogMessages("Retrying...\r\n\n");

                                                Thread.Sleep(5000);
                                            }
                                            else
                                            {
                                                trnIntegrationForm.manualSalesIntegrationLogMessages("ManualSIIntegrationLogOnce");
                                                trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\nSending Sales... (" + Math.Round(percentage, 2) + "%) \r\n\n");

                                                if (i == newSalesInvoices.Count())
                                                {
                                                    trnIntegrationForm.manualSalesIntegrationLogMessages("Send Successful!" + "\r\n\n");
                                                    trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                    trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");
                                                }

                                                break;
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            trnIntegrationForm.manualSalesIntegrationLogMessages("Sending Error: " + e.Message + "\r\n\n");
                                            trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                            trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");

                                            trnIntegrationForm.manualSalesIntegrationLogMessages("Retrying...\r\n\n");

                                            Thread.Sleep(5000);
                                        }
                                    }

                                    send = false;
                                }
                            }

                            post = true;
                            break;
                        }
                        catch (Exception e)
                        {
                            trnIntegrationForm.manualSalesIntegrationLogMessages("Error: " + e.Message + "\r\n\n");
                            trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                            trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");

                            trnIntegrationForm.manualSalesIntegrationLogMessages("Retrying...\r\n\n");

                            Thread.Sleep(5000);
                        }
                    }

                    // =======
                    // Posting
                    // =======
                    if (post)
                    {
                        trnIntegrationForm.manualSalesIntegrationLogMessages("Posting Sales... (0%) \r\n\n");
                        while (true)
                        {
                            try
                            {
                                var groupedSalesInvoices = from d in newSalesInvoices
                                                           group d by new
                                {
                                    d.BranchCode,
                                    d.ManualSINumber
                                } into g
                                select g.Key;

                                var salesInvoices = from d in groupedSalesInvoices.ToList() select d;
                                if (salesInvoices.Any())
                                {
                                    Decimal percentage = 0;
                                    Int32   count      = 0;

                                    foreach (var salesInvoice in salesInvoices.ToList())
                                    {
                                        count     += 1;
                                        percentage = Convert.ToDecimal((Convert.ToDecimal(count) / Convert.ToDecimal(salesInvoices.Count())) * 100);

                                        while (true)
                                        {
                                            try
                                            {
                                                String postSalesInvoiceTask = await PostSalesInvoice(domain, salesInvoice.BranchCode, salesInvoice.ManualSINumber);

                                                if (!postSalesInvoiceTask.Equals("Post Successful..."))
                                                {
                                                    trnIntegrationForm.manualSalesIntegrationLogMessages(postSalesInvoiceTask);
                                                    trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                    trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");

                                                    trnIntegrationForm.manualSalesIntegrationLogMessages("Retrying...\r\n\n");

                                                    Thread.Sleep(5000);
                                                }
                                                else
                                                {
                                                    trnIntegrationForm.manualSalesIntegrationLogMessages("ManualSIIntegrationLogOnce");
                                                    trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\nPosting Sales... (" + Math.Round(percentage, 2) + "%) \r\n\n");

                                                    if (count == salesInvoices.Count())
                                                    {
                                                        trnIntegrationForm.manualSalesIntegrationLogMessages("Post Successful!" + "\r\n\n");
                                                        trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                        trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");
                                                    }

                                                    break;
                                                }
                                            }
                                            catch (Exception e)
                                            {
                                                trnIntegrationForm.manualSalesIntegrationLogMessages("Posting Error: " + e.Message + "\r\n\n");
                                                trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                                trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");

                                                trnIntegrationForm.manualSalesIntegrationLogMessages("Retrying...\r\n\n");

                                                Thread.Sleep(5000);
                                            }
                                        }
                                    }
                                }

                                if (collectionIds.Any())
                                {
                                    foreach (var collectionId in collectionIds)
                                    {
                                        var collection = from d in posdb.TrnCollections
                                                         where d.Id == collectionId
                                                         select d;

                                        if (collection.Any())
                                        {
                                            String defaultManualSINumber = defaultReferenceNumberTimeStamp + "_" + collection.FirstOrDefault().MstCustomer.CustomerCode;

                                            var updateCollectionPostCode = collection.FirstOrDefault();
                                            updateCollectionPostCode.PostCode = defaultManualSINumber;

                                            posdb.SubmitChanges();
                                        }
                                    }
                                }

                                break;
                            }
                            catch (Exception e)
                            {
                                trnIntegrationForm.manualSalesIntegrationLogMessages("Error: " + e.Message + "\r\n\n");
                                trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                                trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");

                                trnIntegrationForm.manualSalesIntegrationLogMessages("Retrying...\r\n\n");

                                Thread.Sleep(5000);
                            }
                        }
                    }
                }
                else
                {
                    trnIntegrationForm.manualSalesIntegrationLogMessages("Data Source Empty \r\n\n");
                    trnIntegrationForm.manualSalesIntegrationLogMessages("Time Stamp: " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "\r\n\n");
                    trnIntegrationForm.manualSalesIntegrationLogMessages("\r\n\n");
                }
            }
        }