Example #1
0
        public static void UpdateSisAScores(IFormsRepository formsRepo, int formResultId)
        {
            try
            {
                def_Forms frm = formsRepo.GetFormByIdentifier("SIS-A");
                int       standardScoreTotal = SharedScoring.UpdateSisScoresNoSave
                                               (
                    formsRepo, frm, formResultId,
                    getSisASubscaleCatagories(),
                    (int totalRawScore, double avgRawScore, SubscaleCatagory cat) => { return(GetSisASubscaleStandardScore(totalRawScore, cat)); },
                    (int totalRawScore, double avgRawScore, SubscaleCatagory cat) => { return(GetSisASubscalePercentile(totalRawScore, cat)); }
                                               );

                //save standard scores to database
                int compositeIndex      = GetSisASupportNeedsIndex(standardScoreTotal);
                int compositePercentile = GetSisASupportNeedsPercentile(standardScoreTotal);
                SharedScoring.UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_support_needs_index", compositeIndex);
                SharedScoring.UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_sni_percentile_rank", compositePercentile);
                formsRepo.Save();
            }
            catch (Exception xcptn)
            {
                Debug.WriteLine("UpdateSisAScores exception: " + xcptn.Message);
            }
        }
        public ActionResult AddFormResults()
        {
            string paramFormId = Request["formId"] as string;

            mLogger.Debug("* * *  ResultsController AddFormResults formId: {0}", paramFormId);

            Session["formId"] = paramFormId;
            int             formId = Convert.ToInt32(paramFormId);
            def_FormResults frmRes = new def_FormResults()
            {
                formId        = formId,
                formStatus    = 0,
                sessionStatus = 0,
                dateUpdated   = DateTime.Today
            };
            int frmRslt = formsRepo.AddFormResult(frmRes);

            frmRes = formsRepo.GetFormResultById(frmRslt);
            def_Forms        frm   = formsRepo.GetFormById(formId);
            List <def_Parts> parts = formsRepo.GetFormParts(frm);

            // Setup session variables
            SessionForm sf = SessionHelper.SessionForm;

            sf.formId       = frm.formId;
            sf.formResultId = frmRslt;

            return(RedirectToAction("Parts", "Results", null));
        }
        public static void UpdateSisCScores(IFormsRepository formsRepo, int formResultId, int ageInYears)
        {
            def_Forms frm = formsRepo.GetFormByIdentifier("SIS-C");

            SharedScoring.UpdateSisScoresNoSave
            (
                formsRepo, frm, formResultId,
                getSisCSubscaleCatagories(),
                (int totalRawScore, double avgRawScore, SubscaleCatagory cat) => { return(GetSisCSubscaleStandardScore(avgRawScore, cat, ageInYears)); },
                (int totalRawScore, double avgRawScore, SubscaleCatagory cat) => { return(GetSisCSubscalePercentile(avgRawScore, cat, ageInYears)); }
            );

            def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultIdentifier(formResultId, "scr_total_rating");
            double totalRating       = Convert.ToDouble(rv.rspValue);
            double meanRating        = Math.Round(totalRating / 7, 2); //usd only for SIS-C reports

            //save standard scores to database
            double compositeIndex      = GetSisCSupportNeedsIndex(meanRating, ageInYears);
            double compositePercentile = GetSisCSupportNeedsPercentile(meanRating, ageInYears);

            SharedScoring.UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_support_needs_index", compositeIndex);
            SharedScoring.UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_sni_percentile_rank", compositePercentile);

            formsRepo.Save();
        }
        private void addUsedForms(SearchModel model)
        {
            ExportModel exportModel = new ExportModel();

            exportModel.formIds       = model.formIds;
            exportModel.formResultIds = model.sisIds;

            exportModel.formNames = new Dictionary <int, string>();

            foreach (int?nFormId in exportModel.formIds)
            {
                if (nFormId != null)
                {
                    int       formId = (int)nFormId;
                    def_Forms form   = formsRepo.GetFormById(formId);
                    if (form != null)
                    {
                        string name = form.identifier;
                        exportModel.formNames.Add(formId, name);
                    }
                }
            }

            Session["ExportModel"] = exportModel;

            model.usedForms = exportModel.formNames;
            if (model.usedForms.Count() > 1)
            {
                model.usedForms.Add(-1, "All");
            }
        }
Example #5
0
        public static def_Sections GetSectionForSubscaleCatagory(def_Forms frm, SubscaleCatagory cat)
        {
            if (cat == null)
            {
                throw new Exception("Could not find a section for NULL SubscaleCatagory");
            }

            //def_Forms frm = formsRepo.GetFormByIdentifier("SIS-A");
            try
            {
                foreach (def_FormParts fp in frm.def_FormParts)
                {
                    foreach (def_PartSections ps in fp.def_Parts.def_PartSections)
                    {
                        string s = ps.def_Sections.title.Replace(" ", "").ToLower();
                        foreach (string numonic in cat.getNumonics())
                        {
                            if (s.Contains(numonic.ToString().ToLower()))
                            {
                                return(ps.def_Sections);
                            }
                        }
                    }
                }
            }
            catch (Exception xcptn)
            {
                Debug.WriteLine("GetSectionForSubscaleCatagory: " + xcptn.Message);
            }

            throw new Exception("Could not find a section for SubscaleCatagory \"" + cat.getNumonics()[0] + "\"");
        }
        public ActionResult Index()
        {
            if (!SessionHelper.IsUserLoggedIn)
            {
                return(RedirectToAction("Index", "Account", null));
            }

            if (SessionHelper.SessionForm == null)
            {
                SessionHelper.SessionForm = new SessionForm();
            }

            // retrieve and set SessionForm params
            string    formIdent = "View_Test_Form";
            def_Forms frm       = formsRepo.GetFormByIdentifier(formIdent);

            if (frm == null)
            {
                return(Content("Could not find form with identifier \"" + formIdent + "\""));
            }
            def_FormResults fr = formsRepo.GetFormResultsByFormId(frm.formId).FirstOrDefault();

            if (fr == null)
            {
                fr = new def_FormResults()
                {
                    formId           = frm.formId,
                    formStatus       = 0,
                    sessionStatus    = 0,
                    dateUpdated      = DateTime.Now,
                    deleted          = false,
                    locked           = false,
                    archived         = false,
                    EnterpriseID     = 0,
                    GroupID          = 0,
                    subject          = 0,
                    interviewer      = 0,
                    assigned         = 0,
                    training         = false,
                    reviewStatus     = 0,
                    statusChangeDate = DateTime.Now
                };
                formsRepo.AddFormResult(fr);
            }


            SessionHelper.SessionForm.formId         = frm.formId;
            SessionHelper.SessionForm.formResultId   = fr.formResultId;
            SessionHelper.SessionForm.formIdentifier = frm.identifier;
            SessionHelper.LoginStatus.EnterpriseID   = 0;

            def_Parts prt = formsRepo.GetFormParts(frm)[0];

            SessionHelper.SessionForm.partId = prt.partId;
            Session["part"] = prt.partId;

            def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

            return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = SessionHelper.SessionForm.partId.ToString() }));
        }
        public ActionResult StartAssmnt()
        {
            if (!SessionHelper.IsUserLoggedIn)
            {
                return(RedirectToAction("Index", "Account", null));
            }

            if (SessionHelper.SessionForm == null)
            {
                SessionHelper.SessionForm = new SessionForm();
            }

            // retrieve and set SessionForm params
            string paramFormId = Request["formId"] as string;

            SessionHelper.SessionForm.formId = Convert.ToInt32(paramFormId);

            string paramFormResultId = Request["formResultId"] as string;

            SessionHelper.SessionForm.formResultId = Convert.ToInt32(paramFormResultId);

            // get the sectionId of the first section of the first part based on the formId
            def_Forms frm = formsRepo.GetFormById(SessionHelper.SessionForm.formId);

            SessionHelper.SessionForm.formIdentifier = frm.identifier;

            def_Parts prt = formsRepo.GetFormParts(frm)[0];

            SessionHelper.SessionForm.partId = prt.partId;
            Session["part"] = prt.partId;

            def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

            return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = SessionHelper.SessionForm.partId.ToString() }));
        }
Example #8
0
        public AdapLAStubApp(IFormsRepository fr)
        {
            formsRepo = fr;
            auth      = new AuthenticationClient();
            stubForm  = formsRepo.GetFormByIdentifier(stubFormIdentifier);

            if (stubForm == null)
            {
                throw new Exception("Could not find LA Stub-application form with identifier \"" + stubFormIdentifier + "\"");
            }
        }
        public ActionResult NewBlankAssessment()
        {
            string formId = Request["formId"];

            SearchModel model = new SearchModel();

            if (model.create && model.edit)
            {
                /*
                 * **** Check if User has authorization to create an Assessment for this Group.
                 */
                // *** RRB 10/27/15 - the Create Assessment should be a method used here and from the 'Action' above.
                def_FormResults frmRes = FormResults.CreateNewFormResultFull(formId,
                                                                             SessionHelper.LoginStatus.EnterpriseID.ToString(),
                                                                             SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].GroupID.ToString(),
                                                                             "0",
                                                                             SessionHelper.LoginStatus.UserID.ToString());
                if (ventureMode)
                {
                    frmRes.assigned = SessionHelper.LoginStatus.UserID;
                }

                formsRepo.AddFormResult(frmRes);

                if (SessionHelper.SessionForm == null)
                {
                    SessionHelper.SessionForm = new SessionForm();
                }
                SessionForm sf = SessionHelper.SessionForm;

                /*
                 * if (sf == null)
                 * {
                 *  return RedirectToAction("Index", "Search", null);
                 * }
                 */
                // set SessionForm params
                sf.formId       = frmRes.formId;                    // TODO: How to determine which formid?
                sf.formResultId = frmRes.formResultId;

                // get the sectionId of the first section of the first part based on the formId
                def_Forms frm = formsRepo.GetFormById(sf.formId);
                def_Parts prt = formsRepo.GetFormParts(frm)[0];
                sf.partId       = prt.partId;
                Session["part"] = prt.partId;
                def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

                return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
            }
            else
            {
                return(RedirectToAction("Index", "Search"));
            }
        }
Example #10
0
        /// <summary>
        /// Perform generic validation:
        ///
        /// For the given formResultId (assigned in SharedValidation constructor),
        /// Make sure there is some non-null, non-whitespace response value for each of the
        /// def_ItemVariables corresponding to a def_SectionItems entry (or def_SectionItemsEnt entry)
        /// where the "display" "validation" and "requiredForm" flags are all marked 1/true.
        ///
        /// Only def_SectionItems for the current def_Forms (parameter "frm") are considered.
        ///
        /// Only def_SectionItemsEnt for the current def_Forms and form enterprise
        /// </summary>
        /// <param name="amt"></param>
        /// <param name="frm"></param>
        /// <param name="ItemVariableSuffixesToSkip"></param>
        /// <returns></returns>
        public bool DoGenericValidation(
            IFormsRepository formsRepo,
            TemplateItems amt,
            def_Forms frm,
            string[] ItemVariableSuffixesToSkip = null)
        {
            //pick an enterprise ID to use for validation purposes
            int  entId   = SessionHelper.LoginStatus.EnterpriseID;
            bool invalid = false;

            amt.missingItemVariablesBySectionByPart = new Dictionary <int, Dictionary <int, List <string> > >();

            //get a list of identifiers for all the required item variables
            //typically this list will be pulled from a single EntAppConfig record for this enterprise/form
            //if such a record is not available, the meta-data structure will be traversed to find the required itemvariables
            //and an EntAppDonfig record will be added to speed the next validation for this enterprise/form
            List <ItemVariableIdentifierWithPartSection> requiredIvs = GetRequiredItemVarsWithPartsSections(formsRepo, frm, entId);

            //iterate through all the required item variable identifiers
            foreach (ItemVariableIdentifierWithPartSection ivps in requiredIvs)
            {
                //if this identifier ends with one of the "skippable" suffixes, skip it
                if (ItemVariableSuffixesToSkip != null)
                {
                    bool skip = false;
                    foreach (string suffixtoSkip in ItemVariableSuffixesToSkip)
                    {
                        if (ivps.itemVariableIdentifier.EndsWith(suffixtoSkip))
                        {
                            skip = true;
                            break;
                        }
                    }
                    if (skip)
                    {
                        continue;
                    }
                }

                //check if we have a valid response for this required item variable
                ValuePair vp = allResponses.FirstOrDefault(vpt => vpt.identifier == ivps.itemVariableIdentifier);
                if (vp == null || vp.rspValue == null || vp.rspValue.Trim().Length == 0)
                {
                    invalid = true;
                    AddMissingItemtoModel(ivps, amt);
                }
            }

            return(invalid);
        }
        public void UpdateAssessmentScores(def_FormResults frmRslt)
        {
            def_Forms frm = formsRepo.GetFormById(frmRslt.formId);

            if (frm.identifier.Equals("SIS-A"))
            {
                SisAScoring.UpdateSisAScores(formsRepo, frmRslt.formResultId);
            }
            else if (frm.identifier.Equals("SIS-C"))
            {
                int ageInYears = SharedScoring.ComputeClientAgeInYears(formsRepo, frmRslt.formResultId);
                SisCScoring.UpdateSisCScores(formsRepo, frmRslt.formResultId, ageInYears);
            }
        }
