public void CancelUnderwriting()
        {
            MerchantModel editMerchant = new MerchantModel();
            UnderwritingResultModel underwritingResult = new UnderwritingResultModel();
            UnderwritingResultModel oldUnderwritingResult = new UnderwritingResultModel();
            LexisNexisExceptionModel lnException = new LexisNexisExceptionModel();

            Int32 merchantRecordId;

            try
            {
                merchantRecordId = Convert.ToInt32(hMerchantRecordId.Value);

                using (ApplicationDbContext ctx = new ApplicationDbContext())
                {
                    editMerchant = ctx.Merchants.First(m => m.RecordId == merchantRecordId);

                    underwritingResult = ctx.UnderwritingResults.FirstOrDefault(ur => ur.Merchant.RecordId == merchantRecordId && ur.Active == true);

                    lnException = ctx.LexisNexisExceptions.FirstOrDefault(lne => lne.UnderwritingResult.RecordId == underwritingResult.RecordId);

                    if (lnException != null)
                    {
                        ctx.LexisNexisExceptions.Remove(lnException);
                    }
                    if (underwritingResult != null)
                    {
                        ctx.UnderwritingResults.Remove(underwritingResult);
                    }

                    ctx.SaveChanges();

                    if (ctx.UnderwritingResults.Any(ur => ur.Merchant.RecordId == merchantRecordId))
                    {
                        oldUnderwritingResult = ctx.UnderwritingResults.Where(ur => ur.Merchant.RecordId == merchantRecordId).OrderByDescending(ur => ur.Timestamp).First();

                        oldUnderwritingResult.Active = true;

                        ctx.SaveChanges();
                    }

                    gridUnderwritingHistory.Rebind();

                }

                //Reset Radio Button Fields
                rblUWCorpInfoVerifiedResult.SelectedValue = "0";
                rblUWBusLicStatusResult.SelectedValue = "0";
                rblUWEINVerifiedResult.SelectedValue = "0";
                rblUWPrincipalVerifiedResult.SelectedValue = "0";
                rblUWCardSalesIndicatorsVerifiedResult.SelectedValue = "0";
                rblUWBankingInfoVerifiedResult.SelectedValue = "0";
                rblUWMCCVerifiedResult.SelectedValue = "0";
                rblUWBVIVerifiedResult.SelectedValue = "0";
                rblUWTaxLiensVerifiedResult.SelectedValue = "0";
                rblUWRiskIndicatorVerifiedResult.SelectedValue = "0";

                //Reset Text Area Fields
                txtUWCorpInfoVerifiedNotes.Text = "";
                txtUWBUsLicStatusVerifiedNotes.Text = "";
                txtUWEINVerifiedNotes.Text = "";
                txtUWPrincipalVerifiedNotes.Text = "";
                txtUWCardSalesIndicatorsVerifiedNotes.Text = "";
                txtUWBankingInfoVerifiedNotes.Text = "";
                txtUWMCCVerifiedNotes.Text = "";
                txtUWBVIVerifiedNotes.Text = "";
                txtUWTaxLiensVerifiedNotes.Text = "";
                txtUWRiskIndicatorVerifiedNotes.Text = "";
                txtUnderwriterInitials.Text = "";

            }
            catch (System.Exception ex)
            {
                _newLogic.WriteExceptionToDB(ex, "CancelUnderwriting");
            }
        }
        public void AutomatedUnderwriting(Int32 MerchantId, Int32 UnderwritingResultId)
        {
            try
            {
                String displayResults = "";

                using (ApplicationDbContext ctx = new ApplicationDbContext())
                {
                    if (ctx.Merchants.Any(m => m.RecordId == MerchantId) && ctx.UnderwritingResults.Any(ur => ur.RecordId == UnderwritingResultId))
                    {
                        var editMerchant = ctx.Merchants.First(m => m.RecordId == MerchantId);
                        var underwritingResults = ctx.UnderwritingResults.FirstOrDefault(ur => ur.RecordId == UnderwritingResultId);
                        var underwritingSchema = editMerchant.AdvancePlan.UnderwritingSchema;

                        if (editMerchant != null && underwritingResults != null)
                        {
                            String baseUrl = "";
                            String apiPath = "api/Underwriting";
                            XmlDocument xmlDoc = new XmlDocument();
                            String riskCodes = "";
                            String isDemo = "0";

                            if (!String.IsNullOrEmpty(_miqroSettings["d9444814-043a-44f2-982c-913c55d84746"]))
                            {
                                baseUrl = _miqroSettings["d9444814-043a-44f2-982c-913c55d84746"];

                                if (!String.IsNullOrEmpty(baseUrl))
                                {
                                    var client = new RestClient(baseUrl);
                                    var request = new RestRequest(apiPath, Method.POST);
                                    request.AddHeader("Accept", "application/xml");
                                    request.Parameters.Clear();

                                    request.AddParameter("CorpName", editMerchant.CorpName ?? "");
                                    request.AddParameter("DbaName", editMerchant.DbaName ?? "");
                                    request.AddParameter("FEIN", editMerchant.FedTaxId ?? "");
                                    if (editMerchant.Business != null)
                                    {
                                        request.AddParameter("CorpPhone", editMerchant.Business.HomePhone ?? "");
                                        if (editMerchant.Business.Address != null)
                                        {
                                            request.AddParameter("CorpAddress", editMerchant.Business.Address.Address ?? "");
                                            request.AddParameter("CorpCity", editMerchant.Business.Address.City ?? "");
                                            request.AddParameter("CorpState", editMerchant.Business.Address.State.Abbreviation ?? "");
                                            request.AddParameter("CorpZip", editMerchant.Business.Address.Zip ?? "");
                                        }
                                    }
                                    else
                                    {
                                        request.AddParameter("CorpPhone", "");
                                        request.AddParameter("CorpAddress", "");
                                        request.AddParameter("CorpCity", "");
                                        request.AddParameter("CorpState", "");
                                        request.AddParameter("CorpZip", "");
                                    }

                                    isDemo = _miqroSettings["3e1acfa5-73dd-4573-8f3c-e7e46aef39dc"] ?? "0";

                                    if (isDemo == "1")
                                    {
                                        request.AddParameter("ARFirst", editMerchant.MerchantPrincipal.Contact.FirstName);
                                        request.AddParameter("ARMiddle", editMerchant.MerchantPrincipal.Contact.MiddleInitial);
                                        request.AddParameter("ARLast", editMerchant.MerchantPrincipal.Contact.LastName);
                                        if (editMerchant.MerchantPrincipal.Contact != null && editMerchant.MerchantPrincipal.Contact.Address != null)
                                        {
                                            request.AddParameter("ARAddress", editMerchant.MerchantPrincipal.Contact.Address.Address ?? "");
                                            request.AddParameter("ARCity", editMerchant.MerchantPrincipal.Contact.Address.City ?? "");
                                            request.AddParameter("ARState", editMerchant.MerchantPrincipal.Contact.Address.State.Abbreviation ?? "");
                                            request.AddParameter("ARZip", editMerchant.MerchantPrincipal.Contact.Address.Zip ?? "");
                                        }
                                        else
                                        {
                                            request.AddParameter("ARAddress", "");
                                            request.AddParameter("ARCity", "");
                                            request.AddParameter("ARState", "");
                                            request.AddParameter("ARZip", "");
                                        }
                                        request.AddParameter("ARAge", "");
                                        if (editMerchant.MerchantPrincipal.PrincipalDoB.HasValue)
                                        {
                                            request.AddParameter("ARDoBYear", editMerchant.MerchantPrincipal.PrincipalDoB.Value.Year.ToString() ?? "");
                                            request.AddParameter("ARDoBMonth", editMerchant.MerchantPrincipal.PrincipalDoB.Value.Month.ToString() ?? "");
                                            request.AddParameter("ARDoBDay", editMerchant.MerchantPrincipal.PrincipalDoB.Value.Day.ToString() ?? "");
                                        }
                                        else
                                        {
                                            request.AddParameter("ARDoBYear", "");
                                            request.AddParameter("ARDoBMonth", "");
                                            request.AddParameter("ARDoBDay", "");
                                        }
                                        if (editMerchant.MerchantPrincipal.PrincipalSsn != null)
                                        {
                                            request.AddParameter("ARSSN", PWDTK.Utf8BytesToString(editMerchant.MerchantPrincipal.PrincipalSsn));
                                        }
                                        else
                                        {
                                            request.AddParameter("ARSSN", "");
                                        }
                                        if (editMerchant.MerchantPrincipal.PrincipalDLNumber != null)
                                        {
                                            request.AddParameter("ARDLNumber", PWDTK.Utf8BytesToString(editMerchant.MerchantPrincipal.PrincipalDLNumber));
                                        }
                                        else
                                        {
                                            request.AddParameter("ARDLNumber", "");
                                        }
                                        if (editMerchant.MerchantPrincipal.PrincipalDLState != null)
                                        {
                                            request.AddParameter("ARDLState", editMerchant.MerchantPrincipal.PrincipalDLState.Abbreviation);
                                        }
                                        else
                                        {
                                            request.AddParameter("ARDLState", "");
                                        }
                                        request.AddParameter("ARPhone", editMerchant.MerchantPrincipal.Contact.HomePhone ?? "");
                                        request.AddParameter("ARFormerLast", "");
                                    }
                                    else
                                    {
                                        request.AddParameter("ARFirst", "");
                                        request.AddParameter("ARMiddle", "");
                                        request.AddParameter("ARLast", "");
                                        request.AddParameter("ARAddress", "");
                                        request.AddParameter("ARCity", "");
                                        request.AddParameter("ARState", "");
                                        request.AddParameter("ARZip", "");
                                        request.AddParameter("ARAge", "");
                                        request.AddParameter("ARDoBYear", "");
                                        request.AddParameter("ARDoBMonth", "");
                                        request.AddParameter("ARDoBDay", "");
                                        request.AddParameter("ARSSN", "");
                                        request.AddParameter("ARDLNumber", "");
                                        request.AddParameter("ARDLState", "");
                                        request.AddParameter("ARPhone", "");
                                        request.AddParameter("ARFormerLast", "");
                                    }

                                    IRestResponse response = client.Execute(request);

                                    if (response != null)
                                    {
                                        var content = response.Content;

                                        XNode node = JsonConvert.DeserializeXNode(content.ToString());

                                        XDocument xDoc = XDocument.Parse(node.ToString());

                                        if (xDoc != null)
                                        {
                                            LexisNexisUnderwritingResultModel autoUnderwritingResults = new LexisNexisUnderwritingResultModel();
                                            Boolean uwComplete = true;

                                            LexisNexisRawResultModel rawXml = new LexisNexisRawResultModel();

                                            rawXml.Timestamp = DateTime.UtcNow;
                                            rawXml.XmlContent = xDoc.ToString();

                                            ctx.LexisNexisRawResults.Add(rawXml);
                                            ctx.SaveChanges();

                                            autoUnderwritingResults.Timestamp = DateTime.UtcNow;
                                            autoUnderwritingResults.LexisNexisRawResult = ctx.LexisNexisRawResults.FirstOrDefault(lnrr => lnrr.RecordId == rawXml.RecordId);
                                            autoUnderwritingResults.Version = "1.7";

                                            if (xDoc.Descendants("Exceptions").Any())
                                            {
                                                autoUnderwritingResults.Error = true;

                                                var exceptions = xDoc.Descendants("Exceptions")
                                                    .Where(x => x.Parent.Name == "Header")
                                                    .Select(x => new
                                                    {
                                                        Code = (String)x.Element("Code") ?? "",
                                                        Source = (String)x.Element("Source") ?? "",
                                                        Message = (String)x.Element("Message") ?? ""
                                                    });

                                                if (exceptions != null)
                                                {
                                                    foreach (var e in exceptions)
                                                    {
                                                        LexisNexisExceptionModel exception = new LexisNexisExceptionModel();

                                                        exception.Timestamp = DateTime.UtcNow;
                                                        exception.Code = e.Code;
                                                        exception.Source = e.Source;
                                                        exception.Message = e.Message;
                                                        exception.UnderwritingResult = underwritingResults;

                                                        ctx.LexisNexisExceptions.Add(exception);
                                                    }

                                                    ctx.SaveChanges();
                                                }
                                            }

                                            if (xDoc.Descendants("Header").Any())
                                            {
                                                var headerInfo = xDoc.Descendants("Header")
                                                    .Select(x => new
                                                    {
                                                        TransactionId = (String)x.Element("TransactionId") ?? "",
                                                        QueryId = (String)x.Element("QueryId") ?? "",
                                                        Status = (Int16?)x.Element("Status") ?? 999,
                                                        Message = (String)x.Element("Message") ?? ""
                                                    })
                                                    .FirstOrDefault();

                                                autoUnderwritingResults.TransactionId = headerInfo.TransactionId;
                                                autoUnderwritingResults.QueryId = headerInfo.QueryId;
                                                autoUnderwritingResults.Status = headerInfo.Status;
                                                autoUnderwritingResults.Message = headerInfo.Message;

                                                displayResults += "Transaction ID: " + headerInfo.TransactionId + "<br />";
                                                displayResults += "Query ID: " + headerInfo.QueryId + "<br />";
                                                displayResults += "Status: " + headerInfo.Status + "<br /><br />";

                                                if (headerInfo.Message != "")
                                                {
                                                    displayResults += "Message: " + headerInfo.Message + "<br /><br />";
                                                }

                                            }
                                            else
                                            {
                                                uwComplete = false;
                                            }

                                            if (xDoc.Descendants("CompanyResults").Any())
                                            {
                                                if (xDoc.Descendants("WatchList").Any())
                                                {
                                                    var watchLists = xDoc.Descendants("WatchList")
                                                         .Where(x => x.Parent.Parent.Name == "CompanyResults")
                                                         .Select(x => new
                                                         {
                                                             Table = (String)x.Element("Table") ?? "",
                                                             RecordNumber = (String)x.Element("RecordNumber") ?? "",
                                                             EntityName = (String)x.Element("EntityName") ?? "",
                                                             Country = (String)x.Element("Country") ?? "",
                                                             Sequence = (String)x.Element("Sequence") ?? ""
                                                         });

                                                    foreach (var wL in watchLists)
                                                    {
                                                        if (wL.Table.Contains("Office of Foreign Asset"))
                                                        {
                                                            autoUnderwritingResults.OFAC = true;
                                                            autoUnderwritingResults.OFACMatchData = "Table: " + wL.Table + " -- RecordNumber: " + wL.RecordNumber + " -- EntityName: " +
                                                                wL.EntityName + " -- Country: " + wL.Country + " -- Sequence: " + wL.Sequence;
                                                        }

                                                        displayResults += "<b>Office of Foreign Asset Control Match</b><br />";
                                                    }
                                                }

                                                var companyResults = xDoc.Descendants("CompanyResults")
                                                    .Select(x => new
                                                    {
                                                        BVI = (int?)x.Element("BusinessVerificationIndicator") ?? 0,
                                                        UnreleasedLienCounter = (int?)x.Element("UnreleasedLienCounter") ?? 0,
                                                        SIC = (String)x.Element("SICCode") ?? "",
                                                        RecentLienType = (String)x.Element("RecentLienType") ?? "",
                                                        BusinessDescription = (String)x.Element("BusinessDescription") ?? ""
                                                    })
                                                    .FirstOrDefault();

                                                autoUnderwritingResults.BVI = companyResults.BVI;
                                                if (companyResults.SIC.Length >= 4)
                                                {
                                                    autoUnderwritingResults.Mcc = companyResults.SIC.Substring(0, 4);
                                                }
                                                else
                                                {
                                                    autoUnderwritingResults.Mcc = companyResults.SIC;
                                                }
                                                autoUnderwritingResults.UnreleasedLienCount = companyResults.UnreleasedLienCounter;
                                                autoUnderwritingResults.BusinessDescription = companyResults.BusinessDescription;

                                                if (companyResults.SIC.Length > 4)
                                                {
                                                    autoUnderwritingResults.AdditionalMccDigits = companyResults.SIC.Substring(4);
                                                }

                                                if (companyResults.RecentLienType != "")
                                                {
                                                    if (ctx.LexisNexisLienTypes.Any(lnlt => lnlt.TypeName == companyResults.RecentLienType))
                                                    {
                                                        autoUnderwritingResults.RecentLienType = ctx.LexisNexisLienTypes.First(lnlt => lnlt.TypeName == companyResults.RecentLienType);
                                                    }
                                                    else
                                                    {
                                                        autoUnderwritingResults.UnmatchedLienType = companyResults.RecentLienType;
                                                    }
                                                }

                                                displayResults += "BVI: " + companyResults.BVI + "<br />";

                                                displayResults += "SIC: ";
                                                if (companyResults.SIC == editMerchant.Mcc.MerchantCategoryCode)
                                                {
                                                    if (underwritingSchema.ApprovedMCCList.Any(x => x.MCC.MerchantCategoryCode == companyResults.SIC))
                                                    {
                                                        displayResults += "Match and Approved MCC<br />";
                                                        autoUnderwritingResults.MccMatch = true;
                                                    }
                                                    else
                                                    {
                                                        displayResults += "Match, but MCC Not Approved<br />";
                                                        autoUnderwritingResults.MccMatch = false;
                                                    }
                                                }
                                                else if (companyResults.SIC == "")
                                                {
                                                    displayResults += "No SIC Found<br />";
                                                    autoUnderwritingResults.MccMatch = false;
                                                }
                                                else
                                                {
                                                    displayResults += "SIC Mismatch (" + companyResults.SIC + ")<br />";
                                                    autoUnderwritingResults.MccMatch = false;
                                                }

                                                if (companyResults.UnreleasedLienCounter > 0)
                                                {
                                                    displayResults += "<br />Unreleased Liens<br />";
                                                    displayResults += "Count: " + companyResults.UnreleasedLienCounter + "<br />";
                                                    displayResults += "Type: " + companyResults.RecentLienType + "<br />";
                                                }

                                                if (xDoc.Descendants("RecentLienFilingDate").Any())
                                                {
                                                    var recentLienDate = xDoc.Descendants("RecentLienFilingDate")
                                                        .Select(x => new
                                                        {
                                                            Year = (int?)x.Element("Year"),
                                                            Month = (int?)x.Element("Month"),
                                                            Day = (int?)x.Element("Day")
                                                        })
                                                        .FirstOrDefault();

                                                    if (recentLienDate != null)
                                                    {
                                                        autoUnderwritingResults.RecentLienDate = DateTime.Parse(recentLienDate.Year + "-" + recentLienDate.Month + "-" + recentLienDate.Day);
                                                        displayResults += "Most Recent Lien: " + recentLienDate.Year + "-" + recentLienDate.Month + "-" + recentLienDate.Day + "<br />";
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                uwComplete = false;
                                            }

                                            if (uwComplete == true)
                                            {
                                                ctx.LexisNexisResults.Add(autoUnderwritingResults);
                                                ctx.SaveChanges();

                                                if (xDoc.Descendants("RiskIndicator").Any())
                                                {
                                                    displayResults += "<br />Company Risk Codes <br />";
                                                    var cRiskIndicators = xDoc.Descendants("RiskIndicator")
                                                        .Where(x => x.Parent.Parent.Name == "CompanyResults")
                                                        .Select(x => new { RiskCode = x.Element("RiskCode").Value, Description = x.Element("Description").Value });

                                                    foreach (var r in cRiskIndicators)
                                                    {
                                                        LexisNexisRiskCodeResultModel riskCodeResults = new LexisNexisRiskCodeResultModel();

                                                        riskCodeResults.Timestamp = DateTime.UtcNow;
                                                        riskCodeResults.LexisNexisUnderwritingResult = ctx.LexisNexisResults.FirstOrDefault(lnr => lnr.RecordId == autoUnderwritingResults.RecordId);
                                                        riskCodeResults.RiskCode = ctx.LexisNexisRiskCodes.FirstOrDefault(lnrc => lnrc.RiskCode == r.RiskCode);

                                                        ctx.LexisNexisRiskCodeResults.Add(riskCodeResults);

                                                        displayResults += r.RiskCode + "  --  " + r.Description + "<br />";
                                                    }

                                                    underwritingResults.LexisNexisResults = ctx.LexisNexisResults.FirstOrDefault(lnr => lnr.RecordId == autoUnderwritingResults.RecordId);
                                                    ctx.SaveChanges();

                                                    FinalizeUnderwriting(autoUnderwritingResults);
                                                }
                                                else
                                                {
                                                    displayResults += "No Risk Indicators Found<br />";
                                                }
                                            }
                                            else
                                            {
                                                CancelUnderwriting();

                                                btnUnderwritingCancel.Visible = false;
                                                btnUnderwritingCancel2.Visible = false;
                                                btnUnderwritingContinue.Visible = false;
                                                btnUnderwritingSave.Visible = false;
                                                btnUnderwritingComplete.Visible = false;
                                                btnUnderwritingTryAgain.Visible = true;

                                                displayResults = "Underwriting was unable to be completed.  Please Cancel and try again or contact your System Administrator for more information.";
                                            }
                                        }
                                        else
                                        {
                                            displayResults = "Underwriting was unable to be completed.  Please Cancel and try again or contact your System Administrator for more information.";
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                lblUnderwritingMessage.Text = displayResults;

            }
            catch (System.Exception ex)
            {
                _newLogic.WriteExceptionToDB(ex, "AutomatedUnderwriting");
            }
        }