Esempio n. 1
0
        public static XDocument saveTransaction(RockContext rockContext, BackgroundCheck bgCheck, XElement xTransaction)
        {
            XDocument xTransactionLog;

            // Clear any SSN nodes before saving XML to record
            foreach (var xSSNElement in xTransaction.Descendants("SSN"))
            {
                xSSNElement.Value = "XXX-XX-XXXX";
            }

            if (!String.IsNullOrWhiteSpace(bgCheck.ResponseXml))
            {
                xTransactionLog = XDocument.Parse(bgCheck.ResponseXml);
            }
            else
            {
                xTransactionLog = new XDocument(
                    new XDeclaration("1.0", "UTF-8", "yes"),
                    new XElement("BgChkTransactions"));
            }

            xTransactionLog.Root.Add(xTransaction);
            bgCheck.ResponseXml = xTransactionLog.ToString();
            rockContext.SaveChanges();

            return(xTransactionLog);
        }
Esempio n. 2
0
        public ActionResult Background(int?driverId)
        {
            BackgroundCheck backgroundCheck = new BackgroundCheck();

            backgroundCheck.DriverId = driverId;
            return(View(backgroundCheck));
        }
Esempio n. 3
0
        private XElement makeBGRequest(BackgroundCheck bgCheck, string ssn, DefinedValueCache requestType, string billingCode, List <string[]> ssnTraceCounties)
        {
            XDocument xRequestDoc = BuildRequest(
                bgCheck.WorkflowId.ToString(),
                bgCheck.PersonAlias.Person,
                ssn,
                requestType,
                billingCode,
                ssnTraceCounties
                );

            var requestDateTime = RockDateTime.Now;

            XDocument xResultDoc       = PostToWebService(xRequestDoc, GetAttributeValue("RequestURL"));
            var       responseDateTime = RockDateTime.Now;

            var xTransaction = new XElement("Transaction",
                                            new XAttribute("TransactionType", "REQUEST"),
                                            new XAttribute("RequestDateTime", requestDateTime),
                                            new XAttribute("ResponseDateTime", responseDateTime),
                                            xRequestDoc.Root,
                                            xResultDoc.Root
                                            );

            return(xTransaction);
        }
        public ActionResult DialogEdit(int id)
        {
            BackgroundCheck bc = (from e in DbUtil.Db.BackgroundChecks
                                  where e.Id == id
                                  select e).Single();

            return(View(bc));
        }
        public ActionResult SubmitCheck(int id, int iPeopleID, string sSSN, string sDLN, string sUser = "", string sPassword = "", int iStateID = 0, string sPlusCounty = "", string sPlusState = "")
        {
            String sResponseURL = Request.Url.Scheme + "://" + Request.Url.Authority + ProtectMyMinistryHelper.PMM_Append;

            Person p = (from e in DbUtil.Db.People
                        where e.PeopleId == iPeopleID
                        select e).Single();

            // Check for existing SSN
            if (sSSN != null && sSSN.Length > 1)
            {
                if (sSSN.Substring(0, 1) == "X")
                {
                    sSSN = Util.Decrypt(p.Ssn, "People");
                }
                else
                {
                    sSSN  = sSSN.Replace("-", "").Replace(" ", "");;
                    p.Ssn = Util.Encrypt(sSSN, "People");
                }
            }
            else
            {
                sSSN = Util.Decrypt(p.Ssn, "People");
            }

            // Check for existing DLN and DL State
            if (sDLN != null && sDLN.Length > 1)
            {
                if (sDLN.Substring(0, 1) == "X")
                {
                    sDLN     = Util.Decrypt(p.Dln, "People");
                    iStateID = p.DLStateID ?? 0;
                }
                else
                {
                    p.Dln       = Util.Encrypt(sDLN, "People");
                    p.DLStateID = iStateID;
                }
            }

            DbUtil.Db.SubmitChanges();

            ProtectMyMinistryHelper.submit(id, sSSN, sDLN, sResponseURL, iStateID, sUser, sPassword, sPlusCounty, sPlusState);

            BackgroundCheck bc = (from e in DbUtil.Db.BackgroundChecks
                                  where e.Id == id
                                  select e).Single();

            if (bc != null && (bc.ServiceCode == "Combo" || bc.ServiceCode == "ComboPC" || bc.ServiceCode == "ComboPS"))
            {
                Volunteer vol = DbUtil.Db.Volunteers.SingleOrDefault(e => e.PeopleId == iPeopleID);
                vol.ProcessedDate = DateTime.Now;
                DbUtil.Db.SubmitChanges();
            }

            return(Redirect("/Volunteering/" + iPeopleID));
        }