Example #12
0
        public static void updateSection1ScoresNoSave(
            IFormsRepository formsRepo,
            def_Forms frm,
            int formResultId)
        {
            def_FormResults fr    = formsRepo.GetFormResultById(formResultId);
            int             entId = fr.EnterpriseID.HasValue ? fr.EnterpriseID.Value : 0;

            string sectionIdentifierPrefix = frm.identifier; //"SIS-A" or "SIS-C"

            foreach (string shortSectionName in new string[] { "1A", "1B" })
            {
                string       sectionIdentifier = sectionIdentifierPrefix + " " + shortSectionName; // e.g. "SIS-A 1A"
                def_Sections sct = formsRepo.GetSectionByIdentifier(sectionIdentifier);
                if (sct == null)
                {
                    throw new Exception("Could not find section with identifier \"" + sectionIdentifier + "\"");
                }

                int rawTotal = 0;

                foreach (def_SectionItems si in formsRepo.GetSectionItemsBySectionIdEnt(sct.sectionId, entId))
                {
                    def_ItemVariables rawScoreIv = formsRepo.GetItemVariablesByItemId(si.itemId)
                                                   .Where(iv => iv.identifier.EndsWith("Support")).SingleOrDefault(); //e.g. "Q1A1_ExMedSupport"

                    if (rawScoreIv != null)
                    {
                        def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(formResultId, rawScoreIv.itemVariableId);
                        if (rv != null && !String.IsNullOrWhiteSpace(rv.rspValue))
                        {
                            int rawScore;
                            if (Int32.TryParse(rv.rspValue, out rawScore))
                            {
                                rawTotal += rawScore;
                            }
                            else
                            {
                                Debug.WriteLine("* * * Skipping item on updating section 1 scores: " +
                                                "Could not parse integer from response value \"{0}\" for itemVariable \"{1}\". (formResultID {2})",
                                                rv.rspValue, rawScoreIv.identifier, formResultId);
                            }
                        }
                    }
                }

                UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_" + shortSectionName + "_raw_total", rawTotal);
            }
        }
        /// <summary>
        /// Prints generic report of Assessment Questions / Answers
        /// </summary>
        /// <param name="formsRepo">Forms Repository</param>
        /// <param name="formResultId">Form Result ID (Assessment Answers)</param>
        /// <param name="outputPath"></param>
        /// <param name="grayscale"></param>
        /// <param name="customSectionOrderByIdentifiers"></param>
        public FormResultPdfReport(
            IFormsRepository formsRepo,
            int formResultId,
            string outputPath,
            bool grayscale)
        {
            Debug.WriteLine("FormResultPdfReport formResultId: " + formResultId.ToString());
            this.formResultId = formResultId;
            this.formsRepo    = formsRepo;
            this.formResults  = (formResultId == -1) ? null : formsRepo.GetFormResultById(formResultId);
            this.form         = (formResults == null) ? null : formsRepo.GetFormById(formResults.formId);    //formResults.def_Forms;
            this.output       = new PdfOutput(grayscale, outputPath);

            //add page number 1 as footer on first page
            output.appendPageFooter();
        }
        public ActionResult CSVOptions(string formId)
        {
            Debug.WriteLine("* * *  ExportController Parts formId: " + formId);
            Session["formId"] = formId;
            int       iFormId = Convert.ToInt32(formId);
            def_Forms frm     = formsRepo.GetFormById(iFormId);

            TemplateCsvOptions model = new TemplateCsvOptions();

            model.formPartMap = new Dictionary <string, int>();
            if (iFormId == 0)
            {
                if (model.parts == null)
                {
                    model.parts = new List <def_Parts>();
                }

                ExportModel exportModel = (ExportModel)Session["ExportModel"];
                List <int?> formIds     = exportModel.formIds;
                model.forms = new List <def_Forms>();

                foreach (int?id in formIds)
                {
                    // Use the dictionary to indicate the starting index for each form in the parts list.
                    model.formPartMap.Add(id + " start", model.parts.Count());
                    frm = formsRepo.GetFormById(Convert.ToInt32(id));
                    List <def_Parts> prts = formsRepo.GetFormParts(frm);
                    model.parts.AddRange(prts);
                    model.forms.Add(frm);

                    // Mark the final index.
                    model.formPartMap.Add(id + " end", model.parts.Count());
                }
            }
            else if (frm == null)
            {
                throw new Exception("ExportController.CSVOptions: could not find form with id " + formId);
            }
            else
            {
                model.parts = formsRepo.GetFormParts(frm);
            }
            model.formId           = iFormId;
            Session["formPartMap"] = model.formPartMap;
            return(View("~/Views/Templates/SIS/csvOptions.cshtml", model));
        }
        public ActionResult ViewReport(int formResultId, int formid)
        {
            if (SessionHelper.SessionForm == null)
            {
                SessionHelper.SessionForm = new SessionForm();
            }
            SessionForm sf = SessionHelper.SessionForm;

            sf.formId       = formid;
            sf.formResultId = formResultId;

            def_Forms form = formsRepo.GetFormById(formid);

            sf.formIdentifier = form.identifier;

            Session["part"] = (int)6;
            return(RedirectToAction("Template", "Results", new { sectionId = 38 }));
        }
Example #16
0
        public def_FormResults CreateMagiForm(int?subject)
        {
            def_Forms       f    = formsRepo.GetFormByIdentifier("LA-ADAP-MAGI");
            def_FormResults magi = new def_FormResults()
            {
                formId               = f.formId,
                formStatus           = 0,
                dateUpdated          = DateTime.Now,
                EnterpriseID         = SessionHelper.LoginStatus.EnterpriseID,
                GroupID              = SessionHelper.LoginStatus.GroupID,
                subject              = subject,
                interviewer          = SessionHelper.LoginStatus.UserID,
                statusChangeDate     = DateTime.Now,
                LastModifiedByUserId = SessionHelper.LoginStatus.UserID
            };

            magi.formResultId = formsRepo.AddFormResult(magi);

            return(magi);
        }
Example #17
0
        public ActionResult CreateStubApplication(string ramsellId)
        {
            if (!SessionHelper.IsUserLoggedIn)
            {
                return(RedirectToAction("Index", "Account", null));
            }

            if (SessionHelper.SessionForm == null)
            {
                SessionHelper.SessionForm = new SessionForm();
            }

            //createa new def_FormResult for the stub application
            AdapLAStubApp stubHelper = new AdapLAStubApp(formsRepo);
            int           newFrId    = stubHelper.CreateAndPrepopulateNewStubApp(ramsellId);
            def_Forms     stubForm   = stubHelper.GetStubForm();

            //setup session vars for viewing stub application screen(s)
            SessionHelper.SessionForm.formId         = stubForm.formId;
            SessionHelper.SessionForm.formResultId   = newFrId;
            SessionHelper.SessionForm.formIdentifier = AdapLAStubApp.stubFormIdentifier;
            SessionHelper.LoginStatus.EnterpriseID   = SessionHelper.LoginStatus.EnterpriseID;

            def_Parts prt = formsRepo.GetFormParts(stubForm)[0];

            SessionHelper.SessionForm.partId = prt.partId;
            Session["part"] = prt.partId;

            def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

            SessionHelper.SessionForm.sectionId = sct.sectionId;
            Session["section"] = sct.sectionId;

            //redirect to first section in newly-created stub app
            return(RedirectToAction("Template", "Results", new {
                sectionId = SessionHelper.SessionForm.sectionId.ToString(),
                partId = SessionHelper.SessionForm.partId.ToString()
            }));
        }
        public FileContentResult GetCsv()
        {
            string paramFormResultId = Request["formResultId"] as string;

            Debug.WriteLine("* * *  ExportController GetCsv formResultId: " + paramFormResultId);

            // Get all the itemVariable's in Assessment order
            // Write out the initial field name (identifier) record
            // Get the Item responses
            // Get the associated ResponseVariables
            // Write it out to CSV
            int              formResultId = Convert.ToInt32(paramFormResultId);
            def_FormResults  frmRes       = formsRepo.GetFormResultById(formResultId);
            def_Forms        frm          = formsRepo.GetFormById(frmRes.formId);
            List <def_Parts> parts        = formsRepo.GetFormParts(frm);

            // return new FileStreamResult(fileStream, "text/csv") { FileDownloadName = fileDownloadName };
            StringWriter sw = new StringWriter();

            sw.WriteLine("FirstName, LastName, NickName");
            sw.WriteLine("Charlie, Chaplin, Chuckles");
            return(File(new System.Text.UTF8Encoding().GetBytes(sw.ToString()), "text/csv", "SisAssmnt.csv"));
        }
Example #19
0
        public ActionResult Validate(FormCollection frmCllctn, TemplateItems ti)
        {
            //save response from formCollection into the DB
            ResultsController rc = new ResultsController(formsRepo);

            rc.ControllerContext = ControllerContext;
            rc.Save(frmCllctn, ti);

            int formResultId = SessionHelper.SessionForm.formResultId;

            SessionHelper.SessionForm.sectionId = -1;

            //Run generic validation
            AdapValidationErrorsModel model = new AdapValidationErrorsModel();

            model.navMenuModel       = AJBoggs.Adap.Templates.TemplateMenus.getAdapNavMenuModel(SessionHelper.SessionForm, formsRepo);
            model.validationMessages = new List <string>();
            model.missingItemVariablesBySectionByPart = new Dictionary <int, Dictionary <int, List <string> > >();
            def_Forms        frm          = formsRepo.GetFormById(SessionHelper.SessionForm.formId);
            List <ValuePair> allResponses = CommonExport.GetDataByFormResultId(formResultId);
            SharedValidation sv           = new SharedValidation(allResponses);
            bool             invalid      = sv.DoGenericValidation(formsRepo, model, frm);

            //transfer generic validation results to an ADAP-specific model
            model.titlesOfMissingSubsectionsBySectionByPart = new Dictionary <int, Dictionary <int, List <string> > >();
            foreach (int prtId in model.missingItemVariablesBySectionByPart.Keys)
            {
                model.titlesOfMissingSubsectionsBySectionByPart.Add(prtId, new Dictionary <int, List <string> >());
                foreach (int sctId in model.missingItemVariablesBySectionByPart[prtId].Keys)
                {
                    def_Sections sct = formsRepo.GetSectionById(sctId);
                    formsRepo.SortSectionItems(sct);
                    List <int> ssSectionIds = new List <int>();
                    foreach (def_SectionItems si in sct.def_SectionItems.Where(si => si.subSectionId.HasValue))
                    {
                        ssSectionIds.Add(formsRepo.GetSubSectionById(si.subSectionId.Value).sectionId);
                    }

                    model.titlesOfMissingSubsectionsBySectionByPart[prtId].Add(sctId, new List <string>());
                    foreach (string itemVariableIdent in model.missingItemVariablesBySectionByPart[prtId][sctId])
                    {
                        //for each item variable identifier returned by generic validation,
                        //lookup the corresponding subsection's title for display on the ADAP "validation errors" screen
                        def_ItemVariables iv  = formsRepo.GetItemVariableByIdentifier(itemVariableIdent);
                        def_Items         itm = iv == null ? null : iv.def_Items;
                        def_SectionItems  si  = itm == null ? null : formsRepo.getSectionItemsForItem(itm).Where(sit => ssSectionIds.Contains(sit.sectionId)).FirstOrDefault();
                        def_Sections      sub = si == null ? null : si.def_Sections;
                        if (sub != null && !model.titlesOfMissingSubsectionsBySectionByPart[prtId][sctId].Contains(sub.title))
                        {
                            model.titlesOfMissingSubsectionsBySectionByPart[prtId][sctId].Add(sub.title);
                        }
                    }
                }
            }

            //run CO-ADAP one-off validation
            if (AdapCOOneOffValidation.RunOneOffValidation(sv, model))
            {
                invalid = true;
            }

            //return the validation errors screen if any errors were found
            //model.validationMessages could have some warnings even if no errors were found, in which case "invalid" would be false here
            if (invalid)
            {
                return(View("~/Views/COADAP/ValidationErrors.cshtml", model));
            }

            //if no problems were found, or if warnings were found but no errors, return the next section in the application
            if (model.validationMessages.Count == 0)
            {
                model.validationMessages.Add("No errors were found");
            }
            int sectionId = Convert.ToInt16(frmCllctn["navSectionId"]);

            return(rc.Template(sectionId, model.validationMessages));
        }
Example #20
0
        public ActionResult CreateAdapApplication()
        {
            def_Forms frm = formsRepo.GetFormByIdentifier("ADAP");
            //string userId = Request["userId"];
            int userId = 0;

            try
            {
                userId = Convert.ToInt32(Request["userId"]);
            }
            catch (Exception excptn)
            {
                Debug.WriteLine("Adap Controller CreateAdapApplication exception:" + excptn.Message);
            }

            int?            intSO   = formsRepo.GetStatusDetailByMasterIdentifier(1, "CANCELLED").sortOrder;
            def_FormResults prevRes = formsRepo.GetEntities <def_FormResults>(x => x.formId == frm.formId &&
                                                                              x.subject == userId &&
                                                                              x.formStatus != intSO)
                                      .OrderByDescending(x => x.dateUpdated)
                                      .FirstOrDefault();

            //def_FormResults prevRes = frm.def_FormResults.Where(f => f.subject == userId && intSO != null && f.formStatus != intSO).OrderByDescending(f => f.dateUpdated).FirstOrDefault();


            if ((prevRes == null) || (prevRes.formStatus == formsRepo.GetStatusDetailByMasterIdentifier(1, "APPROVED").sortOrder))
            {
                AuthenticationClient webclient = new AuthenticationClient();
                UserDisplay          ud        = webclient.GetUserDisplay(userId);

                Dictionary <string, string> ItemsToPopulateFromUAS = new Dictionary <string, string>();
                ItemsToPopulateFromUAS.Add(
                    "ADAP_D1_FirstName_item", String.IsNullOrEmpty(ud.FirstName) ? String.Empty : ud.FirstName);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_D1_LastName_item", String.IsNullOrEmpty(ud.LastName) ? String.Empty : ud.LastName);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_D1_MiddleIntl_item", String.IsNullOrEmpty(ud.MiddleName) ? String.Empty : ud.MiddleName.Substring(0, 1));
                ItemsToPopulateFromUAS.Add(
                    "ADAP_D2_DOB_item", (ud.DOB == null) ? String.Empty : Convert.ToDateTime(ud.DOB).ToString("MM/dd/yyyy"));
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C1_Address_item", (ud.Addresses != null && ud.Addresses.Count() > 0) ? ud.Addresses[0].Address1 : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C1_MayContactYN_item", (ud.Addresses != null && ud.Addresses.Count() > 0) ? ((ud.Addresses[0].MayContactAddress) ? "1" : "0") : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C1_City_item", (ud.Addresses != null && ud.Addresses.Count() > 0) ? ud.Addresses[0].City : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C1_State_item", (ud.Addresses != null && ud.Addresses.Count() > 0) ? ud.Addresses[0].State : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C1_Zip_item", (ud.Addresses != null && ud.Addresses.Count() > 0) ? ud.Addresses[0].ZIP : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C2_Address_item", (ud.Addresses != null && ud.Addresses.Count() > 1) ? ud.Addresses[1].Address1 : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C2_MayContactYN_item", (ud.Addresses != null && ud.Addresses.Count() > 1) ? ((ud.Addresses[1].MayContactAddress) ? "1" : "0") : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C2_City_item", (ud.Addresses != null && ud.Addresses.Count() > 1) ? ud.Addresses[1].City : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C2_State_item", (ud.Addresses != null && ud.Addresses.Count() > 1) ? ud.Addresses[1].State : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C2_Zip_item", (ud.Addresses != null && ud.Addresses.Count() > 1) ? ud.Addresses[1].ZIP : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C3_Phone1_Num_item", (ud.Phones != null && ud.Phones.Count() > 0) ? ud.Phones[0].Phone : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C3_Phone1_MayMsgYN_item", (ud.Phones != null && ud.Phones.Count() > 0) ? ((ud.Phones[0].MayContactPhone) ? "1" : "0") : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C3_Phone2_Num_item", (ud.Phones != null && ud.Phones.Count() > 1) ? ud.Phones[1].Phone : String.Empty);
                ItemsToPopulateFromUAS.Add(
                    "ADAP_C3_Phone2_MayMsgYN_item", (ud.Phones != null && ud.Phones.Count() > 1) ? ((ud.Phones[1].MayContactPhone) ? "1" : "0") : String.Empty);

                // * * * OT 1-20-16 updated this list based on Docs/ADAP/ADAP_item_list.xslx (revision 80734)
                string[] ItemIdentifiersToPopulateFromPrevApplication = new string[]
                {
                    #region long list of item identifiers
                    "ADAP_D1_LastName_item",
                    "ADAP_D1_FirstName_item",
                    "ADAP_D1_MiddleIntl_item",
                    "ADAP_D1_AltName_item",
                    "ADAP_D2_DOB_item",
                    "ADAP_D3_White_item",
                    "ADAP_D3_Black_item",
                    "ADAP_D3_Asian_item",
                    "ADAP_D3_Native_item",
                    "ADAP_D3_Indian_item",
                    "ADAP_D4_EthnicDrop_item",
                    "ADAP_D4_Mexican_item",
                    "ADAP_D4_Puerto_item",
                    "ADAP_D4_Cuban_item",
                    "ADAP_D4_Other_item",
                    "ADAP_D5_Indian_item",
                    "ADAP_D5_Filipino_item",
                    "ADAP_D5_Korean_item",
                    "ADAP_D5_Other_item",
                    "ADAP_D5_Chinese_item",
                    "ADAP_D5_Japanese_item",
                    "ADAP_D5_Vietnamese_item",
                    "ADAP_D5_NA_item",
                    "ADAP_D6_Native_item",
                    "ADAP_D6_Guam_item",
                    "ADAP_D6_Samoan_item",
                    "ADAP_D6_Other_item",
                    "ADAP_D6_NA_item",
                    "ADAP_D7_LangDrop_item",
                    "ADAP_D7_LangOther_item",
                    "ADAP_D8_CurrGenderDrop_item",
                    "ADAP_D8_BirthGenderDrop_item",
                    "ADAP_D9_Ramsell_item",
                    "ADAP_D10_SSN_item",
                    "ADAP_C1_Address_item",
                    "ADAP_C1_City_item",
                    "ADAP_C1_State_item",
                    "ADAP_C1_Zip_item",
                    "ADAP_C1_County_item",
                    "ADAP_C1_MayContactYN_item",
                    "ADAP_C2_SameAsMailing_item",
                    "ADAP_C2_Address_item",
                    "ADAP_C2_City_item",
                    "ADAP_C2_State_item",
                    "ADAP_C2_Zip_item",
                    "ADAP_C2_County_item",
                    "ADAP_C2_MayContactYN_item",
                    "ADAP_C3_Phone1_Num_item",
                    "ADAP_C3_Phone1_Type_item",
                    "ADAP_C3_Phone1_MayMsgYN_item",
                    "ADAP_C3_Phone2_Num_item",
                    "ADAP_C3_Phone2_Type_item",
                    "ADAP_C3_Phone2_MayMsgYN_item",
                    "ADAP_C4_MayCallYN_item",
                    "ADAP_C4_Name_item",
                    "ADAP_C4_Phone_item",
                    "ADAP_C4_KnowHivYN_item",
                    "ADAP_C5_HasCaseMngrYN_item",
                    "ADAP_C5_Mngr1_Name_item",
                    "ADAP_C5_Mngr1_Clinic_item",
                    "ADAP_C5_Mngr2_Name_item",
                    "ADAP_C5_Mngr2_Clinic_item",
                    "ADAP_C5_CanReferYN_item",
                    "ADAP_M1_Month_item",
                    "ADAP_M1_Year_item",
                    "ADAP_M1_DiagnosisLoc_item",
                    "ADAP_M2_ToldAIDS_item",
                    "ADAP_M3_ToldHepC_item",
                    "ADAP_M4_Clinic_item",
                    "ADAP_I1_Med_Yes_item",
                    "ADAP_I1_Med_Denied_item",
                    "ADAP_I1_Med_No_item",
                    "ADAP_I1_Med_Waiting_item",
                    "ADAP_I1_Med_DontKnow_item",
                    "ADAP_I1_DeniedReason_item",
                    "ADAP_I1_NotAppliedReason_item",
                    "ADAP_I2_AffCareOpt_item",
                    "ADAP_I2_AffCareOther_item",
                    "ADAP_I3_MedicareYN_item",
                    "ADAP_I3_MedNumber_item",
                    "ADAP_I3_PartAYN_item",
                    "ADAP_I3_PartBYN_item",
                    "ADAP_I3_PartADate_item",
                    "ADAP_I3_PartBDate_item",
                    "ADAP_H1_StatusDrop_item",
                    "ADAP_H2_RelnDrop_item",
                    "ADAP_H2_RelnOther_item",
                    "ADAP_H3_FileTaxYN_item",
                    "ADAP_H3_TaxStatusOpt_item",
                    "ADAP_H3_TaxDependants_item",
                    "ADAP_H3_TaxNotFileOpt_item",
                    "ADAP_H3_TaxNotFileOther_item",
                    "ADAP_H3_Relatives_item",
                    "ADAP_H4_ChildrenIn_item",
                    "ADAP_H4_ChildrenOut_item",
                    "ADAP_F1_EmployOpt_item",
                    "ADAP_F1_EmployOther_item",
                    "ADAP_F1_EmployerInsOpt_item",
                    "ADAP_F1_EmployNotEnrolled_item",
                    "ADAP_F2_EmployLast90YN_item",
                    "ADAP_F3_A_Recipient_item",
                    "ADAP_F3_A_IncomeTypeDrop_item",
                    "ADAP_F3_A_Employer_item",
                    "ADAP_F3_A_EmployStart_item",
                    "ADAP_F3_A_TempYN_item",
                    "ADAP_F3_A_IncomeTypeOther_item",
                    "ADAP_F3_A_IncomeAmt_item",
                    "ADAP_F3_A_EmployerForm_item",
                    "ADAP_F3_B_Recipient_item",
                    "ADAP_F3_B_IncomeTypeDrop_item",
                    "ADAP_F3_B_Employer_item",
                    "ADAP_F3_B_EmployStart_item",
                    "ADAP_F3_B_TempYN_item",
                    "ADAP_F3_B_IncomeTypeOther_item",
                    "ADAP_F3_B_IncomeAmt_item",
                    "ADAP_F3_B_EmployerForm_item",
                    "ADAP_F3_C_Recipient_item",
                    "ADAP_F3_C_IncomeTypeDrop_item",
                    "ADAP_F3_C_Employer_item",
                    "ADAP_F3_C_EmployStart_item",
                    "ADAP_F3_C_TempYN_item",
                    "ADAP_F3_C_IncomeTypeOther_item",
                    "ADAP_F3_C_IncomeAmt_item",
                    "ADAP_F3_C_EmployerForm_item",
                    "ADAP_F3_D_Recipient_item",
                    "ADAP_F3_D_IncomeTypeDrop_item",
                    "ADAP_F3_D_Employer_item",
                    "ADAP_F3_D_EmployStart_item",
                    "ADAP_F3_D_TempYN_item",
                    "ADAP_F3_D_IncomeTypeOther_item",
                    "ADAP_F3_D_IncomeAmt_item",
                    "ADAP_F3_D_EmployerForm_item",
                    "ADAP_cert_NoSharing_item",
                    "ADAP_cert_Reminders_item"
                    #endregion
                };

                Applications    appl   = new Applications(formsRepo);
                def_FormResults frmRes = appl.CreateFormResultPopulatedFromUAS(SessionHelper.LoginStatus.EnterpriseID, SessionHelper.LoginStatus.GroupID, userId, frm.formId, ItemsToPopulateFromUAS);
                appl.PopulateItemsFromPrevApplication(frmRes, ItemIdentifiersToPopulateFromPrevApplication);

                frmRes.statusChangeDate = DateTime.Now;

                // Save the FormResult, ItemResults, and ResponseVariables
                int newFormResultId = 0;
                try
                {
                    newFormResultId = formsRepo.AddFormResult(frmRes);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("AddFormResult exception:" + ex.Message);
                }

                Debug.WriteLine("AddFormResult newFormResultId:" + newFormResultId.ToString());

                // query the ramsell system and update the formResult responses based on Ramsell response
                def_ResponseVariables rvMemberId = formsRepo.GetResponseVariablesByFormResultIdentifier(newFormResultId, "ADAP_D9_Ramsell");
                if (rvMemberId != null && !String.IsNullOrWhiteSpace(rvMemberId.rspValue))
                {
                    string memberId = rvMemberId.rspValue;
                    string usrId    = UAS.Business.UAS_Business_Functions.GetEntAppConfigAdap("USR");
                    string password = UAS.Business.UAS_Business_Functions.GetEntAppConfigAdap("PWD");
                    Debug.WriteLine("Ramsell UseriD / Password: "******" / " + password);

                    string token = Ramsell.GetOauthToken(usrId, password);
                    new RamsellImport(formsRepo, frmRes.formResultId).ImportApplication(token, memberId);
                }
                //AJBoggs.Adap.Services.Api.Ramsell.PopulateItemsFromRamsellImport(formsRepo, frmRes);

                if (SessionHelper.SessionForm == null)
                {
                    SessionHelper.SessionForm = new SessionForm();
                }

                SessionForm sf = SessionHelper.SessionForm;
                sf.formId         = frm.formId;
                sf.formIdentifier = frm.identifier;
                sf.sectionId      = formsRepo.GetSectionByIdentifier("ADAP_demographic").sectionId;
                sf.partId         = formsRepo.GetPartByFormAndIdentifier(frm, "ADAP").partId;

                // *** RRB - should be deprecated - use SessionForm
                // *** BR - line 359 of the ResultsController calls this session variable, so it must be set to prevent an exception.
                //  Other parts of the application may still use that variable, so changing it in the ResultsController may break something else.
                Session["part"] = sf.partId;
                // Should have the partId also - may not be required.

                sf.formResultId = newFormResultId;

                return(RedirectToAction("Template", "Results", new { sectionId = sf.sectionId.ToString() }));
            }
            else
            {
                return(RedirectToAction("AdapPortal", "COADAP", new { userId = userId, error = "Not Approved" }));
            }
        }