Esempio n. 6
0
 public ActionResult Background([Bind(Include = "BackgroundId, DriverId, Date_of_Birth, Ssn, VehicleType, VehicleYear, DrivingLicence, LicenceState, InsuranceProvider, ExpirationDate")] BackgroundCheck backgroundCheck)
 {
     if (ModelState.IsValid)
     {
         db.BackgroundCheck.Add(backgroundCheck);
         db.SaveChanges();
         return(RedirectToAction("BackgroundConfirmation"));
     }
     return(View(backgroundCheck));
 }
        public ActionResult EditCheck(int id, int label = 0)
        {
            BackgroundCheck bc = (from e in DbUtil.Db.BackgroundChecks
                                  where e.Id == id
                                  select e).Single();

            bc.ReportLabelID = label;

            DbUtil.Db.SubmitChanges();

            return(Redirect("/Volunteering/" + bc.PeopleID));
        }
        public ActionResult DeleteCheck(int id)
        {
            int iPeopleID = 0;

            BackgroundCheck bc = (from e in DbUtil.Db.BackgroundChecks
                                  where e.Id == id
                                  select e).Single();

            iPeopleID = bc.PeopleID;

            DbUtil.Db.BackgroundChecks.DeleteOnSubmit(bc);
            DbUtil.Db.SubmitChanges();

            return(Redirect("/Volunteering/" + iPeopleID));
        }
        public static void Create(int iPeopleID, string sServiceCode, int iType, int iLabel)
        {
            var bcNew = new BackgroundCheck();

            bcNew.StatusID = 1;
            bcNew.UserID = Util.UserPeopleId ?? 0;
            bcNew.PeopleID = iPeopleID;
            bcNew.ServiceCode = sServiceCode; // "Combo", "MVR"
            bcNew.Created = DateTime.Now;
            bcNew.Updated = DateTime.Now;
            bcNew.ReportTypeID = iType;
            bcNew.ReportLabelID = iLabel;

            DbUtil.Db.BackgroundChecks.InsertOnSubmit(bcNew);
            DbUtil.Db.SubmitChanges();
        }
Esempio n. 10
0
        public static void Create(int iPeopleID, string sServiceCode, int iType, int iLabel)
        {
            var bcNew = new BackgroundCheck();

            bcNew.StatusID      = 1;
            bcNew.UserID        = Util.UserPeopleId ?? 0;
            bcNew.PeopleID      = iPeopleID;
            bcNew.ServiceCode   = sServiceCode;           // "Combo", "MVR"
            bcNew.Created       = DateTime.Now;
            bcNew.Updated       = DateTime.Now;
            bcNew.ReportTypeID  = iType;
            bcNew.ReportLabelID = iLabel;

            DbUtil.Db.BackgroundChecks.InsertOnSubmit(bcNew);
            DbUtil.Db.SubmitChanges();
        }
Esempio n. 11
0
        public static void Create(int peopleId, string serviceCode, int reportTypeId, int reportLabelId)
        {
            var bcNew = new BackgroundCheck
            {
                StatusID      = 1,
                UserID        = Util.UserPeopleId ?? 0,
                PeopleID      = peopleId,
                ServiceCode   = serviceCode, // "Combo", "MVR", "Credit"
                Created       = DateTime.Now,
                Updated       = DateTime.Now,
                ReportTypeID  = reportTypeId,
                ReportLabelID = reportLabelId
            };
            var db = DbUtil.Db;

            db.BackgroundChecks.InsertOnSubmit(bcNew);
            db.SubmitChanges();
        }