Example #21
0
        public static void updateSection3ScoresNoSave(
            IFormsRepository formsRepo,
            def_Forms frm,
            int formResultId)
        {
            if (frm.identifier == "SIS-C")
            {
                return;
            }

            string       sectionIdentifier = "SIS-A 3";
            def_Sections sct = formsRepo.GetSectionByIdentifier(sectionIdentifier);

            if (sct == null)
            {
                throw new Exception("Could not find section with identifier \"" + sectionIdentifier + "\"");
            }
            int rawTotal = 0;

            foreach (def_SectionItems si in sct.def_SectionItems)
            {
                if (si.subSectionId != null)        // skip the Subsections
                {
                    continue;
                }
                def_Items itm = formsRepo.GetItemById(si.itemId);
                // def_ItemResults itmResults = itm.def_ItemResults.SingleOrDefault(ir => ir.formResultId == formResultId);
                def_ItemResults itmResults = formsRepo.GetItemResultByFormResItem(formResultId, itm.itemId);
                if (itmResults == null)
                {
                    continue;
                }
                formsRepo.GetItemResultsResponseVariables(itmResults);
                foreach (def_ResponseVariables rv in itmResults.def_ResponseVariables)
                {
                    rv.def_ItemVariables = formsRepo.GetItemVariableById(rv.itemVariableId);
                }
                for (int i = 0; i < 3; i++)
                {
                    string suffix   = SupportNeedsColumnSuffixes[i];
                    string rspValue = null;

                    def_ResponseVariables rv = itmResults.def_ResponseVariables.SingleOrDefault(trv => trv.def_ItemVariables.identifier.EndsWith(suffix));
                    if (rv != null)
                    {
                        rspValue = rv.rspValue;
                    }

                    if (!String.IsNullOrWhiteSpace(rspValue))
                    {
                        int rawScore;
                        if (Int32.TryParse(rv.rspValue, out rawScore))
                        {
                            rawTotal += rawScore;
                        }
                        else
                        {
                            Debug.WriteLine("* * * Skipping item on updating section 1 scores: " +
                                            "Could not parse integer from response value \"{0}\" for itemVariable \"{1}\". (formResultID {2})",
                                            rv.rspValue, rv.def_ItemVariables.identifier, formResultId);
                        }
                    }
                }
            }

            UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_3_raw_total", rawTotal);
        }
Example #22
0
        public ActionResult ShowEligibility()
        {
            if (!SessionHelper.IsUserLoggedIn)
            {
                return(RedirectToAction("Index", "Account", null));
            }

            if (SessionHelper.SessionForm == null)
            {
                SessionHelper.SessionForm = new SessionForm();
            }

            // retrieve and set SessionForm params
            string     formIdent = "CA-ADAP-DASHBOARD", entName = "California";
            def_Forms  frm = formsRepo.GetFormByIdentifier(formIdent);
            Enterprise ent = new AuthenticationClient().GetEnterpriseByName(entName);

            if (frm == null)
            {
                return(Content("Could not find form with identifier \"" + formIdent + "\""));
            }

            if (ent == null)
            {
                return(Content("Could not find enterprise with name \"" + entName + "\""));
            }

            //  Get the FormResult to get the subject of the current Application
            def_FormResults fr = formsRepo.GetFormResultById(SessionHelper.SessionForm.formResultId);

            if (fr == null)
            {
                return(Content("Could not find the current Application  \"" + SessionHelper.SessionForm.formResultId.ToString() + "\""));
            }

            // Get the Eligibility Form for the subject
            IEnumerable <def_FormResults> frElgList = formsRepo.GetFormResultsByFormSubject(frm.formId, fr.subject);
            def_FormResults frElg = null;

            if ((frElgList == null) || frElgList.Count <def_FormResults>() == 0)
            {
                mLogger.Debug("Couldn't find a current FormResult for Eligibility.  Create one.");
                frElg = new def_FormResults()
                {
                    formId               = frm.formId,
                    formStatus           = 0,
                    sessionStatus        = 0,
                    dateUpdated          = DateTime.Now,
                    deleted              = false,
                    locked               = false,
                    archived             = false,
                    EnterpriseID         = ent.EnterpriseID,
                    GroupID              = fr.GroupID, // User the same Enrollment Center
                    subject              = fr.subject,
                    interviewer          = fr.interviewer,
                    assigned             = fr.assigned,
                    training             = false,
                    reviewStatus         = 0,
                    statusChangeDate     = DateTime.Now,
                    LastModifiedByUserId = fr.LastModifiedByUserId
                };

                AuthenticationClient authClient = new AuthenticationClient();
                var groupIds = authClient.GetGroupsInUserPermissions(SessionHelper.LoginStatus.EnterpriseID, SessionHelper.LoginStatus.UserID).Select(x => x.GroupID);
                var groupId  = groupIds.FirstOrDefault();

                Dictionary <string, string> uasItemDictionary = new Dictionary <string, string>();
                var uasData = authClient.GetUser(fr.subject.Value);

                var adapId = authClient.GetExistingAdapIdentifier(uasData.UserID, uasData.EnterpriseID);

                // ADAP ID
                if (!String.IsNullOrWhiteSpace(adapId))
                {
                    uasItemDictionary.Add("C1_MemberIdentifier_item", adapId);
                }

                Applications appl = new Applications(formsRepo);

                //Populate from UAS
                //Populate items where Source = UAS in json file
                frElg = appl.CreateFormResultPopulatedFromUAS(SessionHelper.LoginStatus.EnterpriseID, groupId, uasData.UserID, frm.formId, uasItemDictionary);

                int newFrmRsltId = formsRepo.AddFormResult(frElg);
                mLogger.Debug("New Eligibility FormResult created: {0}", newFrmRsltId);
            }
            else
            {
                frElg = frElgList.First <def_FormResults>();
            }


            SessionHelper.SessionForm.formId         = frElg.formId;
            SessionHelper.SessionForm.formResultId   = frElg.formResultId;
            SessionHelper.SessionForm.formIdentifier = formIdent;
            // SessionHelper.LoginStatus.EnterpriseID = ent.EnterpriseID;


            def_Parts prt = formsRepo.GetFormParts(frm)[0];

            SessionHelper.SessionForm.partId = prt.partId;
            Session["part"] = prt.partId.ToString();
            def_Sections sct = formsRepo.GetSectionsInPart(prt)[1];

            Session["section"] = sct.sectionId.ToString();

            return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = SessionHelper.SessionForm.partId.ToString() }));
        }
Example #23
0
        public void CreateElgibility(int formResultId)
        {
            string     formIdent = "CA-ADAP-DASHBOARD", entName = "California";
            def_Forms  frm = formsRepo.GetFormByIdentifier(formIdent);
            Enterprise ent = new AuthenticationClient().GetEnterpriseByName(entName);

            //  Get the FormResult to get the subject of the current Application
            def_FormResults fr = formsRepo.GetFormResultById(formResultId);

            // Get the Eligibility Form for the subject
            IEnumerable <def_FormResults> frElgList = formsRepo.GetFormResultsByFormSubject(frm.formId, fr.subject);
            def_FormResults frmRes = null;

            if ((frElgList == null) || frElgList.Count <def_FormResults>() == 0)
            {
                mLogger.Debug("Couldn't find a current FormResult for Eligibility.  Create one.");
                frmRes = new def_FormResults()
                {
                    formId               = frm.formId,
                    formStatus           = 0,
                    sessionStatus        = 0,
                    dateUpdated          = DateTime.Now,
                    deleted              = false,
                    locked               = false,
                    archived             = false,
                    EnterpriseID         = ent.EnterpriseID,
                    GroupID              = fr.GroupID, // User the same Enrollment Center
                    subject              = fr.subject,
                    interviewer          = fr.interviewer,
                    assigned             = fr.assigned,
                    training             = false,
                    reviewStatus         = 0,
                    statusChangeDate     = DateTime.Now,
                    LastModifiedByUserId = fr.LastModifiedByUserId
                };

                int newFrmRsltId = formsRepo.AddFormResult(frmRes);
                mLogger.Debug("New Eligibility FormResult created: {0}", newFrmRsltId);
            }
            else
            {
                frmRes = frElgList.First <def_FormResults>();
            }

            // make sure item responses exist for the form
            Dictionary <string, string> DataToPopulate = new Dictionary <string, string>();
            var sectionItems = formsRepo.GetSectionItemsBySectionId(756);

            AuthenticationClient authClient = new AuthenticationClient();
            var uasData = authClient.GetUser(fr.subject.Value);
            var adapId  = authClient.GetADAPIdentifier(uasData.UserID, uasData.EnterpriseID);

            foreach (var item in sectionItems)
            {
                var defItem = formsRepo.GetItemById(item.itemId);

                if (defItem.identifier == "C1_MemberIdentifier_item")
                {
                    DataToPopulate.Add(defItem.identifier, adapId);
                }
                else if (defItem.identifier == "C1_MemberFirstName_item")
                {
                    def_ResponseVariables firstName = formsRepo.GetResponseVariablesBySubjectForm(fr.subject.Value, 15, "C1_MemberFirstName");
                    DataToPopulate.Add(defItem.identifier, firstName != null ? firstName.rspValue : string.Empty);
                }
                else if (defItem.identifier == "C1_MemberLastName_item")
                {
                    def_ResponseVariables lastName = formsRepo.GetResponseVariablesBySubjectForm(fr.subject.Value, 15, "C1_MemberLastName");
                    DataToPopulate.Add(defItem.identifier, lastName != null ? lastName.rspValue : string.Empty);
                }
                else if (defItem.identifier == "C1_MemberDateOfBirth_item")
                {
                    def_ResponseVariables dob = formsRepo.GetResponseVariablesBySubjectForm(fr.subject.Value, 15, "C1_MemberDateOfBirth");
                    DataToPopulate.Add(defItem.identifier, dob != null ? dob.rspValue : string.Empty);
                }
                else
                {
                    DataToPopulate.Add(defItem.identifier, string.Empty);
                }
            }

            foreach (String s in DataToPopulate.Keys)
            {
                def_Items       item = formsRepo.GetItemByIdentifier(s);
                def_ItemResults ir   = new def_ItemResults()
                {
                    itemId        = item.itemId,
                    sessionStatus = 0,
                    dateUpdated   = DateTime.Now
                };

                // check if the key already exist
                var itemResult = formsRepo.GetItemResultByFormResItem(frmRes.formResultId, item.itemId);
                if (itemResult == null)
                {
                    frmRes.def_ItemResults.Add(ir);

                    foreach (var iv in formsRepo.GetItemVariablesByItemId(item.itemId))
                    {
                        // Note for General forms like ADAP there should only be 1 ItemVariable per Item
                        def_ResponseVariables rv = new def_ResponseVariables();
                        rv.itemVariableId = iv.itemVariableId;
                        // rv.rspDate = DateTime.Now;    // RRB 11/11/15 The date, fp, and int fields are for the native data conversion.
                        rv.rspValue = DataToPopulate[s];

                        formsRepo.ConvertValueToNativeType(iv, rv);
                        ir.def_ResponseVariables.Add(rv);
                    }
                }
                else
                {
                    ir = itemResult;
                }
            }

            formsRepo.Save();
        }
Example #24
0
        public static int UpdateSisScoresNoSave(
            IFormsRepository formsRepo,
            def_Forms frm,
            int formResultId,
            SubscaleCatagory[] subscales,
            Func <int, double, SubscaleCatagory, double> GetSubscaleStandardScore,
            Func <int, double, SubscaleCatagory, double> GetSubscalePercentile)
        {
            DateTime startTime = DateTime.Now;

            updateSection1ScoresNoSave(formsRepo, frm, formResultId);
            if (frm.identifier == "SIS-A")
            {
                updateSection3ScoresNoSave(formsRepo, frm, formResultId);
            }

            double standardScoreTotal = 0, totalRating = 0;
            int    totalRawScoreTotal = 0;
            int    standardScoreCount = 0;

            foreach (SubscaleCatagory cat in subscales)
            {
                def_Sections sct = GetSectionForSubscaleCatagory(frm, cat);
                formsRepo.SortSectionItems(sct);

                int totalRawScore = 0, countRawScore = 0;


                foreach (def_SectionItems si in sct.def_SectionItems)
                {
                    if (si.subSectionId != null)        // skip the Subsections
                    {
                        continue;
                    }
                    def_Items itm = formsRepo.GetItemById(si.itemId);
                    // def_ItemResults itmResults = itm.def_ItemResults.SingleOrDefault(ir => ir.formResultId == formResultId);
                    def_ItemResults itmResults = formsRepo.GetItemResultByFormResItem(formResultId, itm.itemId);
                    if (itmResults == null)
                    {
                        continue;
                    }
                    formsRepo.GetItemResultsResponseVariables(itmResults);
                    foreach (def_ResponseVariables rv in itmResults.def_ResponseVariables)
                    {
                        rv.def_ItemVariables = formsRepo.GetItemVariableById(rv.itemVariableId);
                    }
                    for (int i = 0; i < 3; i++)
                    {
                        string suffix   = SupportNeedsColumnSuffixes[i];
                        string rspValue = null;

                        def_ResponseVariables rv = itmResults.def_ResponseVariables.SingleOrDefault(trv => trv.def_ItemVariables.identifier.EndsWith(suffix));
                        if (rv != null)
                        {
                            rspValue = rv.rspValue;
                        }

                        if (!String.IsNullOrWhiteSpace(rspValue))
                        {
                            int rspInt;
                            if (Int32.TryParse(rspValue, out rspInt))
                            {
                                totalRawScore += rspInt;
                                countRawScore++;
                            }
                            else
                            {
                                Debug.WriteLine("* * * Skipping item on updating scores: " +
                                                "Could not parse integer from response value \"{0}\" for itemVariable \"{1}\". (formResultID {2})",
                                                rv.rspValue, rv.def_ItemVariables.identifier, formResultId);
                                Debug.Print("could not parse integer from response value \"" + rspValue + "\"");
                            }
                        }
                    }
                }

                double rawScoreAvg   = Math.Round((double)totalRawScore / countRawScore, 2);
                double standardScore = GetSubscaleStandardScore(totalRawScore, rawScoreAvg, cat); //totalRawScore / 5;
                double percentile    = GetSubscalePercentile(totalRawScore, rawScoreAvg, cat);    //totalRawScore;

                //save subscale scores to database
                string sctNumberLetter = sct.title.Substring(0, sct.title.IndexOf('.'));
                UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_" + sctNumberLetter + "_raw", totalRawScore);
                UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_" + sctNumberLetter + "_std", standardScore);
                UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_" + sctNumberLetter + "_avg", rawScoreAvg);
                UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_" + sctNumberLetter + "_pct", percentile);

                standardScoreTotal += standardScore;
                totalRawScoreTotal += totalRawScore;
                totalRating        += rawScoreAvg;
                standardScoreCount++;
            }

            //save overall scores to database
            //int compositeIndex = GetSupportNeedsIndex((int)standardScoreTotal);//19;
            //int compositePercentile = GetSupportNeedsPercentile((int)standardScoreTotal);
            UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_total_rawscores_all_SIS_sections", totalRawScoreTotal);
            UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_standard_score_total", standardScoreTotal);
            //saveResponse(formsRepo, formResultId, "scr_support_needs_index", compositeIndex);
            //saveResponse(formsRepo, formResultId, "scr_sni_percentile_rank", compositePercentile);
            UpdateScoreResponseNoSave(formsRepo, formResultId, "scr_total_rating", totalRating);

            TimeSpan duration = DateTime.Now - startTime;

            Debug.WriteLine("* * *  SharedScoring:UpdateSisScores COMPLETED IN " + duration.ToString());
            return((int)standardScoreTotal);
        }
Example #25
0
        /// <summary>
        /// Step through meta-data heirarchy and retrieve a list of identifiers for all required def_ItemVariables
        ///
        /// Also include the partId and sectionId for each def_ItemVariable identifier returned.
        /// </summary>
        /// <param name="frm"></param>
        /// <returns></returns>
        private static List <ItemVariableIdentifierWithPartSection> ComputeRequiredItemVarsWithPartsSections(IFormsRepository formsRepo, def_Forms frm, int enterpriseId)
        {
            List <ItemVariableIdentifierWithPartSection> result = new List <ItemVariableIdentifierWithPartSection>();
            List <def_FormParts> formParts = formsRepo.GetFormPartsByFormId(frm.formId);

            foreach (def_FormParts fp in formParts)
            {
                var part = formsRepo.GetPartById(fp.partId);
                formsRepo.GetPartSections(part); //Loads part sections into part def_PartSections property
                def_Sections firstSection = null;

                foreach (def_PartSections ps in part.def_PartSections)
                {
                    var  partSectionsEnt = formsRepo.GetPartSectionsEnt(ps);
                    bool skip            = false;
                    foreach (def_PartSectionsEnt pse in partSectionsEnt)
                    {
                        if (pse.EnterpriseID == SessionHelper.LoginStatus.EnterpriseID && !pse.visible)
                        {
                            skip = true;
                            continue;
                        }
                    }

                    if (skip)
                    {
                        continue;
                    }
                    List <def_SectionItems> allSectionItems = new List <def_SectionItems>();

                    var section = formsRepo.GetSectionById(ps.sectionId);
                    firstSection = section;
                    formsRepo.SortSectionItems(section); //This loads section items into section.def_SectionItems

                    foreach (def_SectionItems si in section.def_SectionItems)
                    {
                        var sectionItemsEnt = formsRepo.GetSectionItemsEnt(si);
                        // if no items are found, ICollection.Any() will return false, .All() will return true.
                        if (si.display == false && !sectionItemsEnt.Any(sie => sie.EnterpriseID == enterpriseId && sie.validation == 1))
                        {
                            continue;
                        }
                        if (si.subSectionId.HasValue)
                        {
                            def_Sections sub = formsRepo.GetSubSectionById(si.subSectionId.Value);
                            formsRepo.SortSectionItems(sub); //This loads section items into sub.def_SectionItems
                            foreach (def_SectionItems ssi in sub.def_SectionItems)
                            {
                                allSectionItems.Add(ssi);
                            }
                        }
                        else
                        {
                            allSectionItems.Add(si);
                        }
                    }

                    foreach (def_SectionItems si in allSectionItems)
                    {
                        si.def_SectionItemsEnt = formsRepo.GetSectionItemsEnt(si);
                        si.def_Items           = formsRepo.GetItemById(si.itemId);
                        if (si.display == false && !si.def_SectionItemsEnt.Any(sie => sie.EnterpriseID == enterpriseId && sie.validation == 1))
                        {
                            Debug.WriteLine("* * *  SharedValidation:DoGenericValidation method  * * * Validation: skipping section item with display=false (itm label = " + si.def_Items.label + ")");
                            continue;
                        }

                        if (!si.requiredForm)
                        {
                            // if no items are found, ICollection.Any() will return false, .All() will return true.
                            if (!si.def_SectionItemsEnt.Any(r => r.EnterpriseID == enterpriseId && r.requiredForm))
                            {
                                Debug.WriteLine("* * *  SharedValidation:DoGenericValidation method  * * * Validation: skipping section item with requiredform=false (itm label = " + si.def_Items.label + ")");
                                continue;
                            }
                        }

                        // if no items are found, ICollection.Any() will return false, .All() will return true.
                        if (si.def_SectionItemsEnt.Any(sie => sie.EnterpriseID == enterpriseId && sie.validation == 0))
                        {
                            Debug.WriteLine("* * *  SharedValidation:DoGenericValidation method  * * * Validation: skipping section item where Enterprise specific validation is 0 (itm label = " + si.def_Items.label + ")");
                            continue;
                        }

                        var item = formsRepo.GetItemById(si.itemId);
                        formsRepo.GetItemVariables(item);
                        foreach (def_ItemVariables iv in item.def_ItemVariables)
                        {
                            result.Add(
                                new ItemVariableIdentifierWithPartSection
                            {
                                partId    = ps.partId,
                                sectionId = ps.sectionId,
                                itemVariableIdentifier = iv.identifier
                            }
                                );
                        }
                    }
                }
            }

            return(result);
        }