Esempio n. 12
0
        public static BackgroundCheck Create(CMSDataContext db, int peopleId, int?userPeopleId, string serviceCode, int reportTypeId, int reportLabelId)
        {
            var bcNew = new BackgroundCheck
            {
                StatusID      = 1,
                UserID        = userPeopleId ?? 0,
                PeopleID      = peopleId,
                ServiceCode   = serviceCode, // "Combo", "MVR", "Credit"
                Created       = DateTime.Now,
                Updated       = DateTime.Now,
                ReportTypeID  = reportTypeId,
                ReportLabelID = reportLabelId
            };

            db.BackgroundChecks.InsertOnSubmit(bcNew);
            db.SubmitChanges();
            return(bcNew);
        }
Esempio n. 13
0
        public static void handleTransaction(RockContext rockContext, BackgroundCheck bgCheck, XElement xTransaction)
        {
            bool createdNewAttribute = false;
            // Handle transaction status
            XElement xOrderResponse = null;

            if (xTransaction.Attribute("TransactionType").Value == "REQUEST")
            {
                xOrderResponse = xTransaction.Elements().Last();

                XElement xResponseStatus = xOrderResponse.Element("Status");
                if (xResponseStatus != null)
                {
                    string status = xResponseStatus.Value;
                    createdNewAttribute = SaveAttributeValue(bgCheck.Workflow, "RequestStatus", status, FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext, null) || createdNewAttribute;

                    if (status == "ERROR")
                    {
                        createdNewAttribute = SaveAttributeValue(bgCheck.Workflow, "RequestMessage", xOrderResponse.Elements("Message").Select(x => x.Value).ToList().AsDelimited(Environment.NewLine), FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext, null) || createdNewAttribute;
                    }
                }

                XElement xResponseErrors = xOrderResponse.Elements("Errors").FirstOrDefault();
                if (xResponseErrors != null)
                {
                    createdNewAttribute = SaveAttributeValue(bgCheck.Workflow, "RequestMessage", xResponseErrors.Elements("Message").Select(x => x.Value).ToList().AsDelimited(Environment.NewLine), FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext, null) || createdNewAttribute;
                }
            }
            else if (xTransaction.Attribute("TransactionType").Value == "RESPONSE")
            {
                xOrderResponse = xTransaction.Elements().First();
            }

            // Handle request status
            if (xOrderResponse != null)
            {
                XElement xOrder = xOrderResponse.Element("Order");

                if (xOrder != null && xOrder.Elements("OrderDetail").Any(x => x.Elements("Status").Any()))
                {
                    SaveResults(rockContext, bgCheck, xOrderResponse);
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Sends a background request to Checkr.  This method is called by the BackgroundCheckRequest action's Execute
        /// method for the Checkr component.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="workflow">The Workflow initiating the request.</param>
        /// <param name="personAttribute">The person attribute.</param>
        /// <param name="ssnAttribute">The SSN attribute.</param>
        /// <param name="requestTypeAttribute">The request type attribute.</param>
        /// <param name="billingCodeAttribute">The billing code attribute.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns>
        /// True/False value of whether the request was successfully sent or not.
        /// </returns>
        public override bool SendRequest(RockContext rockContext, Model.Workflow workflow,
                                         AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute,
                                         AttributeCache billingCodeAttribute, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            try
            {
                // Check to make sure workflow is not null
                if (workflow == null)
                {
                    errorMessages.Add("The 'Checkr' background check provider requires a valid workflow.");
                    UpdateWorkflowRequestStatus(workflow, rockContext, "FAIL");
                    return(true);
                }

                // Lock the workflow until we're finished saving so the webhook can't start working on it.
                var lockObject = _lockObjects.GetOrAdd(workflow.Id, new object());
                lock ( lockObject )
                {
                    // Checkr can respond very fast, possibly before the workflow finishes.
                    // Save the workflow now to ensure previously completed activities/actions
                    // are not run again via the checkr webhook. This is not done at the Action
                    // or Activity level for speed reasons.
                    if (workflow.IsPersisted == true)
                    {
                        rockContext.SaveChanges();
                    }

                    Person person;
                    int?   personAliasId;
                    if (!GetPerson(rockContext, workflow, personAttribute, out person, out personAliasId, errorMessages))
                    {
                        errorMessages.Add("Unable to get Person.");
                        UpdateWorkflowRequestStatus(workflow, rockContext, "FAIL");
                        return(true);
                    }

                    string packageName;
                    if (!GetPackageName(rockContext, workflow, requestTypeAttribute, out packageName, errorMessages))
                    {
                        errorMessages.Add("Unable to get Package.");
                        UpdateWorkflowRequestStatus(workflow, rockContext, "FAIL");
                        return(true);
                    }

                    string candidateId;
                    if (!CreateCandidate(person, out candidateId, errorMessages))
                    {
                        errorMessages.Add("Unable to create candidate.");
                        UpdateWorkflowRequestStatus(workflow, rockContext, "FAIL");
                        return(true);
                    }

                    if (!CreateInvitation(candidateId, packageName, errorMessages))
                    {
                        errorMessages.Add("Unable to create invitation.");
                        UpdateWorkflowRequestStatus(workflow, rockContext, "FAIL");
                        return(true);
                    }

                    using (var newRockContext = new RockContext())
                    {
                        var backgroundCheckService = new BackgroundCheckService(newRockContext);
                        var backgroundCheck        = backgroundCheckService.Queryable()
                                                     .Where(c =>
                                                            c.WorkflowId.HasValue &&
                                                            c.WorkflowId.Value == workflow.Id)
                                                     .FirstOrDefault();

                        if (backgroundCheck == null)
                        {
                            backgroundCheck            = new BackgroundCheck();
                            backgroundCheck.WorkflowId = workflow.Id;
                            backgroundCheckService.Add(backgroundCheck);
                        }

                        backgroundCheck.PersonAliasId = personAliasId.Value;
                        backgroundCheck.ForeignId     = 2;
                        backgroundCheck.PackageName   = packageName;
                        backgroundCheck.RequestDate   = RockDateTime.Now;
                        backgroundCheck.RequestId     = candidateId;
                        newRockContext.SaveChanges();
                    }

                    UpdateWorkflowRequestStatus(workflow, rockContext, "SUCCESS");

                    if (workflow.IsPersisted)
                    {
                        // Make sure the AttributeValues are saved to the database immediately because the Checkr WebHook
                        // (which might otherwise get called before they are saved by the workflow processing) needs to
                        // have the correct attribute values.
                        workflow.SaveAttributeValues(rockContext);
                    }

                    _lockObjects.TryRemove(workflow.Id, out _);   // we no longer need that lock for this workflow
                }

                return(true);
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, null);
                errorMessages.Add(ex.Message);
                UpdateWorkflowRequestStatus(workflow, rockContext, "FAIL");
                return(true);
            }
        }
Esempio n. 15
0
        public override bool SendRequest(RockContext rockContext, Workflow workflow, AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute, AttributeCache billingCodeAttribute, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            rockContext.SaveChanges();

            // Check to make sure workflow is not null
            if (workflow == null || workflow.Id == 0)
            {
                errorMessages.Add("The 'Protect My Ministry' background check provider requires a valid persisted workflow.");
                return(false);
            }

            workflow.LoadAttributes();

            // Get the person that the request is for
            Person person = null;

            if (personAttribute != null)
            {
                Guid?personAliasGuid = workflow.GetAttributeValue(personAttribute.Key).AsGuidOrNull();
                if (personAliasGuid.HasValue)
                {
                    person = new PersonAliasService(rockContext).Queryable()
                             .Where(p => p.Guid.Equals(personAliasGuid.Value))
                             .Select(p => p.Person)
                             .FirstOrDefault();
                    person.LoadAttributes(rockContext);
                }
            }

            if (person == null)
            {
                errorMessages.Add("The 'Protect My Ministry' background check provider requires the workflow to have a 'Person' attribute that contains the person who the background check is for.");
                return(false);
            }

            string billingCode = workflow.GetAttributeValue(billingCodeAttribute.Key);
            Guid?  campusGuid  = billingCode.AsGuidOrNull();

            if (campusGuid.HasValue)
            {
                var campus = CampusCache.Read(campusGuid.Value);
                if (campus != null)
                {
                    billingCode = campus.Name;
                }
            }
            string            ssn         = Encryption.DecryptString(workflow.GetAttributeValue(ssnAttribute.Key));
            DefinedValueCache requestType = DefinedValueCache.Read(workflow.GetAttributeValue(requestTypeAttribute.Key).AsGuid());

            if (requestType == null)
            {
                errorMessages.Add("Unknown request type.");
                return(false);
            }

            int orderId = workflow.Id;

            string requestTypePackageName = requestType.GetAttributeValue("PMMPackageName").Trim();

            BackgroundCheck bgCheck = getBgCheck(rockContext, workflow, person.PrimaryAliasId.Value);

            List <string[]> SSNTraceCounties = null;

            if (requestTypePackageName.Equals("PLUS", StringComparison.OrdinalIgnoreCase) && !String.IsNullOrWhiteSpace(bgCheck.ResponseXml))
            {
                IEnumerable <XElement> transactions                = XDocument.Parse(bgCheck.ResponseXml).Root.Elements("Transaction");
                IEnumerable <XElement> OrderXMLs                   = transactions.SelectMany(x => x.Elements("OrderXML"));
                IEnumerable <XElement> Orders                      = OrderXMLs.Select(x => x.Element("Order")).Where(x => x != null);
                IEnumerable <XElement> OrderDetails                = Orders.SelectMany(x => x.Elements("OrderDetail"));
                IEnumerable <XElement> SSNTraces                   = OrderDetails.Where(x => x.Attribute("ServiceCode")?.Value == "SSNTrace" && x.Element("Status") != null);
                IEnumerable <XElement> SSNTraceResults             = SSNTraces.Select(x => x.Element("Result"));
                IEnumerable <XElement> SSNTraceIndividuals         = SSNTraceResults.SelectMany(x => x.Elements("Individual"));
                IEnumerable <XElement> SSNTraceIndividualsToSearch = SSNTraceIndividuals.Where(x => x.Element("EndDate") == null || x.Element("EndDate").Element("Year") == null || (x.Element("EndDate").Element("Year").Value.AsInteger() > (DateTime.Now.Year - 8)));
                SSNTraceCounties = SSNTraceIndividualsToSearch.Where(x => x.Element("County") != null && x.Element("State") != null).Select(x => new string[] { x.Element("County").Value, x.Element("State").Value }).ToList();
            }

            XElement xTransaction = makeBGRequest(bgCheck, ssn, requestType, billingCode, SSNTraceCounties);

            saveTransaction(rockContext, bgCheck, xTransaction);
            handleTransaction(rockContext, bgCheck, xTransaction);
            return(true);

            //catch (Exception ex)
            //{
            //    ExceptionLogService.LogException(ex, null);
            //    errorMessages.Add(ex.Message);
            //    return false;
            //}
        }
Esempio n. 16
0
        public static void SaveResults(RockContext rockContext, BackgroundCheck bgCheck, XElement xResult)
        {
            bool createdNewAttribute = false;

            if (xResult != null)
            {
                var xOrder = xResult.Elements("Order").FirstOrDefault();
                if (xOrder != null)
                {
                    bool resultFound = false;

                    // Find any order details with a status element
                    string reportStatus = "Pass";
                    foreach (var xOrderDetail in xOrder.Elements("OrderDetail"))
                    {
                        var goodStatus = (xOrderDetail.Attribute("ServiceCode")?.Value == "SSNTrace") ? "COMPLETE" : "NO RECORD";

                        var xStatus = xOrderDetail.Elements("Status").FirstOrDefault();
                        if (xStatus != null)
                        {
                            resultFound = true;
                            if (xStatus.Value != goodStatus)
                            {
                                reportStatus = "Review";
                                break;
                            }
                        }
                    }

                    if (resultFound)
                    {
                        // If no records found, still double-check for any alerts
                        if (reportStatus != "Review")
                        {
                            var xAlerts = xOrder.Elements("Alerts").FirstOrDefault();
                            if (xAlerts != null)
                            {
                                if (xAlerts.Elements("OrderId").Any())
                                {
                                    reportStatus = "Review";
                                }
                            }
                        }

                        // Save the recommendation
                        string recommendation = (from o in xOrder.Elements("Recommendation") select o.Value).FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(recommendation))
                        {
                            if (SaveAttributeValue(bgCheck.Workflow, "ReportRecommendation", recommendation,
                                                   FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext,
                                                   new Dictionary <string, string> {
                                { "ispassword", "false" }
                            }))
                            {
                                createdNewAttribute = true;
                            }
                        }

                        // Save the report link
                        Guid?  binaryFileGuid = null;
                        string reportLink     = (from o in xOrder.Elements("ReportLink") select o.Value).FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(reportLink))
                        {
                            if (SaveAttributeValue(bgCheck.Workflow, "ReportLink", reportLink,
                                                   FieldTypeCache.Read(Rock.SystemGuid.FieldType.URL_LINK.AsGuid()), rockContext))
                            {
                                createdNewAttribute = true;
                            }

                            // Save the report
                            binaryFileGuid = SaveFile(bgCheck.Workflow.Attributes["Report"], reportLink, bgCheck.Workflow.Id.ToString() + ".pdf");
                            if (binaryFileGuid.HasValue)
                            {
                                if (SaveAttributeValue(bgCheck.Workflow, "Report", binaryFileGuid.Value.ToString(),
                                                       FieldTypeCache.Read(Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid()), rockContext,
                                                       new Dictionary <string, string> {
                                    { "binaryFileType", "" }
                                }))
                                {
                                    createdNewAttribute = true;
                                }
                            }
                        }

                        // Save the status
                        if (SaveAttributeValue(bgCheck.Workflow, "ReportStatus", reportStatus,
                                               FieldTypeCache.Read(Rock.SystemGuid.FieldType.SINGLE_SELECT.AsGuid()), rockContext,
                                               new Dictionary <string, string> {
                            { "fieldtype", "ddl" }, { "values", "Pass,Fail,Review" }
                        }))
                        {
                            createdNewAttribute = true;
                        }

                        // Update the background check file
                        if (bgCheck != null)
                        {
                            bgCheck.ResponseDate = RockDateTime.Now;
                            bgCheck.RecordFound  = reportStatus == "Review";

                            if (binaryFileGuid.HasValue)
                            {
                                var binaryFile = new BinaryFileService(rockContext).Get(binaryFileGuid.Value);
                                if (binaryFile != null)
                                {
                                    bgCheck.ResponseDocumentId = binaryFile.Id;
                                }
                            }
                        }
                    }
                }
            }

            rockContext.SaveChanges();

            if (createdNewAttribute)
            {
                AttributeCache.FlushEntityAttributes();
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Sends a background request to Checkr.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="workflow">The Workflow initiating the request.</param>
        /// <param name="personAttribute">The person attribute.</param>
        /// <param name="ssnAttribute">The SSN attribute.</param>
        /// <param name="requestTypeAttribute">The request type attribute.</param>
        /// <param name="billingCodeAttribute">The billing code attribute.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns>
        /// True/False value of whether the request was successfully sent or not.
        /// </returns>
        public override bool SendRequest(RockContext rockContext, Model.Workflow workflow,
                                         AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute,
                                         AttributeCache billingCodeAttribute, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            try
            {
                // Check to make sure workflow is not null
                if (workflow == null)
                {
                    errorMessages.Add("The 'Checkr' background check provider requires a valid workflow.");
                    UpdateWorkflowRequestStatus(workflow, rockContext, "FAIL");
                    return(true);
                }

                Person person;
                int?   personAliasId;
                if (!GetPerson(rockContext, workflow, personAttribute, out person, out personAliasId, errorMessages))
                {
                    errorMessages.Add("Unable to get Person.");
                    UpdateWorkflowRequestStatus(workflow, rockContext, "FAIL");
                    return(true);
                }

                string packageName;
                if (!GetPackageName(rockContext, workflow, requestTypeAttribute, out packageName, errorMessages))
                {
                    errorMessages.Add("Unable to get Package.");
                    UpdateWorkflowRequestStatus(workflow, rockContext, "FAIL");
                    return(true);
                }

                string candidateId;
                if (!CreateCandidate(person, out candidateId, errorMessages))
                {
                    errorMessages.Add("Unable to create candidate.");
                    UpdateWorkflowRequestStatus(workflow, rockContext, "FAIL");
                    return(true);
                }

                if (!CreateInvitation(candidateId, packageName, errorMessages))
                {
                    errorMessages.Add("Unable to create invitation.");
                    UpdateWorkflowRequestStatus(workflow, rockContext, "FAIL");
                    return(true);
                }

                using (var newRockContext = new RockContext())
                {
                    var backgroundCheckService = new BackgroundCheckService(newRockContext);
                    var backgroundCheck        = backgroundCheckService.Queryable()
                                                 .Where(c =>
                                                        c.WorkflowId.HasValue &&
                                                        c.WorkflowId.Value == workflow.Id)
                                                 .FirstOrDefault();

                    if (backgroundCheck == null)
                    {
                        backgroundCheck            = new BackgroundCheck();
                        backgroundCheck.WorkflowId = workflow.Id;
                        backgroundCheckService.Add(backgroundCheck);
                    }

                    backgroundCheck.PersonAliasId = personAliasId.Value;
                    backgroundCheck.ForeignId     = 2;
                    backgroundCheck.PackageName   = packageName;
                    backgroundCheck.RequestDate   = RockDateTime.Now;
                    backgroundCheck.RequestId     = candidateId;
                    newRockContext.SaveChanges();

                    UpdateWorkflowRequestStatus(workflow, newRockContext, "SUCCESS");
                    return(true);
                }
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, null);
                errorMessages.Add(ex.Message);
                UpdateWorkflowRequestStatus(workflow, rockContext, "FAIL");
                return(true);
            }
        }
        public static bool submit(int iRequestID, string sSSN, string sDLN, string sResponseURL, int iStateID, string sUser, string sPassword, string sPlusCounty, string sPlusState)
        {
            if (sUser == null || sPassword == null)
            {
                return(false);
            }

            // Get the already created (via create()) background check request
            BackgroundCheck bc = (from e in DbUtil.Db.BackgroundChecks
                                  where e.Id == iRequestID
                                  select e).Single();

            if (bc == null)
            {
                return(false);
            }

            // Create XML
            XmlWriterSettings xws = new XmlWriterSettings();

            xws.Indent = false;
            xws.NewLineOnAttributes = false;
            xws.NewLineChars        = "";

            // Create Bundle
            SubmitBundle sb = new SubmitBundle();

            sb.iPeopleID         = bc.PeopleID;
            sb.sUser             = sUser;
            sb.sPassword         = sPassword;
            sb.sBillingReference = bc.Id.ToString();
            sb.sSSN         = sSSN;
            sb.sServiceCode = bc.ServiceCode;
            sb.sResponseURL = sResponseURL;
            sb.bTestMode    = (DbUtil.Db.Setting("PMMTestMode", "false") == "true");
            sb.sPlusCounty  = sPlusCounty;
            sb.sPlusState   = sPlusState;

            // Get State (if MVR)
            if (bc.ServiceCode == "MVR" && iStateID > 0)
            {
                BackgroundCheckMVRCode bcmc = (from e in DbUtil.Db.BackgroundCheckMVRCodes
                                               where e.Id == iStateID
                                               select e).Single();

                if (bcmc == null)
                {
                    return(false);
                }

                sb.sDNL       = sDLN;
                sb.sStateCode = bcmc.Code;
                sb.sStateAbbr = bcmc.StateAbbr;
            }

            // Main Request
            MemoryStream msRequest = new MemoryStream();
            XmlWriter    xwWriter  = XmlWriter.Create(msRequest, xws);

            xmlCreate(xwWriter, sb);
            string sXML = Encoding.UTF8.GetString(msRequest.ToArray()).Substring(1);

            msRequest.Close();

            // Submit Request to PMM
            var fields = new NameValueCollection();

            fields.Add("REQUEST", sXML);

            WebClient wc = new WebClient();

            wc.Encoding = System.Text.Encoding.UTF8;
            var response = Encoding.UTF8.GetString(wc.UploadValues(PMM_URL, "POST", fields));

            ResponseBundle rbResponse = processResponse(response);

            if (rbResponse.bHasErrors)
            {
                bc.StatusID      = 0;
                bc.ErrorMessages = rbResponse.sErrors;
            }
            else
            {
                if (rbResponse.bHasInstant)
                {
                    bc.StatusID      = 3;
                    bc.ErrorMessages = "";
                    bc.ReportID      = Int32.Parse(rbResponse.sReportID);
                    bc.ReportLink    = rbResponse.sReportLink;
                }
                else
                {
                    bc.StatusID      = 2;
                    bc.ErrorMessages = "";
                    bc.ReportID      = Int32.Parse(rbResponse.sReportID);
                }
            }

            DbUtil.Db.SubmitChanges();
            return(true);
        }