Example #26
0
        public static List <ItemVariableIdentifierWithPartSection> GetRequiredItemVarsWithPartsSections(IFormsRepository formsRepo, def_Forms frm, int enterpriseId)
        {
            //if not in venture mode, get the required item vars as normal (without touching uas_EntApConfig)
            if (!SessionHelper.IsVentureMode)
            {
                return(ComputeRequiredItemVarsWithPartsSections(formsRepo, frm, enterpriseId));
            }

            string configEnumCode = "Required_ItemVariables_FormId_" + frm.formId;

            //attempt to query a pre-computed list of item variabel identifiers from the local Venture DB
            uas_EntAppConfig eac = null;

            using (DbConnection connection = UasAdo.GetUasAdoConnection())
            {
                connection.Open();
                eac = UasAdo.GetEntAppConfig(connection, configEnumCode, enterpriseId);
            }

            //if no pre-computed list was found, create it now and insert it into the local Venture DB so it can be quickly retrieved next time
            if (eac == null || String.IsNullOrWhiteSpace(eac.ConfigValue))
            {
                List <ItemVariableIdentifierWithPartSection> requiredIvs = ComputeRequiredItemVarsWithPartsSections(formsRepo, frm, enterpriseId);
                string configValueString = String.Empty;
                foreach (ItemVariableIdentifierWithPartSection ivps in requiredIvs)
                {
                    configValueString += ivps.partId + "," + ivps.sectionId + "," + ivps.itemVariableIdentifier + ";";
                }

                using (DbConnection connection = UasAdo.GetUasAdoConnection())
                {
                    connection.Open();
                    UasAdo.AddEntAppConfig(connection, new uas_EntAppConfig()
                    {
                        EnterpriseID  = enterpriseId,
                        ApplicationID = UAS.Business.Constants.APPLICATIONID,
                        EnumCode      = configEnumCode,
                        baseTypeId    = 14,
                        ConfigName    = "Required ItemVariable Identifiers for Form " + frm.identifier,
                        ConfigValue   = configValueString,
                        CreatedDate   = DateTime.Now,
                        CreatedBy     = 1,
                        StatusFlag    = "A"
                    });
                }
                return(requiredIvs);
            }

            //if a pre-computed list was found in the local Venture DB, parse identifiers, partIds, sectionIds from the configValue
            List <ItemVariableIdentifierWithPartSection> result = new List <ItemVariableIdentifierWithPartSection>();

            string[] chunks = eac.ConfigValue.Split(';');
            foreach (string chunk in chunks)
            {
                if (String.IsNullOrWhiteSpace(chunk))
                {
                    continue;
                }
                try
                {
                    string[] subChunks = chunk.Split(',');
                    result.Add(new ItemVariableIdentifierWithPartSection
                    {
                        partId    = Convert.ToInt32(subChunks[0]),
                        sectionId = Convert.ToInt32(subChunks[1]),
                        itemVariableIdentifier = subChunks[2]
                    });
                }
                catch (Exception e)
                {
                    throw new Exception("Error converting string \"" + chunk + "\" into ItemVariableIdentifierWithPartSection", e);
                }
            }

            return(result);
        }
        public ActionResult GoAction(FormCollection formCollection)
        {
            string      recId             = formCollection["recId"];
            string      paramFormResultId = formCollection["sisId"];
            string      paramFormId       = formCollection["formId"];
            string      category          = formCollection["CategoryID"];
            SearchModel model             = new SearchModel();

            if (SessionHelper.SessionForm == null)
            {
                // return RedirectToAction("Index", "Search", null);
                SessionHelper.SessionForm = new SessionForm();
            }
            SessionForm sf = SessionHelper.SessionForm;

            if (String.IsNullOrWhiteSpace(category))
            {
                return(RedirectToAction("Index", "Search"));
            }
            else if (category.ToLower().Equals("edit") && model.edit)
            {
                // retrieve and set SessionForm params
                sf.formId       = Convert.ToInt32(paramFormId);
                sf.formResultId = Convert.ToInt32(paramFormResultId);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);

                if (!formResult.locked || (formResult.locked && model.editLocked))
                {
                    // get the sectionId of the first section of the first part based on the formId
                    def_Forms frm = formsRepo.GetFormById(sf.formId);
                    def_Parts prt = formsRepo.GetFormParts(frm)[0];
                    sf.partId       = prt.partId;
                    Session["part"] = prt.partId;
                    def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, sf.formResultId, (int)AccessLogging.accessLogFunctions.EDIT, "Initiate editing of assessment.");
                    }
                    return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
                }
            }
            else if (category.ToLower().Equals("review"))
            {
                // retrieve and set SessionForm params
                sf.formId       = Convert.ToInt32(paramFormId);
                sf.formResultId = Convert.ToInt32(paramFormResultId);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);

                if (model.editLocked)
                {
                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, sf.formResultId, (int)AccessLogging.accessLogFunctions.REVIEW, "Assessment accessed for review.");
                    }

                    if (model.unlock == true)
                    {
                        formsRepo.LockFormResult(formResult.formResultId);
                    }

                    if (formResult.reviewStatus != (int)ReviewStatus.REVIEWED && formResult.reviewStatus != (int)ReviewStatus.APPROVED && formResult.reviewStatus != (int)ReviewStatus.PRE_QA)
                    {
                        def_FormResults preQAcopy = AssessmentCopy.CopyAssessment(formsRepo, formResult.formResultId);

                        if (WebServiceActivity.IsWebServiceEnabled())
                        {
                            WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.REVIEW, "formResultId=" + preQAcopy.formResultId.ToString());
                        }
                    }

                    ReviewStatus.ChangeStatus(formsRepo, formResult, ReviewStatus.REVIEWED, "Initiate review of assessment");

                    // get the sectionId of the first section of the first part based on the formId
                    def_Forms frm = formsRepo.GetFormById(sf.formId);
                    def_Parts prt = formsRepo.GetFormParts(frm)[0];
                    sf.partId       = prt.partId;
                    Session["part"] = prt.partId;
                    def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];


                    return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
                }
            }
            else if (category.ToLower().Equals("approve"))
            {
                // retrieve and set SessionForm params
                sf.formId       = Convert.ToInt32(paramFormId);
                sf.formResultId = Convert.ToInt32(paramFormResultId);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);

                if (model.editLocked)
                {
                    ReviewStatus.ChangeStatus(formsRepo, formResult, ReviewStatus.APPROVED, "Approve review of assessment");

                    if (WebServiceActivity.IsWebServiceEnabled())
                    {
                        WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.APPROVE, "formResultId=" + formResult.formResultId.ToString());
                    }
                }
            }
            else if (category.ToLower().Equals("create"))
            {
                if (model.create == true)
                {
                    string          formId = String.IsNullOrEmpty(paramFormId) ? "1" : paramFormId;
                    def_FormResults frmRes = FormResults.CreateNewFormResultFull(formId,
                                                                                 SessionHelper.LoginStatus.EnterpriseID.ToString(),
                                                                                 SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].GroupID.ToString(),
                                                                                 recId,
                                                                                 SessionHelper.LoginStatus.UserID.ToString()
                                                                                 );
                    string strFormResultId = String.Empty;
                    try
                    {
                        int formRsltId = formsRepo.AddFormResult(frmRes);
                        strFormResultId = formRsltId.ToString();
                        Debug.WriteLine("GoAction create FormResultId strFormResultId:" + strFormResultId);
                    }
                    catch (Exception excptn)
                    {
                        Debug.WriteLine("GoAction Defws.CreateNewFormResultFull formsRepo.AddFormResult  exception:" + excptn.Message);
                        Debug.WriteLine("   GoAction formId:" + formId
                                        + "   entId: " + SessionHelper.LoginStatus.EnterpriseID.ToString()
                                        + "   GroupId: " + SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].GroupID.ToString()
                                        + "   recId: " + recId.ToString()
                                        + "   UserId: " + SessionHelper.LoginStatus.UserID.ToString()
                                        );
                    }

                    if ((!String.IsNullOrEmpty(strFormResultId)) && !String.IsNullOrEmpty(recId))
                    {
                        int intRecId;

                        if (int.TryParse(recId, out intRecId))
                        {
                            using (var context = DataContext.getSisDbContext())
                            {
                                // Contact tempContact = new Contact();
                                Contact tempContact = (from c in context.Contacts
                                                       where c.ContactID == intRecId
                                                       select c).FirstOrDefault();

                                // Address tempAddress = new Address();
                                Address tempAddress = (from a in context.Addresses
                                                       where (a.ContactID == tempContact.ContactID) &&
                                                       (a.AddressType == "R")
                                                       select a).FirstOrDefault();

                                Dictionary <string, string> responsesByIdentifier = new Dictionary <string, string>();
                                responsesByIdentifier.Add("sis_cl_first_nm", tempContact.FirstName);
                                responsesByIdentifier.Add("sis_cl_last_nm", tempContact.LastName);

                                if (tempAddress != null)
                                {
                                    responsesByIdentifier.Add("sis_cl_addr_line1", tempAddress.Address1);
                                    responsesByIdentifier.Add("sis_cl_city", tempAddress.City);
                                    responsesByIdentifier.Add("sis_cl_st", tempAddress.StateCode);
                                    responsesByIdentifier.Add("sis_cl_zip", tempAddress.Zip);
                                }

                                string msg = formsRepo.CreateNewResponseValues(strFormResultId, responsesByIdentifier);
                                Debug.WriteLine("GoAction CreateNewResponseValues strFormResultId: " + strFormResultId + "    msg: " + msg);
                            }
                        }

                        // Retrieve and set SessionForm params
                        sf.formId       = 1; // Temporary
                        sf.formResultId = Convert.ToInt32(strFormResultId);

                        // Get the sectionId of the first section of the first part based on the formId
                        def_Forms frm = formsRepo.GetFormById(sf.formId);
                        def_Parts prt = formsRepo.GetFormParts(frm)[0];
                        sf.partId       = prt.partId;
                        Session["part"] = prt.partId;
                        def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

                        return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
                    }
                }
            }
            else if (category.ToLower().Equals("delete"))
            {
                if (model.delete == true)
                {
                    formsRepo.FormResultDeleteLogically(Convert.ToInt32(paramFormResultId));

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, Convert.ToInt32(paramFormResultId), (int)AccessLogging.accessLogFunctions.DELETE, "Delete assessment.");
                    }


                    if (ventureMode == false && WebServiceActivity.IsWebServiceEnabled())
                    {
                        WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.DELETE, "formResultId=" + paramFormResultId);
                        def_FormResults preQAcopy = ReviewStatus.GetLatestPreQACopy(formsRepo, Convert.ToInt32(paramFormResultId));

                        if (preQAcopy != null)
                        {
                            formsRepo.FormResultDeleteLogically(preQAcopy.formResultId);
                            WebServiceActivity.CallWebService(formsRepo, (int)WebServiceActivity.webServiceActivityFunctions.DELETE, "formResultId=" + preQAcopy.formResultId.ToString());
                        }
                    }
                }
            }
            else if (category.ToLower().Equals("lock"))
            {
                if (model.unlock == true)
                {
                    formsRepo.LockFormResult(Convert.ToInt32(paramFormResultId));
                }
            }
            else if (category.ToLower().Equals("unlock"))
            {
                if (model.unlock == true)
                {
                    formsRepo.UnlockFormResult(Convert.ToInt32(paramFormResultId));
                }
            }
            else if (category.ToLower().Equals("archive"))
            {
                if (model.archive == true)
                {
                    formsRepo.ArchiveFormResult(Convert.ToInt32(paramFormResultId));

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, Convert.ToInt32(paramFormResultId), (int)AccessLogging.accessLogFunctions.ARCHIVE, "Archive assessment.");
                    }
                }
            }
            else if (category.ToLower().Equals("unarchive"))
            {
                if (model.archive == true)
                {
                    formsRepo.UnarchiveFormResult(Convert.ToInt32(paramFormResultId));

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, Convert.ToInt32(paramFormResultId), (int)AccessLogging.accessLogFunctions.UNARCHIVE, "Unarchive assessment.");
                    }
                }
            }
            else if (category.ToLower().Equals("upload"))
            {
                def_FormResults fr = formsRepo.GetFormResultById(Convert.ToInt32(paramFormResultId));

                if (fr.formStatus == (byte)FormResults_formStatus.COMPLETED)
                {
                    SessionHelper.Write("uploadFormResultId", Convert.ToInt32(paramFormResultId));
                    return(RedirectToAction("UploadSingle", "DataSync"));
                }
            }
            else if (category.ToLower().Equals("undelete"))
            {
                if (model.undelete == true)
                {
                    formsRepo.FormResultUndelete(Convert.ToInt32(paramFormResultId));

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, Convert.ToInt32(paramFormResultId), (int)AccessLogging.accessLogFunctions.UNDELETE, "Undelete assessment.");
                    }
                }
            }
            else if (category.ToLower().Equals("planning") && model.edit)
            {
                // retrieve and set SessionForm params
                sf.formId       = Convert.ToInt32(paramFormId);
                sf.formResultId = Convert.ToInt32(paramFormResultId);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);

                if (!formResult.locked || (formResult.locked && model.editLocked))
                {
                    // get the sectionId of the first section of the first part based on the formId
                    def_Forms frm = formsRepo.GetFormById(sf.formId);
                    def_Parts prt = formsRepo.GetPartByFormAndIdentifier(frm, "Other");
                    sf.partId       = prt.partId;
                    Session["part"] = prt.partId;
                    def_Sections sct = formsRepo.GetSectionsInPart(prt)[0];

                    if (ventureMode == false)
                    {
                        AccessLogging.InsertAccessLogRecord(formsRepo, sf.formResultId, (int)AccessLogging.accessLogFunctions.EDIT, "Initiate editing of interview planning.");
                    }
                    return(RedirectToAction("Template", "Results", new { sectionId = sct.sectionId.ToString(), partId = sf.partId.ToString() }));
                }
            }

            return(RedirectToAction("Index", "Search"));
        }
Example #28
0
        /// <summary>
        /// Used by ResultsController.ValidateFormResult()
        ///
        /// Runs the hard-coded validation rules, which can't be encoded into meta-data, for SIS-A and SIS-C forms.
        ///
        /// adds to the model's validation messages for any validation errors or warnings.
        /// </summary>
        /// <param name="sv"></param>
        /// <param name="model"></param>
        /// <returns>true if any validation ERRORS where found, false if nothin (or only wanrings) found</returns>
        public static bool RunOneOffValidation(IFormsRepository formsRepo, def_Forms frm, int entId, List <ValuePair> allResponses, TemplateItems model)
        {
            bool invalid          = false;
            bool isSisCAssessment = frm.identifier.Equals("SIS-C");

            #region if any section 1 "other" text fields are populated, make sure they have a positive numerical response. (and vice-versa)
            string itemsToCheck = isSisCAssessment ?
                                  "A19,A20,A21,B14,B15,B16" // <- check these section 1 items if SIS-C
                : "A19,B13";                                // <- check these if SIS-A
            foreach (string shortIdentifier in itemsToCheck.Split(','))
            {
                string textIdentifier;
                string numIdentifier;

                if (isSisCAssessment)
                {
                    textIdentifier = "SIS-C_Q1" + shortIdentifier + "_Other";
                    numIdentifier  = "SIS-C_Q1" + shortIdentifier + "_Ex" + (shortIdentifier.StartsWith("A") ? "Med" : "Beh") + "Support";
                }
                else // Assumes that if it isn't SIS-C,it must be a SIS-A assessment
                {
                    textIdentifier = "Q1" + shortIdentifier + "_Other";
                    numIdentifier  = "Q1" + shortIdentifier + "_Ex" + (shortIdentifier.StartsWith("A") ? "Med" : "Beh") + "Support";
                }

                ValuePair textVp = allResponses.SingleOrDefault(vpt => vpt.identifier == textIdentifier); //formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, textIdentifier);
                ValuePair numVp  = allResponses.SingleOrDefault(vpt => vpt.identifier == numIdentifier);  //def_ResponseVariables numRv = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, numIdentifier);

                bool textBlank = textVp == null || String.IsNullOrWhiteSpace(textVp.rspValue);            //isNullEmptyOrBlank(textRv);
                bool numBlank  = numVp == null || String.IsNullOrWhiteSpace(numVp.rspValue);              //isNullEmptyOrBlank(numRv);

                if (numBlank)
                {
                    invalid = true;
                    model.validationMessages.Add("Section 1: \"other\" item " + shortIdentifier + " has no numerical response");
                }
                else if ((Int32.Parse(numVp.rspValue) > 0) && textBlank)
                {
                    invalid = true;
                    model.validationMessages.Add("Section 1: \"other\" item " + shortIdentifier + " has positive numerical response, but no text explaination");
                }
            }
            #endregion

            #region check interviewee age / interview date
            ValuePair vpBirthDate = allResponses.SingleOrDefault(vpt => vpt.identifier == "sis_cl_dob_dt");
            ValuePair vpIntDate   = allResponses.SingleOrDefault(vpt => vpt.identifier == "sis_completed_dt");
            DateTime  dtDob;
            DateTime  dtInt;
            //def_ResponseVariables rvBirthDate = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "sis_cl_dob_dt");
            //def_ResponseVariables rvIntDate = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "sis_completed_dt");
            if (vpBirthDate != null && DateTime.TryParse(vpBirthDate.rspValue, out dtDob) &&
                vpIntDate != null && DateTime.TryParse(vpIntDate.rspValue, out dtInt))
            {
                int age = dtInt.Year - dtDob.Year;
                if (dtInt.Month < dtDob.Month)
                {
                    age--;
                }
                if ((dtInt.Month == dtDob.Month) && (dtInt.Day < dtDob.Day))
                {
                    age--;
                }

                //for SIS-C assessments, age must fall between 5 and 16 inclusive, and interview date must be 2009 at earliest
                if (isSisCAssessment)
                {
                    if (age < 5)
                    {
                        invalid = true;
                        model.validationMessages.Add("Profile: interviewee age is " + age + " years, should be at least 5 years");
                    }
                    if (age > 16)
                    {
                        invalid = true;
                        model.validationMessages.Add("Profile: interviewee age is " + age + " years, should be at most 16 years");
                    }
                    if (dtInt.Year < 2009)
                    {
                        invalid = true;
                        model.validationMessages.Add("Profile: interview date is in the year " + dtInt.Year + ", should be 2009 at the earliest");
                    }
                }

                //for SIS-A assessments, age must be at least 15, and interview date must be 2004 at earliest
                else
                {
                    if (dtInt.Year < 2004)
                    {
                        invalid = true;
                        model.validationMessages.Add("Profile: interview date is in the year " + dtInt.Year + ", should be 2004 at the earliest");
                    }
                    if (age < 15)
                    {
                        invalid = true;
                        model.validationMessages.Add("Profile: interviewee age is " + age + " years, should be at least 15 years");
                    }
                }
            }
            #endregion

            #region if "SEVERE MEDICAL RISK" under supplementl questions is marked "yes"...

            ValuePair vpSup = allResponses.SingleOrDefault(vpt => vpt.identifier == "Q4A1v1");
            //def_ResponseVariables rvSup = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "Q4A1v1");
            if (vpSup != null && vpSup.rspValue != null && (vpSup.rspValue.Equals("1") || vpSup.rspValue.ToLower().Equals("true")))
            {
                int rspInt;

                //make sure at least one of the items under section 1A has a rsponse value "2"
                bool      anyTwosInOtherItems = false;
                ValuePair vp;

                for (int i = 1; i <= 21; i++)
                {
                    if (isSisCAssessment) // Accomodating for different identifiers (SIS-A vs SIS-C)
                    {
                        vp = allResponses.SingleOrDefault(vpt => vpt.identifier == "SIS-C_Q1A" + i + "_ExMedSupport");
                    }
                    else
                    {
                        vp = allResponses.SingleOrDefault(vpt => vpt.identifier == "Q1A" + i + "_ExMedSupport");
                    }
                    //def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "Q1A" + i + "_ExMedSupport");
                    if ((vp != null) && Int32.TryParse(vp.rspValue, out rspInt) && (rspInt == 2))
                    {
                        anyTwosInOtherItems = true;
                        break;
                    }
                }

                ValuePair vpExMedSup = allResponses.SingleOrDefault(vpt => vpt.identifier == "Q1A_ed_ExMedSupport");
                //def_ResponseVariables edRv = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "Q1A_ed_ExMedSupport");

                if ((vpExMedSup != null) && Int32.TryParse(vpExMedSup.rspValue, out rspInt) && (rspInt == 2))
                {
                    anyTwosInOtherItems = true;
                }

                if (!anyTwosInOtherItems)
                {
                    invalid = true;
                    model.validationMessages.Add("Marked \"yes\" under SEVERE MEDICAL RISK in supplemental questions, but no scores of 2 in section 1A");
                }
            }
            #endregion

            #region Custom validation for supplemental questions 2-4, depending on section 1B responses
            Dictionary <string, string[]> specs;
            if (isSisCAssessment)
            {
                specs = new Dictionary <string, string[]>
                {
                    { "Q4A2v1", new string[] {
                          //if Q4A2v1 has response "yes", at least one
                          //of these item variables must have response "2"
                          "SIS-C_Q1B2", //question 2 in SIS-C
                          "SIS-C_Q1B3", //question 3 in SIS-C
                          "SIS-C_Q1B8", //question 8 in SIS-C
                      } },
                    { "Q4A3v1", new string[] {
                          "SIS-C_Q1B2", //question 2 in SIS-C
                          "SIS-C_Q1B3", //question 3 in SIS-C
                          "SIS-C_Q1B8", //question 8 in SIS-C
                      } },
                    { "Q4A4v1", new string[] {
                          "SIS-C_Q1B5", //question 5 in SIS-C
                          "SIS-C_Q1B6", //question 6 in SIS-C
                          "SIS-C_Q1B7", //question 7 in SIS-C
                      } },
                };
            }
            else
            {
                specs = new Dictionary <string, string[]>
                {
                    { "Q4A2v1", new string[] {
                          //if Q4A2v1 has response "yes", at least one
                          //of these item variables must have response "2"
                          "Q1B2", //question 2 in SIS-C
                          "Q1B3", //question 3 in SIS-C
                          "Q1B9", //question 8 in SIS-C
                      } },
                    { "Q4A3v1", new string[] {
                          "Q1B2", //question 2 in SIS-C
                          "Q1B3", //question 3 in SIS-C
                          "Q1B9", //question 8 in SIS-C
                      } },
                    { "Q4A4v1", new string[] {
                          "Q1B5", //question 5 in SIS-C
                          "Q1B6", //question 6 in SIS-C
                          "Q1B7", //question 7 in SIS-C
                      } },
                };
            }
            foreach (string supIvIdent in specs.Keys)
            {
                def_ItemVariables supIv = formsRepo.GetItemVariableByIdentifier(supIvIdent);
                if (supIv == null)
                {
                    throw new Exception("Could not find item variable with identifier \"" + supIvIdent + "\"");
                }
                def_Items supItm   = formsRepo.GetItemById(supIv.itemId);
                string    supIndex = supIvIdent.Substring(3, 1);

                //rvSup = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, supIv.itemVariableId);
                vpSup = allResponses.SingleOrDefault(vpt => vpt.identifier == supIv.identifier);

                if (vpSup != null && vpSup.rspValue != null && (vpSup.rspValue.Equals("1") || vpSup.rspValue.ToLower().Equals("true")))
                {
                    List <string> checkedItemLabels   = new List <string>();
                    bool          anyTwosInOtherItems = false;
                    foreach (string ivPrefix in specs[supIvIdent])
                    {
                        def_ItemVariables iv  = formsRepo.GetItemVariableByIdentifier(ivPrefix + "_ExBehSupport");
                        def_Items         itm = formsRepo.GetItemById(iv.itemId);
                        checkedItemLabels.Add("\"" + itm.label + "\"");

                        ValuePair vp = allResponses.SingleOrDefault(vpt => vpt.identifier == iv.identifier);
                        //def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, iv.itemVariableId);
                        if ((vp != null) && (vp.rspValue != null) && (vp.rspValue == "2"))
                        {
                            anyTwosInOtherItems = true;
                            break;
                        }
                    }

                    if (!anyTwosInOtherItems)
                    {
                        invalid = true;
                        model.validationMessages.Add("Marked \"yes\" under supplemental question " + supIndex + ", but no scores of 2 in any of these section 1B items: "
                                                     + String.Join(", ", checkedItemLabels));
                    }
                }
            }
            #endregion

            #region Require notes for Section 1A or 1B where the item is flagged as Important For/To
            foreach (def_FormParts fp in frm.def_FormParts)
            {
                //This is currently hardcodoed for Enterprise 44: Virginia.  This should probably be added to a lookup Table so the feature can be switched on/off for any enterprise.
                //if (fr.EnterpriseID == 44)
                //{
                if (fp.def_Parts.identifier.StartsWith("Section 1"))
                {
                    foreach (def_PartSections ps in fp.def_Parts.def_PartSections)
                    {
                        foreach (def_SectionItems si in ps.def_Sections.def_SectionItems)
                        {
                            // Configured in def_SectionItemsEnt, some Enterprises require validation on these sections.  Currently checks for a 1 for Enterprise 44.
                            // Empty lists should return false.
                            if (si.def_SectionItemsEnt.Any(r => r.validation == 1 && r.EnterpriseID == entId) && si.subSectionId != null)
                            {
                                foreach (def_SectionItems subsi in si.def_SubSections.def_Sections.def_SectionItems)
                                {
                                    List <def_ItemVariables> ivImportant = subsi.def_Items.def_ItemVariables.Where(iv => iv.identifier.EndsWith("_ImportantFor") || iv.identifier.EndsWith("_ImportantTo")).ToList();
                                    if (ivImportant.Count() == 0)
                                    {
                                        Debug.WriteLine("ResultsController:ValidateFormResult method  * * * Could not find Important For/To itemVariable for item \"" + subsi.def_Items.identifier + "\"");
                                    }
                                    else
                                    {
                                        List <bool> rvImpBools = new List <bool>();
                                        foreach (def_ItemVariables iv in ivImportant)
                                        {
                                            ValuePair vp = allResponses.SingleOrDefault(vpt => vpt.identifier == iv.identifier);
                                            //def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, iv.itemVariableId);
                                            rvImpBools.Add((vp != null && vp.rspValue != null && vp.rspValue.Equals("1")));
                                        }
                                        // Test true if any value is true.  Empty lists should return false.
                                        if (rvImpBools.Any(r => r))
                                        {
                                            List <def_ItemVariables> ivNote = subsi.def_Items.def_ItemVariables.Where(iv => iv.identifier.EndsWith("_Notes")).ToList();
                                            foreach (def_ItemVariables iv in ivNote)
                                            {
                                                ValuePair vp = allResponses.SingleOrDefault(vpt => vpt.identifier == iv.identifier);
                                                //def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, iv.itemVariableId);
                                                if (vp == null || String.IsNullOrEmpty(vp.rspValue))
                                                {
                                                    invalid = true;
                                                    model.validationMessages.Add(subsi.def_Sections.title + ", " + subsi.def_Items.label +
                                                                                 ": Notes are required for items flagged as Important.");
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //}
            }
            #endregion

            #region For all supplemental questions, require sub-questions if top-level response is "Yes" (Bug 13132, #2 in description)

            //iterate through all the sub-sections in the Supplemental Questions section
            def_Sections sqSection = formsRepo.GetSectionByIdentifier("SQ");
            formsRepo.SortSectionItems(sqSection);
            foreach (def_SectionItems si in sqSection.def_SectionItems.Where(si => si.subSectionId != null))
            {
                bool         validationRequired = false;
                def_Sections subSct             = formsRepo.GetSubSectionById(si.subSectionId);

                //exclude "S4aPageNotes" subsection
                if (subSct.identifier == "S4aPageNotes")
                {
                    continue;
                }

                //iterate through all the sectionitems in this subsection, in order
                formsRepo.SortSectionItems(subSct);
                foreach (def_SectionItems subSi in subSct.def_SectionItems)
                {
                    //if the sectionitem points to an item, that item must represent a top-level yes.no Supplemental Question
                    //and it should have exactly one itemVariable, with basetype 1
                    if (subSi.itemId > 1)
                    {
                        def_ItemVariables ivTopQuestion = subSi.def_Items.def_ItemVariables.FirstOrDefault();

                        ValuePair vpTopQuestion = allResponses.SingleOrDefault(vpt => vpt.identifier == ivTopQuestion.identifier);
                        //def_ResponseVariables rvTopQuestion = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, ivTopQuestion.itemVariableId);

                        //check if the response is "yes" for this top-level yes/no
                        if (vpTopQuestion != null && !String.IsNullOrWhiteSpace(vpTopQuestion.rspValue) && vpTopQuestion.rspValue == "1")
                        {
                            validationRequired = true;
                        }
                    }

                    //if the sectionitem points to a sub-subsection, that sub-subsection contains lower-level items
                    //that should be checked only if the previous top-level question was answered "yes"
                    else if (subSi.subSectionId.HasValue && validationRequired)
                    {
                        def_Sections subSubSct = formsRepo.GetSubSectionById(subSi.subSectionId);

                        //iterate through the item variables in this sub-subsection and require responses for some of them,
                        //if their identifier ends with a, b, c, d, or d2
                        formsRepo.SortSectionItems(subSubSct);
                        foreach (def_SectionItems subSubSi in subSubSct.def_SectionItems.Where(subSubSi => subSubSi.subSectionId == null))
                        {
                            foreach (def_ItemVariables bottomLevelIv in subSubSi.def_Items.def_ItemVariables)
                            {
                                if ("a,b,c,d,d2".Split(',').Where(suffix => bottomLevelIv.identifier.EndsWith(suffix)).Any())
                                {
                                    ValuePair vp = allResponses.SingleOrDefault(vpt => vpt.identifier == bottomLevelIv.identifier);
                                    //def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, bottomLevelIv.itemVariableId);
                                    if (vp == null || String.IsNullOrWhiteSpace(vp.rspValue) ||
                                        (bottomLevelIv.baseTypeId == 1 && vp.rspValue.ToLower() == "unanswered"))
                                    //^ ^ ^ OT 3-24-16 consider "unanswered" the same as blank for yes/nos ("unanswered" responses may exist in DB as a result of a bug: Bug 13132, #1 in description)
                                    {
                                        invalid = true;
                                        model.validationMessages.Add(sqSection.title + ": since you marked \"yes\" under \"" + subSct.title + "\", you must provide a response for \"" + subSubSi.def_Items.label + "\"");
                                    }
                                }
                            }
                        }

                        //reset the flag so the following subsection is not validated unless we hit another top-level "yes"
                        validationRequired = false;
                    }
                }
            }

            #endregion

            return(invalid);
        }
Example #29
0
        /// <summary>
        /// Gets data from the def_FormResults record for a form result
        /// </summary>
        /// <param name="formResult">The form result to get data from</param>
        /// <param name="form">The form result's form</param>
        /// <returns>ValuePairs containing identifier = label for a form result entry, value = the form result entry (string)</returns>
        public static List <ValuePair> GetFormResultValues(def_FormResults formResult, def_Forms form)
        {
            List <ValuePair> values = new List <ValuePair>();

            //number
            ValuePair valuePair = new ValuePair(FormResultExportTagName.recipientId.ToString(), formResult.subject.ToString());

            values.Add(valuePair);

            //number
            valuePair = new ValuePair(FormResultExportTagName.formResultId.ToString(), formResult.formResultId.ToString());
            values.Add(valuePair);

            //^ SisId in csv second row

            //text
            valuePair = new ValuePair(FormResultExportTagName.identifier.ToString(), form.identifier);
            values.Add(valuePair);

            //add formId (number)
            valuePair = new ValuePair(FormResultExportTagName.formId.ToString(), form.formId.ToString());
            values.Add(valuePair);

            //number
            valuePair = new ValuePair(FormResultExportTagName.group.ToString(), formResult.GroupID.ToString());
            values.Add(valuePair);

            //number
            valuePair = new ValuePair(FormResultExportTagName.enterprise.ToString(), formResult.EnterpriseID.ToString());
            values.Add(valuePair);

            ////number
            //valuePair = new ValuePair(interviewerId, formResult.interviewer.ToString());
            //values.Add(valuePair);

            //number
            valuePair = new ValuePair(FormResultExportTagName.assigned.ToString(), formResult.assigned.ToString());
            values.Add(valuePair);

            //number
            valuePair = new ValuePair(FormResultExportTagName.statusId.ToString(), formResult.formStatus.ToString());
            values.Add(valuePair);

            //text
            valuePair = new ValuePair(FormResultExportTagName.dateUpdated.ToString(), formResult.dateUpdated.ToString());
            values.Add(valuePair);

            //text
            valuePair = new ValuePair(FormResultExportTagName.statusChangeDate.ToString(), formResult.statusChangeDate.ToString());
            values.Add(valuePair);

            valuePair = new ValuePair(FormResultExportTagName.deleted.ToString(), formResult.deleted.ToString());
            values.Add(valuePair);

            valuePair = new ValuePair(FormResultExportTagName.locked.ToString(), formResult.locked.ToString());
            values.Add(valuePair);

            valuePair = new ValuePair(FormResultExportTagName.archived.ToString(), formResult.archived.ToString());
            values.Add(valuePair);

            //number
            valuePair = new ValuePair(FormResultExportTagName.reviewStatus.ToString(), formResult.reviewStatus.ToString());
            values.Add(valuePair);

            //number
            valuePair = new ValuePair(FormResultExportTagName.lastModifiedByUserId.ToString(), formResult.LastModifiedByUserId.ToString());
            values.Add(valuePair);

            //pull info that comes from other def tables
            using (formsEntities def = DataContext.GetDbContext())
            {
                try
                {
                    int    statusMasterId   = def.def_StatusMaster.Where(sm => sm.formId == 1 && sm.ApplicationId == 1).Select(sm => sm.statusMasterId).First();
                    int    statusDetailId   = def.def_StatusDetail.Where(sd => sd.statusMasterId == statusMasterId && sd.sortOrder == formResult.reviewStatus).Select(sd => sd.statusDetailId).First();
                    string reviewStatusText = def.def_StatusText.Where(st => st.statusDetailId == statusDetailId).Select(st => st.displayText).First();
                    valuePair = new ValuePair(FormResultExportTagName.reviewStatusText.ToString(), reviewStatusText);
                    values.Add(valuePair);
                }
                catch (Exception e) { Debug.WriteLine(e); }

                try
                {
                    valuePair = new ValuePair(FormResultExportTagName.statusText.ToString(),
                                              ((WebService.WSConstants.FR_formStatus)(formResult.formStatus)).ToString());
                    values.Add(valuePair);
                }
                catch (Exception e) { Debug.WriteLine(e); }
            }

            //pull info that comes from uas tables
            using (UASEntities uas = DataContext.getUasDbContext())
            {
                try
                {
                    valuePair = new ValuePair(FormResultExportTagName.groupName.ToString(),
                                              uas.uas_Group
                                              .Where(g => g.GroupID == formResult.GroupID)
                                              .Select(g => g.GroupName).First());
                    values.Add(valuePair);
                }
                catch (Exception e) { Debug.WriteLine(e); }

                try
                {
                    valuePair = new ValuePair(FormResultExportTagName.assignedLoginId.ToString(),
                                              uas.uas_User
                                              .Where(u => u.UserID == formResult.assigned)
                                              .Select(u => u.LoginID).First());
                    values.Add(valuePair);
                }
                catch (Exception e) { Debug.WriteLine(e); }

                try
                {
                    valuePair = new ValuePair(FormResultExportTagName.lastModifiedByLoginId.ToString(),
                                              uas.uas_User
                                              .Where(u => u.UserID == formResult.LastModifiedByUserId)
                                              .Select(u => u.LoginID).First());
                    values.Add(valuePair);
                }
                catch (Exception e) { Debug.WriteLine(e); }

                try
                {
                    valuePair = new ValuePair(FormResultExportTagName.enterpriseName.ToString(),
                                              uas.uas_Enterprise
                                              .Where(e => e.EnterpriseID == formResult.EnterpriseID)
                                              .Select(e => e.EnterpriseName).First());
                    values.Add(valuePair);
                }
                catch (Exception e) { Debug.WriteLine(e); }
            }

            return(values);
        }
Example #30
0
        public FileStreamResult ExportFormJSON()
        {
            //use session variables to pick a FormResults object from the database
            string formId = Request["formId"] as string;

            Debug.WriteLine("* * *  GetFormResultsJSON formId: " + formId);

            int iFormId = Convert.ToInt32(formId);

            formsEntities db = DataContext.GetDbContext();

            db.Configuration.LazyLoadingEnabled = false;

            // def_Forms form = db.def_Forms
            //     .Include(fr => fr.def_FormParts
            //         .Select(fp => fp.def_Parts)
            //         .Select(pa => pa.def_PartSections
            //             .Select(p => p.def_Sections)
            //             .Select(s => s.def_SectionItems
            //             .Select(si => si.def_SubSections))))
            //     .Include(fr => fr.def_FormParts
            //         .Select(fp => fp.def_Parts)
            //         .Select(pa => pa.def_PartSections
            //             .Select(p => p.def_Sections)
            //             .Select(s => s.def_SectionItems
            //                 .Select(si => si.def_Items)
            //                 .Select(i => i.def_ItemVariables))))
            //     .Single(f => f.formId == iFormId);



            def_Forms            form      = db.def_Forms.Where(f => f.formId == iFormId).FirstOrDefault();
            List <def_FormParts> formParts = db.def_FormParts.Where(fp => fp.formId == iFormId).ToList();
            List <int>           partIds   = formParts.Select(fp => fp.partId).ToList();
            List <def_Parts>     parts     = db.def_Parts.Where(p => partIds.Contains(p.partId)).ToList();

            partIds = parts.Select(p => p.partId).ToList();
            List <def_PartSections> partSections = db.def_PartSections.Where(ps => partIds.Contains(ps.partId)).ToList();
            List <int>          sectionIds       = partSections.Select(ps => ps.sectionId).ToList();
            List <def_Sections> sections         = db.def_Sections.Where(s => sectionIds.Contains(s.sectionId)).ToList();

            List <def_SectionItems>  sectionItems  = new List <def_SectionItems>();
            List <def_SubSections>   subSections   = new List <def_SubSections>();
            List <def_Items>         items         = new List <def_Items>();
            List <def_ItemVariables> itemVariables = new List <def_ItemVariables>();

            foreach (def_Sections section in sections)
            {
                GetSectionItemsAndSubSectionsRecursive(section.sectionId, sectionItems, subSections);
            }

            foreach (def_SectionItems si in sectionItems)
            {
                if (si.subSectionId == null)
                {
                    def_Items item = db.def_Items.Where(i => i.itemId == si.itemId).FirstOrDefault();

                    items.Add(item);

                    List <def_ItemVariables> newItemVariables = db.def_ItemVariables.Where(iv => iv.itemId == item.itemId).ToList();

                    itemVariables.AddRange(newItemVariables);
                }
            }


            string jsonString = "{\"data\":[" + fastJSON.JSON.ToJSON(form);

            jsonString += "," + fastJSON.JSON.ToJSON(formParts);
            jsonString += "," + fastJSON.JSON.ToJSON(parts);
            jsonString += "," + fastJSON.JSON.ToJSON(partSections);
            jsonString += "," + fastJSON.JSON.ToJSON(sections);
            jsonString += "," + fastJSON.JSON.ToJSON(sectionItems);
            jsonString += "," + fastJSON.JSON.ToJSON(subSections);
            jsonString += "," + fastJSON.JSON.ToJSON(items);
            jsonString += "," + fastJSON.JSON.ToJSON(itemVariables);
            jsonString += "]}";

            MemoryStream stream = new MemoryStream();

            //write json string to file, then stream it out
            //DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(FormResultJSON));

            StreamWriter streamWriter = new StreamWriter(stream);

            streamWriter.Write(jsonString);
            //streamWriter.Close();
            //stream.Close();

            FileStreamResult fsr = null;

            streamWriter.Flush();
            stream.Position = 0;

            try
            {
                fsr = new FileStreamResult(stream, "application/json")
                {
                    FileDownloadName = form.identifier + " " + DateTime.Now + ".json"
                };
            }
            catch (Exception exp)
            {
                Debug.WriteLine("File write exception: " + exp.Message);
                string errMsg = "File write exception: " + exp.Message;
                return(ProcessError(errMsg));
            }


            return(fsr);
        }