private void tryPrintSingleLineLabel(def_Sections sct, int indentLevel, double sectionLabelIndent, double itemLabelIndent, double responseIndent)
        {
            Dictionary <string, string> responses        = GetResponsesByItemVariableIdentifier(sct);
            List <string> positiveResponsesItemVariables = responses.Where(pair => pair.Value.Equals("Yes")).Select(pair => pair.Key).ToList();

            //if there is exactly one response for this section, print it on the same line as the section header
            if (positiveResponsesItemVariables.Count == 1)
            {
                string            ivIdent = positiveResponsesItemVariables.First();
                def_ItemVariables iv      = formsRepo.GetItemVariableByIdentifier(ivIdent);
                def_Items         itm     = formsRepo.GetItemById(iv.itemId);
                string            label   = itm.label;
                double            drawY   = output.drawY;
                printGenericSectionHeader(sct, sectionLabelIndent);
                output.drawY = drawY;
                output.appendWrappedText(label, responseIndent, 8 - responseIndent);
                output.drawY -= .1;
            }

            //otherewise, delegate to the standard section printing
            else
            {
                base.PrintGenericSection(output, sct, indentLevel, responses);
            }
        }
Пример #2
0
        private string GetSupplementalResponseText(def_ItemVariables iv, def_ResponseVariables rv)
        {
            string responseText;

            if (rv == null)
            {
                responseText = "";
            }
            else
            {
                responseText = rv.rspValue;
                if (iv.baseTypeId == 1)
                {
                    if (responseText.Equals("1") || responseText.ToLower().Equals("true"))
                    {
                        return("yes");
                    }
                    if (responseText.Equals("0") || responseText.ToLower().Equals("false"))
                    {
                        return("no");
                    }
                }
            }
            return(responseText);
        }
        public bool SaveFileUploads(int formResultId, HttpRequestBase httpRequest)
        {
            //for debugging runtime
            //DateTime startTime = DateTime.Now;
            Debug.WriteLine("***  SaveFileUploads formResultId: " + formResultId.ToString());

            // This section handles files uploaded as part of an HTML file upload
            if ((httpRequest != null) && (httpRequest.Files != null))
            {
                foreach (string key in httpRequest.Files.AllKeys)
                {
                    def_ItemVariables iv = formsRepo.GetItemVariableByIdentifier(key);
                    if (iv != null)
                    {
                        HttpPostedFileWrapper upload = (HttpPostedFileWrapper)httpRequest.Files[iv.identifier];
                        if (upload.ContentLength > 0)
                        {
                            // RRB 11/10/15 moved to Business layer
                            // val = formsRepo.SaveUpload(upload, iv.identifier, SessionHelper.SessionForm.formResultId);
                            string rspVal = Assmnts.Business.Uploads.FileUploads.SaveUpload(
                                upload.InputStream, Path.GetFileName(upload.FileName), iv.identifier, formResultId);

                            def_ItemResults ir = SaveItemResult(formResultId, iv.itemId);
                            SaveResponseVariable(ir, iv, rspVal);
                        }
                    }
                }

                // All responses are now in Entity Framework, so Save all the Entities to the Forms Repository
                formsRepo.Save();
            }

            return(true);
        }
        protected string GetResponse(int formResultId, def_Items itm, def_ItemVariables iv)
        {
            def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(formResultId, iv.itemVariableId);
            string response          = (rv == null) ? String.Empty : rv.rspValue;

            // special case for drop-downs/radiolists with options in meta-data
            if ((itm != null) && (iv.baseTypeId == 8) && !String.IsNullOrWhiteSpace(itm.prompt) && itm.prompt.Contains(";"))
            {
                try {
                    return(itm.prompt.Split(';')[Convert.ToInt16(response) - 1]);
                }
                catch (Exception e) {
                    Debug.WriteLine(" *** FormResultPdfReport.cs failed to retrieve selected option for ItemVariable "
                                    + iv.itemVariableId + ", response string \"" + response + "\"");
                }
            }

            //special case for YES/NO items
            else if ((response != null) && (iv.baseTypeId == 1))
            {
                if (response.Equals("1"))
                {
                    return("Yes");
                }

                if (response.Equals("0"))
                {
                    return("No");
                }
            }

            return(response);
        }
        protected void buildTableWithItems(PdfOutput output, def_Parts part, int nColumns, string[] headers, params string[] identifiers)
        {
            int nRows = identifiers.Length / nColumns;

            string[][] vals = new string[nRows][];
            for (int row = 0; row < nRows; row++)
            {
                vals[row] = new string[nColumns];
                for (int col = 0; col < nColumns; col++)
                {
                    string    ident = identifiers[row * nColumns + col];
                    def_Items itm   = formsRepo.GetItemByIdentifier(/*formResults,*/ ident);                  //formsRepo.GetAllItems().First(t => t.identifier.Equals(ident));//getItemByIdentifier(part,ident);
                    if (itm == null)
                    {
                        throw new Exception("could not find item with identifer " + ident);
                    }
                    formsRepo.GetItemVariables(itm);
                    def_ItemVariables iv = itm.def_ItemVariables.FirstOrDefault();
                    if (iv == null)
                    {
                        throw new Exception("could not find any itemVariables for item with identifer " + ident);
                    }
                    def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(formResultId, iv.itemVariableId);                    //iv.def_ResponseVariables.FirstOrDefault();
                    vals[row][col] = ((rv == null) ? "" : rv.rspValue);
                }
            }
            output.appendSimpleTable(headers, vals);
        }
Пример #6
0
        private static string GetFormattedResponse(def_ResponseVariables rv, XmlSchemaSimpleType type, IFormsRepository formsRepo)
        {
            string response = rv.rspValue;

            //for boolean items (typically representing checked checkboxes), check if there is a specific output value in lookup tables
            //negative responses to boolean items (rspValue "0") can be ignored in this step because they will be excluded from the output anyways

            if (rv.rspValue == "1") //this if-statement reduces the number of DB reads, doesn't effect output
            {
                def_ItemVariables iv = formsRepo.GetItemVariableById(rv.itemVariableId);
                if (iv.baseTypeId == 1)
                {
                    def_LookupMaster lm = formsRepo.GetLookupMastersByLookupCode(iv.identifier);
                    if (lm != null)
                    {
                        List <def_LookupDetail> ld = formsRepo.GetLookupDetailsByLookupMasterEnterprise(lm.lookupMasterId, SessionHelper.LoginStatus.EnterpriseID);
                        if (ld.Count > 0)
                        {
                            response = ld[0].dataValue;
                        }
                    }
                }
            }

            try
            {
                return(Utilities.FormatDataByXmlDataType(response, type));
            }
            catch (Exception excptn)
            {
                Debug.WriteLine("GetFormattedResponse Message: " + excptn.Message);

                return(GetDefaultValue(type));  // to pass validation
            }
        }
        public string GetSisIdFromTrackingNumber(int formId, int trackingNumber)
        {
            List <int>        result     = new List <int>();
            def_ItemVariables ivTrackNum = formsRepo.GetItemVariableByIdentifier("sis_track_num");

            foreach (def_FormResults fr in formsRepo.GetFormResultsByFormId(formId).ToList())
            {
                def_ResponseVariables rvTrackNum = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, ivTrackNum.itemVariableId);
                if (rvTrackNum != null && rvTrackNum.rspInt.HasValue && rvTrackNum.rspInt.Value == trackingNumber)
                {
                    result.Add(fr.formResultId);
                }
            }

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < result.Count(); i++)
            {
                sb.Append(result[i]);
                if (i + 1 < result.Count())
                {
                    sb.Append(", ");
                }
            }
            return(sb.ToString());
        }
        private void printD5AndD6(def_Sections sct, int indentLevel, double sectionLabelIndent, double itemLabelIndent, double responseIndent)
        {
            Dictionary <string, string> responses = GetResponsesByItemVariableIdentifier(sct);

            List <string> yesLabels = new List <string>();

            foreach (string ivIdent in responses.Keys)
            {
                if (responses[ivIdent].Equals("Yes"))
                {
                    def_ItemVariables iv  = formsRepo.GetItemVariableByIdentifier(ivIdent);
                    def_Items         itm = formsRepo.GetItemById(iv.itemId);
                    yesLabels.Add(itm.label);
                }
            }
            if (yesLabels.Count > 0)
            {
                string rsp = yesLabels[0];
                for (int i = 1; i < yesLabels.Count; i++)
                {
                    rsp += ", " + yesLabels[i];
                }

                printGenericSectionHeader(sct, sectionLabelIndent);
                output.appendWrappedText(rsp, responseIndent, 8 - responseIndent);
                output.drawY -= .1;
            }
        }
        private void UpdateResponse(string itemVariableIdentifier, string response)
        {
            def_ItemVariables iv = formsRepo.GetItemVariableByIdentifier(itemVariableIdentifier);

            if (iv == null)
            {
                throw new Exception("Cannot find itemVariable with identifier \"" + itemVariableIdentifier + "\"");
            }
            def_ItemResults ir = userData.SaveItemResult(toFormResultId, iv.itemId);

            userData.SaveResponseVariable(ir, iv, response);
        }
Пример #10
0
        public static bool RunSingleSectionOneOffValidation(IFormsRepository formsRepo, FormCollection frmCllctn, int sectionId, out List <string> validationErrorMessages)
        {
            bool invalid = false;

            validationErrorMessages = new List <string>();
            def_Sections sct = formsRepo.GetSectionById(sectionId);

            #region Sections 2,3: if the Frequency is greater than zero, then the Duration and Type of support must be greater than zero.
            if ("SIS-A 2A,SIS-A 2B,SIS-A 2C,SIS-A 2D,SIS-A 2E,SIS-A 2F,SIS-A 3".Split(',').ToList().Contains(sct.identifier))
            {
                formsRepo.SortSectionItems(sct);
                foreach (def_SectionItems si in sct.def_SectionItems)
                {
                    if (si.subSectionId == null)
                    {
                        def_ItemVariables ivFreq = si.def_Items.def_ItemVariables.Where(iv => iv.identifier.EndsWith("_Fqy")).FirstOrDefault();
                        if (ivFreq == null)
                        {
                            throw new Exception("could not find fequency itemVariable (with suffix \"_Fqy\") for item \"" + si.def_Items.identifier + "\"");
                        }

                        string rspFreq = frmCllctn[ivFreq.identifier];
                        //def_ResponseVariables rvFreq = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, ivFreq.itemVariableId);

                        if (rspFreq != null && rspFreq.Trim().Length > 0 && Convert.ToInt16(rspFreq) > 0)
                        {
                            foreach (string suffix in new string[] { "_TOS", "_DST" })
                            {
                                def_ItemVariables ivSuff = si.def_Items.def_ItemVariables.Where(iv => iv.identifier.EndsWith(suffix)).FirstOrDefault();
                                if (ivSuff == null)
                                {
                                    throw new Exception("could not find itemVariable with suffix \"" + suffix + "\" for item \"" + si.def_Items.identifier + "\"");
                                }

                                string rspSuff = frmCllctn[ivSuff.identifier];
                                //def_ResponseVariables rvSuff = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, ivSuff.itemVariableId);
                                if (rspSuff == null || rspSuff.Trim().Length == 0 || Convert.ToInt16(rspSuff) == 0)
                                {
                                    invalid = true;
                                    validationErrorMessages.Add(si.def_Sections.title + ", " + si.def_Items.label +
                                                                ": you entered a Frequency greater than zero, so Daily Support Time and Type of Support must also be greater than zero.");
                                }
                            }
                        }
                    }
                }
            }

            #endregion

            return(invalid);
        }
        private void printD8(def_Sections sct, int indentLevel, double sectionLabelIndent, double itemLabelIndent, double responseIndent)
        {
            //append the "current gender" response in the same line as the section header
            double drawY = output.drawY;

            printGenericSectionHeader(sct, sectionLabelIndent);
            def_ItemVariables ivCurrGender  = formsRepo.GetItemVariableByIdentifier("ADAP_D8_CurrGenderDrop");
            string            rspCurrGender = GetResponseThroughLookupTables(formResultId, ivCurrGender.def_Items, ivCurrGender);

            if (!String.IsNullOrWhiteSpace(rspCurrGender))
            {
                output.drawY = drawY;
                output.appendWrappedText(rspCurrGender, responseIndent, 8 - responseIndent);
                output.drawY -= .1;
            }

            //if applicable, append the "gender at birth" label and response on one line
            def_Items         itmBirthGenderLabel = formsRepo.GetItemByIdentifier("ADAP_D8_BirthGenderLabel_item");
            def_ItemVariables ivBirthGender       = formsRepo.GetItemVariableByIdentifier("ADAP_D8_BirthGenderDrop");
            string            rspBirthGender      = GetResponseThroughLookupTables(formResultId, ivBirthGender.def_Items, ivBirthGender);

            if (!String.IsNullOrWhiteSpace(rspBirthGender))
            {
                double itemLabelHeight = itmBirthGenderLabel == null ? 0 :
                                         output.appendWrappedText(itmBirthGenderLabel.label, itemLabelIndent, responseIndent - itemLabelIndent, output.boldFont);
                double drawYBelowItemLabel = output.drawY;
                output.drawY += itemLabelHeight;
                output.appendWrappedText(rspBirthGender, responseIndent, 8 - responseIndent);
                output.drawY = Math.Min(drawYBelowItemLabel, output.drawY - .05);
            }

            //Dictionary<string, string> responses = GetResponsesByItemVariableIdentifierThroughLookupTables(sct);

            //foreach (string prefix in new string[] { "ADAP_D8_CurrGender", "ADAP_D8_BirthGender" })
            //{

            //    string ivIdent = prefix + "Drop";
            //    string labelItemIdent = prefix + "Label_item";

            //    def_Items labelItm = formsRepo.GetItemByIdentifier(labelItemIdent);
            //    string rsp = responses.ContainsKey( ivIdent ) ? responses[ivIdent] : "";

            //    //append item label (if applicable), without actually moving drawY down the page
            //    double itemLabelHeight =  labelItm == null ? 0 :
            //        output.appendWrappedText(labelItm.label, itemLabelIndent, responseIndent - itemLabelIndent, output.boldFont);
            //    double drawYBelowItemLabel = output.drawY;
            //    output.drawY += itemLabelHeight;
            //    output.appendWrappedText(rsp, responseIndent, 8 - responseIndent);
            //    output.drawY = Math.Min(drawYBelowItemLabel, output.drawY - .05);

            //}
        }
        /// <summary>
        /// Get the application data from Ramsell in their XML format.
        /// Nearly identical to the XML format that is sent to Ramsell
        /// </summary>
        /// <param name="oauthToken">Oauth 2 security token</param>
        /// <param name="fromMemberId">Ramsell MemberId</param>
        /// <returns></returns>
        public int ImportApplication(string oauthToken, string fromMemberId)
        {
            string decodedXml = Services.Api.Ramsell.GetApplicationXml(oauthToken, fromMemberId);

            if (String.IsNullOrWhiteSpace(decodedXml))
            {
                throw new Exception("received empty response from Ramsell for memberId \"" + fromMemberId + "\"");
            }

            // Process the XML returned from Ramsell
            List <string> checkedBoxes = new List <string>();
            Dictionary <string, string> specialCaseValuesByTagname = new Dictionary <string, string>();

            using (System.Xml.XmlReader reader = XmlReader.Create(new StringReader(decodedXml)))
            {
                //iterate through each element node in the file
                while (reader.Read())
                {
                    //tags "string" and "Patient" are boilerplate, they can be ignored (this doesn't skip their children)
                    if ((reader.NodeType != XmlNodeType.Element) || (reader.Name == "string") || (reader.Name == "Patient"))
                    {
                        continue;
                    }

                    //update DEF responses based on tagname + contents
                    ImportXmlNodeFromRamsell(reader, checkedBoxes, specialCaseValuesByTagname);
                }
            }

            //for any checkboxes that are included in the "ramsellIdentifierMap" in RamsellExport.cs,
            //uncheck the ones that weren't included in the xml
            List <string> checkboxIvIdentifiers = GetGroupedCheckboxItemVarIdentifiers();

            foreach (string checkboxIvIdent in checkboxIvIdentifiers)
            {
                if (checkedBoxes.Contains(checkboxIvIdent))
                {
                    continue;
                }
                def_ItemVariables checkBoxIv = formsRepo.GetItemVariableByIdentifier(checkboxIvIdent);
                def_ItemResults   ir         = userData.SaveItemResult(toFormResultId, checkBoxIv.itemId);
                userData.SaveResponseVariable(ir, checkBoxIv, "0");
            }

            //handle any special-case ramsell tags that require on-off transformations
            RamsellTransformations.ImportSpecialCasesNoSave(specialCaseValuesByTagname, toFormResultId, formsRepo);

            formsRepo.Save();

            return(0);
        }
Пример #13
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);
            }
        }
Пример #14
0
        public static void UpdateScoreResponseNoSave(IFormsRepository formsRepo, int formResultId, string itemVariableIdent, double response)
        {
            //if response exists already...
            def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultIdentifier(formResultId, itemVariableIdent);

            if (rv != null)
            {
                rv.rspValue = response.ToString();
            }

            //if not...
            def_ItemVariables iv = formsRepo.GetItemVariableByIdentifier(itemVariableIdent);

            if (iv == null)
            {
                throw new Exception("could not find itemVariable with identifier \"" + itemVariableIdent + "\"");
            }
            def_ItemResults ir = formsRepo.GetItemResultByFormResItem(formResultId, iv.itemId);

            if (ir == null)
            {
                ir = new def_ItemResults()
                {
                    itemId        = iv.itemId,
                    formResultId  = formResultId,
                    dateUpdated   = DateTime.Now,
                    sessionStatus = 0
                };
                formsRepo.AddItemResult(ir);
            }
            rv = ir.def_ResponseVariables.FirstOrDefault(trv => trv.itemVariableId == iv.itemVariableId);
            if (rv == null)
            {
                rv = new def_ResponseVariables()
                {
                    itemResultId   = ir.itemResultId,
                    itemVariableId = iv.itemVariableId,
                    rspValue       = response.ToString()
                };
                formsRepo.AddResponseVariable(rv);
            }
            else
            {
                rv.rspValue = response.ToString();
            }
        }
        private void SaveAssessmentFromDataTable(int formResultId, DataTable dt)
        {
            int prevItemId = -1;

            def_ItemResults itemResult = null;

            foreach (DataRow row in dt.Rows)
            {
                int    currItemId     = Int32.Parse(row["itemId"].ToString());
                int    itemVariableId = Int32.Parse(row["itemVariableId"].ToString());
                string rspValue       = row["rspValue"].ToString();

                if (currItemId != prevItemId)
                {
                    itemResult               = new def_ItemResults();
                    itemResult.dateUpdated   = DateTime.Now;
                    itemResult.itemId        = currItemId;
                    itemResult.sessionStatus = 0;
                    itemResult.formResultId  = formResultId;

                    formsRepo.AddItemResultNoSave(itemResult);
                }

                if (itemResult != null)
                {
                    def_ResponseVariables responseVariable = new def_ResponseVariables();
                    responseVariable.itemVariableId = itemVariableId;
                    responseVariable.rspValue       = rspValue;

                    def_ItemVariables itemVariable = formsRepo.GetItemVariableById(itemVariableId);

                    if (itemVariable != null)
                    {
                        formsRepo.ConvertValueToNativeType(itemVariable, responseVariable);

                        itemResult.def_ResponseVariables.Add(responseVariable);
                    }
                }
                prevItemId = currItemId;
            }

            formsRepo.Save();
        }
Пример #16
0
        private void InsertNewResponse(def_FormResults fr, string ivIdentifier, string response)
        {
            def_ItemVariables iv = formsRepo.GetItemVariableByIdentifier(ivIdentifier);

            def_ResponseVariables rv = new def_ResponseVariables()
            {
                itemVariableId = iv.itemVariableId,
                rspValue       = response
            };

            def_ItemResults ir = new def_ItemResults()
            {
                itemId                = iv.itemId,
                sessionStatus         = 0,
                dateUpdated           = DateTime.Now,
                def_ResponseVariables = { rv }
            };

            fr.def_ItemResults.Add(ir);
        }
        public def_ResponseVariables SaveResponseVariable(def_ItemResults ir, def_ItemVariables iv, string val)
        {
            // Add / Update the associated Response Variable in the database
            def_ResponseVariables rv = ir.def_ResponseVariables.Where(rrv => rrv.itemVariableId == iv.itemVariableId).FirstOrDefault();

            if (rv == null)
            {
                rv = new def_ResponseVariables()
                {
                    //itemResultId = ir.itemResultId,
                    itemVariableId = iv.itemVariableId,
                    rspValue       = val
                };

                try
                {
                    formsRepo.ConvertValueToNativeType(iv, rv);
                }
                catch (Exception xcptn)
                {
                    Debug.WriteLine(iv.identifier + " Exception: " + xcptn.Message);
                }

                ir.def_ResponseVariables.Add(rv);
            }
            else
            {
                rv.rspValue = val;
                try
                {
                    formsRepo.ConvertValueToNativeType(iv, rv);
                }
                catch (Exception xcptn)
                {
                    Debug.WriteLine(iv.identifier + " Exception: " + xcptn.Message);
                }
            }

            return(rv);
        }
        //ADAP_D7 (preferred language)
        private void printD7(def_Sections sct, int indentLevel, double sectionLabelIndent, double itemLabelIndent, double responseIndent)
        {
            //append the one response in the same line as the section header
            //if the user responded with "other", show the text they entered into the "other" textbox
            double drawY = output.drawY;

            printGenericSectionHeader(sct, sectionLabelIndent);
            def_ItemVariables iv  = formsRepo.GetItemVariableByIdentifier("ADAP_D7_LangDrop");
            string            rsp = GetResponseThroughLookupTables(formResultId, iv.def_Items, iv);

            if (rsp.StartsWith("Other"))
            {
                rsp = GetSingleResponse("ADAP_D7_LangOther");
            }

            if (!String.IsNullOrWhiteSpace(rsp))
            {
                output.drawY = drawY;
                output.appendWrappedText(rsp, responseIndent, 8 - responseIndent);
                output.drawY -= .1;
            }
        }
Пример #19
0
        /// <summary>
        /// called by RamsellImport
        /// </summary>
        /// <param name="specialCaseValuesByTagname"></param>
        /// <param name="toFormResultId"></param>
        /// <param name="formsRepo"></param>
        public static void ImportSpecialCasesNoSave(Dictionary <string, string> specialCaseValuesByTagname, int toFormResultId, IFormsRepository formsRepo)
        {
            UserData ud = new UserData(formsRepo);

            foreach (string ramsellTagName in specialCaseValuesByTagname.Keys)
            {
                Transformation matchingTrans = GetTransformationforRamsellTagName(ramsellTagName);
                if (matchingTrans == null)
                {
                    continue;
                }

                //prepare in/out vars for the transformation
                Dictionary <string, string> inRamsellValsByTag = new Dictionary <string, string>();
                foreach (string tag in matchingTrans.GetRamsellTagNames())
                {
                    inRamsellValsByTag.Add(tag, specialCaseValuesByTagname.ContainsKey(tag) ? specialCaseValuesByTagname[tag] : null);
                }

                //output is pre-populated with existing responses - though they are typically ignored by transformations
                Dictionary <string, string> outRspValsByItmVar = new Dictionary <string, string>();
                foreach (string ivIdentifier in matchingTrans.GetItemVariableIdentifiers())
                {
                    def_ResponseVariables existingRv = formsRepo.GetResponseVariablesByFormResultIdentifier(toFormResultId, ivIdentifier);
                    outRspValsByItmVar.Add(ivIdentifier, existingRv == null ? null : existingRv.rspValue);
                }

                //run transformation
                matchingTrans.GetImportValuesByItemVarIdentifier(inRamsellValsByTag, outRspValsByItmVar);

                //insert output values into DB
                foreach (string ivIdent in outRspValsByItmVar.Keys)
                {
                    def_ItemVariables iv = formsRepo.GetItemVariableByIdentifier(ivIdent);
                    def_ItemResults   ir = ud.SaveItemResult(toFormResultId, iv.itemId);
                    ud.SaveResponseVariable(ir, iv, outRspValsByItmVar[ivIdent]);
                }
            }
        }
Пример #20
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));
        }
        /// <summary>
        /// Process a single node from an XML improted from Ramsell, modifying the specified formResult as applicable.
        /// Noramlly this will only be called from within a loop to iterate over xml nodes, however this function will recurse to handle Ramsell's "income" structures
        /// </summary>
        /// <param name="fromReader">XmlReader where Read() has already been called</param>
        /// <param name="checkedBoxes">this should ba appended to with itemVariable identifiers for each checked checkbox. Used to uncheck excluded boxes at the end of the import</param>
        /// <param name="specialCaseValuesByTagname">this will be used to run special-case transformations that may involve multiple ramsell tags</param>
        private void ImportXmlNodeFromRamsell(
            XmlReader fromReader,
            List <string> checkedBoxes,
            Dictionary <string, string> specialCaseValuesByTagname)
        {
            if (fromReader.NodeType != XmlNodeType.Element)
            {
                throw new Exception("Expecting NodeType \"" + XmlNodeType.Element + "\", found \"" + fromReader.NodeType + "\"");
            }
            string ramellTagName = fromReader.Name;

            //the "Income_Item" tag is a one-off structure with multiple occurances
            if (ramellTagName == "Income_Item")
            {
                ImportIncomeStructureFromRamsell(fromReader);
                return;
            }

            //get the nodes contents
            string ramsellVal = String.Empty;

            if (!fromReader.IsEmptyElement)
            {
                fromReader.Read();
                if (fromReader.NodeType == XmlNodeType.EndElement)
                {
                    return;
                }
                if (fromReader.NodeType != XmlNodeType.Text)
                {
                    throw new Exception("Inside of node \"" + ramellTagName + "\", found NodeType \"" + fromReader.NodeType
                                        + "\", expecting NodeType \"" + XmlNodeType.Text + "\", or \"" + XmlNodeType.EndElement + "\"");
                }
                ramsellVal = fromReader.Value;
            }


            //based on tagName, check if this a simple case (no transformation necessary)
            List <string> ivIdentifiers = RamsellExport.GetItemVariableIdentifiersForRamsellTagName(ramellTagName);

            if (ivIdentifiers.Count == 1)
            {
                //one-to-one case: this ramsell tagName corresponds with exactly one itemVariable
                //so just save the text contents as a response to that itemVariable

                // RRB 4/18/16 Ramsell seems to be sending a default date of 1900-01-01
                //              This should be tested more.  If doesn't fix, maybe our date converter is causing an empty DOB to be this date.
                if (ramellTagName.Equals("DOB") && (string.IsNullOrEmpty(ramsellVal) || ramsellVal.StartsWith("1900")))
                {
                    ;
                }
                else
                {
                    UpdateResponse(ivIdentifiers[0], ramsellVal);
                }
            }
            else if (ivIdentifiers.Count > 1)
            {
                //checkbox case: this ramsell tagName corresponds to a set of itemVariables (representing checkboxes in the application)
                //so pick the checkbox based on this node's text contents, and save the response "1" for that checkbox
                #region checkbox case

                //based on lookups, pick the inidividual itemvariable (matchIv) that matches the node contents (ramsellVal)
                def_ItemVariables matchIv = null;
                foreach (string ivIdent in ivIdentifiers)
                {
                    def_ItemVariables iv = formsRepo.GetItemVariableByIdentifier(ivIdent);
                    if (iv.baseTypeId == 1)
                    {
                        def_LookupMaster lm = formsRepo.GetLookupMastersByLookupCode(iv.identifier);
                        if (lm != null)
                        {
                            List <def_LookupDetail> ld = formsRepo.GetLookupDetailsByLookupMasterEnterprise(lm.lookupMasterId, SessionHelper.LoginStatus.EnterpriseID);
                            if (ld.Where(ldt => ramsellVal == ldt.dataValue).Any())
                            {
                                matchIv = iv;
                                break;
                            }
                        }
                    }
                }

                //save the respones "1" to the single matched itemVariable, and add it to the "checkedBoxes" list
                //at the end of the import, any grouped checkboxes that haven't been added to that list will be unchecked
                if (matchIv == null)
                {
                    Debug.WriteLine("* * * RamsellImport: Could not find matching itemVariable for ramsell tag/value \"" + ramellTagName + "/" + ramsellVal + "\", skipping...");
                }
                else
                {
                    def_ItemResults ir = userData.SaveItemResult(toFormResultId, matchIv.itemId);
                    userData.SaveResponseVariable(ir, matchIv, "1");
                    checkedBoxes.Add(matchIv.identifier);
                }
                #endregion
            }
            else
            {
                //this tagname must be either ignorable or handled by a special one-off transformation,
                //so just record the tagname/value pair to be handled later on.
                //the special-cases can involve multiple ramsell tags so there is no way to handle them one tag at a time.
                specialCaseValuesByTagname.Add(ramellTagName, ramsellVal);
            }
        }
Пример #22
0
        private void Upload_SaveResponseVariable(string itmVarIdentifier, string rspVal, def_FormResults fr)
        {
            if (String.IsNullOrWhiteSpace(rspVal))
            {
                return;
            }

            Debug.WriteLine("sving identifier/value: " + itmVarIdentifier + " -> " + rspVal);

            def_ItemVariables iv = GetItemVariableByIdentifier(itmVarIdentifier);

            if (iv == null)
            {
                Debug.WriteLine("could not find item variable with identifier \"" + itmVarIdentifier + "\" (not case-sensitive)");
                return;
            }

            //delete any existing response for this formResult+itemVariable
            def_ResponseVariables existingRv = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, iv.itemVariableId);

            if (existingRv != null)
            {
                formsRepo.DeleteResponseVariableNoSave(existingRv);
            }

            //for response values that reresent dates, convert them to the new format
            try
            {
                if (iv.baseTypeId == 3)
                {
                    rspVal = convertOldToNewDate(rspVal);
                }
            }
            catch (DateNotSupportedException dnse)
            {
                Debug.WriteLine("found date prior to 1900 in response for item variable \"" + itmVarIdentifier + "\", skipping...");
                return;
            }

            //
            if (itmVarIdentifier.Equals("sis_cl_attend"))
            {
                switch (rspVal)
                {
                case "All Of":  rspVal = "1"; break;

                case "Part Of": rspVal = "2"; break;

                case "Did Not": rspVal = "3"; break;
                }
            }

            def_ItemResults ir = fr.def_ItemResults.Where(r => r.itemId == iv.itemId).FirstOrDefault();//formsRepo.GetItemResultByFormResItem(formRsltId, iv.itemId);

            //int itemResultId;
            if (ir == null)
            {
                ir = new def_ItemResults();
                //ir.formResultId = formRsltId;
                ir.itemId        = iv.itemId;
                ir.sessionStatus = 0;
                ir.dateUpdated   = DateTime.Now;

                fr.def_ItemResults.Add(ir);
                //try{
                //    itemResultId = formsRepo.AddItemResult(ir);
                //}
                //catch (Exception e)
                //{
                //    return;
                //    Debug.WriteLine("error while adding item result! ItemVariable Identifier: \"{0}\", response value: \"{1}\", formResultId: \"{2}\"", itmVarIdentifier, rspVal, formRsltId);
                //}
            }
            //else
            //{
            //    itemResultId = ir.itemResultId;
            //}

            //if there is already a response variable for this itemvariable, return
            //if (ir.def_ResponseVariables.Where(v => v.itemVariableId == iv.itemVariableId).Any())
            //    return;

            def_ResponseVariables rv = new def_ResponseVariables
            {
                //itemResultId = itemResultId,
                itemVariableId = iv.itemVariableId,
                rspValue       = rspVal
            };

            try
            {
                formsRepo.ConvertValueToNativeType(iv, rv);
            }
            catch (Exception e)
            {
                Debug.WriteLine("For item variable \"{0}\", Unable to convert value \"{1}\" to native type (baseTypeId {2})", iv.identifier, rspVal, iv.baseTypeId);
                return;
            }

            ir.def_ResponseVariables.Add(rv);
            //try
            //{
            //    formsRepo.AddResponseVariable(rv);
            //}
            //catch (Exception e)
            //{
            //    Debug.WriteLine("error while adding response variable! ItemVariable Identifier: \"{0}\", response value: \"{1}\", formResultId: \"{2}\"", itmVarIdentifier, rspVal, formRsltId);
            //}

            //formsRepo.Save();
        }
        protected void PrintGenericSection(
            PdfOutput output,
            def_Sections section,
            int indentLevel,
            Dictionary <string, string> responsesByItemVariable)
        {
            if (output.drawY < 1.5)
            {
                output.appendPageBreak();
            }

            if (indentLevel < 2)
            {
                output.appendSectionBreak();
            }

            //print section title + identifier
            double sectionLabelIndent = .5 + labelIndent * (indentLevel - 1);
            double itemLabelIndent    = labelIndent * indentLevel;
            double responseIndent     = valueIndent + labelIndent * (indentLevel - 1);

            output.appendWrappedText(buildSectionHeaderText(section),
                                     sectionLabelIndent, 8 - sectionLabelIndent, output.sectionHeaderFontSize);
            output.drawY -= .1;

            List <def_Items> ignoreList = new List <def_Items>();
            int singleBoolCount         = 0;

            formsRepo.GetSectionItems(section);

            //add items wtihout responses to the ignore list, count the number of single-boolean items
            Debug.WriteLine("FormResultPdfReport.PrintGenericSection section: " + section.identifier);
            foreach (def_SectionItems si in section.def_SectionItems.Where(si => !si.subSectionId.HasValue))
            {
                def_Items itm = formsRepo.GetItemById(si.itemId);
                Debug.WriteLine("   itm: " + itm.identifier);
                ICollection <def_ItemVariables> ivs = formsRepo.GetItemVariablesByItemId(itm.itemId);
                if (ivs.Any(iv => !responsesByItemVariable.ContainsKey(iv.identifier) || String.IsNullOrWhiteSpace(responsesByItemVariable[iv.identifier])))
                {
                    ignoreList.Add(itm);
                }

                if ((ivs.Count == 1) && (ivs.First().baseTypeId == 1))
                {
                    singleBoolCount++;
                }
            }

            //if there at least 4 boolean items in this section, ignore all labeled items with single negative boolean responses
            if (singleBoolCount >= 4)
            {
                foreach (def_SectionItems si in section.def_SectionItems.Where(si => !si.subSectionId.HasValue))
                {
                    def_Items itm = formsRepo.GetItemById(si.itemId);
                    ICollection <def_ItemVariables> ivs = formsRepo.GetItemVariablesByItemId(itm.itemId);
                    if (ignoreList.Contains(itm) || itm.label.Trim().Length == 0)
                    {
                        continue;
                    }

                    if (ivs.Count == 1)
                    {
                        def_ItemVariables iv = ivs.First();
                        if ((iv.baseTypeId == 1) && (!responsesByItemVariable.ContainsKey(iv.identifier) || responsesByItemVariable[iv.identifier].Equals("No")))
                        {
                            ignoreList.Add(itm);
                        }
                    }
                }
            }

            //iterate through section items, printing to pdf output
            foreach (def_SectionItems si in section.def_SectionItems)
            {
                if (si.subSectionId.HasValue)
                {
                    PrintGenericSection(output, formsRepo.GetSubSectionById(si.subSectionId.Value), indentLevel + 1);
                }
                else
                {
                    def_Items itm = formsRepo.GetItemById(si.itemId);
                    if (ignoreList.Where(x => x.itemId == itm.itemId).Any())
                    {
                        continue;
                    }

                    formsRepo.GetEnterpriseItems(new def_Items[] { itm }.ToList(), formResults.EnterpriseID.Value);
                    appendItemLabelAndResponses(itm, itemLabelIndent, responseIndent, responsesByItemVariable);
                }
            }
        }
Пример #24
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);
        }
        public ActionResult UploadAssmntCsv(int rowCount)
        {
            //* * * OT 2-4-16 This will be updated so that when rowCount is large, a smaller batchSize is used.
            int batchSize = rowCount;

            using (var csvr = new CsvReader(new StreamReader(Request.InputStream)))
            {
                csvr.ReadHeaderRecord();

                //organize csv headers into a heirarchy that mirrors the response data schema (itemResults->responseVariables)
                //So for each ItemId, we have a set of ItemVariableIDs, each with one csvHeader.
                //This will be used to organize responses in a similar heirarchy and ultimately perform a batch insert
                //all without having to read any more meta-data
                Dictionary <int, Dictionary <int, string> > csvHeadersByIvByItem = new Dictionary <int, Dictionary <int, string> >();
                foreach (string csvHeader in csvr.HeaderRecord)
                {
                    string            ivIdent = getItemVariableIdentifierFromCsvHeader(csvHeader);
                    def_ItemVariables iv      = formsRepo.GetItemVariableByIdentifier(ivIdent);
                    if (iv == null)
                    {
                        continue;
                    }
                    int itmId = iv.itemId;
                    if (!csvHeadersByIvByItem.ContainsKey(itmId))
                    {
                        csvHeadersByIvByItem.Add(itmId, new Dictionary <int, string>());
                    }
                    csvHeadersByIvByItem[itmId].Add(iv.itemVariableId, csvHeader);
                }

                //NO READS AFTER THIS POINT

                //create a structure matching csvHeadersByIvByItem
                //this one will contain responses
                //for each ItemId, we have a set of ItemVariableIDs, each with an empty array to hold a batch of responses
                Dictionary <int, Dictionary <int, string[]> > rspValsByIvByItem = new Dictionary <int, Dictionary <int, string[]> >();
                foreach (int itemId in csvHeadersByIvByItem.Keys)
                {
                    Dictionary <int, string>   csvHeadersByIv = csvHeadersByIvByItem[itemId];
                    Dictionary <int, string[]> rspValsByIv    = new Dictionary <int, string[]>();
                    foreach (int ivId in csvHeadersByIv.Keys)
                    {
                        rspValsByIv.Add(ivId, new string[batchSize]);
                    }
                    rspValsByIvByItem.Add(itemId, rspValsByIv);
                }
                int[] formResultIds = new int[batchSize]; //formResultId for each row of the csv


                //* * * OT 2-4-16 The code below (including call to SaveBatchResponses)
                //* * * will be wrapped in another loop to handle large uploads in multiple batches

                //iterate through the uploaded csv rows,
                //use the heirarchy of headers to populate the heirarchy of responses with input data
                int rowIndex = 0;
                while (csvr.HasMoreRecords && rowIndex < rowCount)
                {
                    AssmntRecord acl = new AssmntRecord(csvr.ReadDataRecord());

                    int formRsltId = acl.getInt("sis_id");
                    foreach (int itemId in csvHeadersByIvByItem.Keys)
                    {
                        Dictionary <int, string>   csvHeadersByIv = csvHeadersByIvByItem[itemId];
                        Dictionary <int, string[]> rspValsByIv    = rspValsByIvByItem[itemId];
                        foreach (int ivId in csvHeadersByIv.Keys)
                        {
                            rspValsByIv[ivId][rowIndex] = acl[csvHeadersByIv[ivId]];
                        }
                    }
                    formResultIds[rowIndex] = formRsltId;

                    rowIndex++;
                }

                //push all the data into the database at once.
                //this does not require any reads, because the response heirarchy matches the DB schema (itemResults->responseVariables)
                try
                {
                    formsRepo.SaveBatchResponses(rspValsByIvByItem, formResultIds);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("* * * UploadAssmntCsv: failed to save formResultIds " + String.Join(", ", formResultIds));
                }
            }

            return(Content("Upload Successful!"));
        }
Пример #26
0
        protected void PrintSupplementalQuestions(PdfOutput output)
        {
            def_Parts part = formsRepo.GetPartByFormAndIdentifier(form, "Supplemental Questions");

            AppendPartHeader(output, part.identifier);

            def_Sections topSct = formsRepo.GetSectionsInPart(part).FirstOrDefault();

            if (topSct == null)
            {
                throw new Exception("not sections found in part with partId " + part.partId);
            }

            List <def_Sections> sectionList = new List <def_Sections>();

            formsRepo.SortSectionItems(topSct);
            foreach (def_SectionItems sctnItm in topSct.def_SectionItems)
            {
                if (sctnItm.display == false)
                {
                    continue;
                }
                def_Sections subSctns = formsRepo.GetSubSectionById(sctnItm.subSectionId);// sctnItm.def_SubSections.def_Sections;
                sectionList.Add(subSctns);
            }

            int  grayCount          = 0;
            bool showWhiteQuestions = true;

            foreach (def_Sections sct in sectionList)
            {
                formsRepo.SortSectionItems(sct);
                foreach (def_SectionItems si in sct.def_SectionItems)
                {
                    if (si.display == false)
                    {
                        continue;
                    }

                    //if this is a "gray" question... (high-level questions pertaining to a set of "white" questions)
                    if (si.subSectionId == null)
                    {
                        grayCount++;
                        if (grayCount > 1)
                        {
                            output.drawY -= .5;
                        }
                        def_Items         itm = si.def_Items;
                        def_ItemVariables iv  = itm.def_ItemVariables.FirstOrDefault();
                        if (iv == null)
                        {
                            throw new Exception("no item variable for question with itemId " + si.itemId);
                        }
                        def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(formResultId, iv.itemVariableId);//iv.def_ResponseVariables.FirstOrDefault();
                        if (rv == null)
                        {
                            continue;
                        }

                        //don't show the white questions if the response value is false
                        if (iv.baseTypeId == 1 && (rv.rspValue.ToLower().Equals("false") || rv.rspValue.Equals("0")))
                        {
                            showWhiteQuestions = false;
                        }
                        else
                        {
                            showWhiteQuestions = true;
                        }

                        if (output.drawY < .5)
                        {
                            output.appendPageBreak();
                        }

                        if (!itm.label.Equals("Page Notes"))
                        {
                            double y = output.drawY;
                            output.appendWrappedText(grayCount + ".", .8, 6, output.boldFont);
                            output.drawY = y;
                        }
                        output.appendWrappedText(itm.label, 1, 7, output.boldFont);
                        output.appendWrappedText(GetSupplementalResponseText(iv, rv), 1.5, 6, output.boldFont);
                        output.drawY -= PdfOutput.itemSpacing;
                    }

                    // if this is a "white" question-set
                    else
                    {
                        if (!showWhiteQuestions)
                        {
                            continue;
                        }
                        foreach (def_SectionItems ssi in si.def_SubSections.def_Sections.def_SectionItems)
                        {
                            def_Items itm = ssi.def_Items;
                            if (itm == null)
                            {
                                throw new Exception("no item for setionItems with sectionItemId " + ssi.sectionItemId);
                            }
                            def_ItemVariables iv = itm.def_ItemVariables.FirstOrDefault();
                            if (iv == null)
                            {
                                throw new Exception("no item variable for item with itemId " + itm.itemId);
                            }
                            def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(formResultId, iv.itemVariableId);

                            try
                            {
                                output.appendWrappedText(itm.label, 1.1, 6);
                            }
                            catch (ApplicationException e)
                            {
                                string msg = "Exception appending label \"" +
                                             itm.label + "\" for item with itemId " + itm.itemId + "\nchars:";
                                foreach (char c in itm.label.ToCharArray())
                                {
                                    msg += " " + c + "(" + ((int)c) + ")";
                                }
                                throw new Exception(msg, e);
                            }

                            output.appendWrappedText(GetSupplementalResponseText(iv, rv), 1.5, 6);
                            output.drawY -= PdfOutput.itemSpacing;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Used to display responses to radiobuttons or dropdowns.
        ///
        /// Retrieve a numerical response for the given def_FormResult and deF_ItemVariable from the ResponseVariables table,
        /// Then lookup the display text associated with the numerical response, for the current UI language.
        /// </summary>
        /// <param name="formResultId"></param>
        /// <param name="itm"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        private string GetResponseThroughLookupTables(int formResultId, def_Items itm, def_ItemVariables iv)
        {
            string           rsp = GetResponse(formResultId, itm, iv);
            def_LookupMaster lm  = formsRepo.GetLookupMastersByLookupCode(iv.identifier);

            if (lm == null)
            {
                return(rsp);
            }

            def_LookupDetail ld = formsRepo.GetLookupDetailByEnterpriseMasterAndDataValue(SessionHelper.LoginStatus.EnterpriseID, lm.lookupMasterId, rsp);

            if (ld != null)
            {
                CultureInfo    ci     = Thread.CurrentThread.CurrentUICulture;
                string         region = (ci == null) ? "en" : ci.TwoLetterISOLanguageName.ToLower();
                int            langId = formsRepo.GetLanguageByTwoLetterISOName(region).langId;
                def_LookupText lt     = formsRepo.GetLookupTextsByLookupDetailLanguage(ld.lookupDetailId, langId).FirstOrDefault();
                if (lt != null)
                {
                    return(lt.displayText);
                }
            }
            return(rsp);
        }
        /*  This method Saves data from the screen when the Submit button is clicked.
         *  The concept is that we know which Section was last displayed from the session variables.
         *  So we cycle through the ItemVariables and update the associated ResponseValues from the FormCollection of screen values.
         */
        public ActionResult Save(FormCollection frmCllctn, Assmnts.Models.TemplateItems ti)
        {
            mLogger.Debug("  ResultController:Save");

            Dictionary <string, string> previousResponseValues = SessionHelper.ResponseValues;

            if (previousResponseValues != null)
            {
                //Throw out responses that haven't changed
                foreach (var previousResponseKvp in previousResponseValues)
                {
                    if (!string.IsNullOrWhiteSpace(previousResponseKvp.Key))
                    {
                        var newResponseValue = frmCllctn.GetValue(previousResponseKvp.Key);
                        //If the value is bool and it is now false (checkbox for example) it won't be sent back in the form collection
                        //we need to test for bool and set these values to false (if they are true)
                        var itemVariable = formsRepo.GetItemVariableByIdentifier(previousResponseKvp.Key);
                        //itemVariable will often be null because all the PREVIOUS_ identifiers get sent through also
                        var impliedBooleanFalseResult = false;
                        if (newResponseValue == null && itemVariable != null && itemVariable.baseTypeId == Assmnts.Constants.CAADAP.BASE_TYPE_BOOLEAN)
                        {
                            newResponseValue          = new ValueProviderResult("0", "0", CultureInfo.CurrentCulture);
                            impliedBooleanFalseResult = true;
                        }
                        if (newResponseValue != null)
                        {
                            //Compare previous with posted values
                            //Note if they are both null or both empty we want to throw it out
                            if (newResponseValue.AttemptedValue == null && previousResponseKvp.Value == null)
                            {
                                frmCllctn.Remove(previousResponseKvp.Key);
                            }
                            else if (newResponseValue.AttemptedValue != null && previousResponseKvp.Value != null)
                            {
                                var  previousResponseString = previousResponseKvp.Value;
                                var  newResponseString      = newResponseValue.AttemptedValue;
                                bool previousResponseTrue   = false;
                                bool previousResponseFalse  = false;
                                //If it's a bool, try to convert 'false' to '0' and so on
                                if (previousResponseTrue = previousResponseString.Equals("true", StringComparison.InvariantCultureIgnoreCase) ||
                                                           (previousResponseFalse = previousResponseString.Equals("false", StringComparison.InvariantCultureIgnoreCase)))
                                {
                                    if (itemVariable != null && itemVariable.baseTypeId == Assmnts.Constants.CAADAP.BASE_TYPE_BOOLEAN)
                                    {
                                        if (previousResponseFalse)
                                        {
                                            previousResponseString = "0";
                                        }
                                        else if (previousResponseTrue)
                                        {
                                            previousResponseString = "1";
                                        }
                                    }
                                }
                                if (newResponseString.Equals(previousResponseString))
                                {
                                    frmCllctn.Remove(previousResponseKvp.Key);
                                }
                                else if (impliedBooleanFalseResult)
                                {
                                    //The values are different, but the form collection doesn't contain the result
                                    frmCllctn.Add(previousResponseKvp.Key, newResponseValue.AttemptedValue);
                                }
                            }
                        }
                    }
                }
            }

            // If User is not logged in, there are no session variables.
            // This prevents saving the formResultId
            if (!SessionHelper.IsUserLoggedIn)
            {
                return(RedirectToAction("Index", "Account", null));
            }

            //check if the form is unchanged
            //bool unchanged = true;
            //foreach (string key in frmCllctn.Keys)
            //{
            //    HttpCookie oldVal = Request.Cookies["frmOriginal___" + key];
            //    if (oldVal != null && !frmCllctn[key].Trim().Equals(oldVal.Value.Replace("%0d%0a","").Trim()))
            //    {
            //        //mLogger.Debug("* * *  ResultsController:SaveSectionItems changed key: \"" + key + "\", original value: \"" + Session["frmOriginal___" + key] + "\", new value: \"" + frmCllctn[key] + "\"" );
            //        unchanged = false;
            //        break;
            //    }
            //}

            bool        unchanged = false;
            SessionForm sf        = SessionHelper.SessionForm;

            if (unchanged || sf.readOnlyMode)
            {
                mLogger.Debug("* * *  ResultsController:SaveSectionItems form is unchanged, skipping update");
            }
            else
            {
                mLogger.Debug("* * *  ResultsController:Save method  * * *    sectionId: {0}", sf.sectionId);

                // save responses to database

                //* * * OT 03/10/16 Switched to using AJBoggs\Def\Domain\UserData.SaveFormCollection.cs
                UserData ud = new UserData(formsRepo);
                ud.SaveFormCollection(frmCllctn, sf.sectionId, sf.formResultId);
                ud.SaveFileUploads(sf.formResultId, Request);

                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);
                formResult.LastModifiedByUserId = SessionHelper.LoginStatus.UserID;
                formResult.dateUpdated          = DateTime.Now;

                // Update the assigned field in the formResults based on the data in the Interviewer field on idprof1.
                if (sf.sectionId == 1)
                {
                    def_ItemVariables interviewerVar = formsRepo.GetItemVariableByIdentifier("sis_int_id");
                    if (interviewerVar != null)
                    {
                        def_ItemResults ir = formsRepo.GetItemResultByFormResItem(formResult.formResultId, interviewerVar.itemId);
                        if (ir != null)
                        {
                            def_ResponseVariables rv = formsRepo.GetResponseVariablesByItemResultItemVariable(ir.itemResultId, interviewerVar.itemVariableId);
                            if (rv != null && !String.IsNullOrEmpty(rv.rspValue))
                            {
                                int rspInt;
                                if (Int32.TryParse(rv.rspValue, out rspInt))
                                {
                                    formResult.assigned = rspInt;
                                }
                                else
                                {
                                    mLogger.Error("Error converting response value {0} to int.", rv.rspValue);
                                }
                            }
                        }
                    }
                }

                formsRepo.Save();

                //set status to "in progress" for SIS forms
                //if (sf.formIdentifier.Equals("SIS-A") || sf.formIdentifier.Equals("SIS-C"))
                //{

                //if ( (fr.reviewStatus != ReviewStatus.APPROVED) && (fr.reviewStatus != ReviewStatus.REVIEWED) && (fr.reviewStatus != ReviewStatus.PRE_QA) )
                //{
                //    fr.formStatus = (byte)FormResults_formStatus.IN_PROGRESS;
                //    // this will be saved to the database in one of the scoring updates below
                //}

                //}

                bool isSisForm = sf.formIdentifier.Equals("SIS-A") || sf.formIdentifier.Equals("SIS-C");

                //run single-section validation for sis forms
                if (isSisForm)
                {
                    List <string> validationErrorMessages;
                    bool          ssValidationFailed = SisOneOffValidation.RunSingleSectionOneOffValidation(
                        formsRepo, frmCllctn, sf.sectionId, out validationErrorMessages);
                    if (ssValidationFailed)
                    {
                        return(Template(sf.sectionId, validationErrorMessages));
                    }

                    //run full-assessment validation and update scores for completed SIS forms
                    if (formResult.formStatus == (byte)FormResults_formStatus.COMPLETED || formResult.locked)
                    {
                        //if validation passes, it will trigger scoring automatically
                        if (sf.sectionId != 504 && !ValidateFormResult(formResult))                         // Section 504 is interview planning
                        {
                            //if validation fails set the form status to in-progress
                            formsRepo.SetFormResultStatus(formResult, (byte)FormResults_formStatus.IN_PROGRESS);
                        }
                    }
                }
            }

            // string ctrl = "Results";
            // if (frmCllctn.AllKeys.Contains("UseThisControllerForTemplate"))
            //    ctrl = frmCllctn["UseThisControllerForTemplate"];

            //debug runtime
            //TimeSpan duration = DateTime.Now - startTime;
            //using (StreamWriter sw = System.IO.File.AppendText(@"C:\Users\otessmer\Desktop\log.txt"))
            //{
            //    sw.WriteLine(duration.Milliseconds);
            //}

            // if necessary, redirect to a different section now that we've saved the results
            string navSectionId = String.Empty;

            if (frmCllctn.AllKeys.Contains("navSectionId"))
            {
                navSectionId = frmCllctn["navSectionId"];
                if (!String.IsNullOrEmpty(navSectionId))
                {
                    if (navSectionId == "search")
                    {
                        return(RedirectToAction("Index", "Search", new { }));
                    }

                    if (navSectionId == "logout")
                    {
                        return(RedirectToAction("LogoutUAS", "Account"));
                    }

                    if (navSectionId == "new")
                    {
                        return(RedirectToAction("NewBlankAssessment", "Search", new { formId = SessionHelper.Read <int>("newFormId") }));
                    }

                    // Redirect subforms to the original parent page.
                    if (navSectionId == "SubForm")
                    {
                        SessionForm psf = (SessionForm)Session["ParentFormData"];
                        return(RedirectToAction("ToTemplate", "Adap", new {
                            formResultId = psf.formResultId,
                            formId = psf.formId,
                            partId = psf.partId,
                            sectionIdOverride = psf.sectionId
                        }));
                    }

                    // Must be a Form Part Section
                    //Displays successful save message
                    Session["part"] = frmCllctn["navPartId"];
                    Session["form"] = frmCllctn["navFormId"];
                }
            }
            else
            {
                navSectionId = sf.sectionId.ToString();
            }

            if (Session["IsPageLoad"] != null)
            {
            }
            if (navSectionId == "703")
            {
                TempData["Savemsg"]       = "Contact info save successful";
                TempData["SavemsgHeader"] = "Saved";
            }
            else if (navSectionId == "704")
            {
                TempData["Savemsg"]       = "Demographics info save successful";
                TempData["SavemsgHeader"] = "Saved";
            }
            else if (navSectionId == "705")
            {
                TempData["Savemsg"]       = "Clinical info save successful";
                TempData["SavemsgHeader"] = "Saved";
            }
            else if (navSectionId == "706")
            {
                TempData["Savemsg"]       = "Health Coverage info save successful";
                TempData["SavemsgHeader"] = "Saved";
            }
            else if (navSectionId == "726")
            {
                TempData["Savemsg"]       = "Income info save successful";
                TempData["SavemsgHeader"] = "Saved";
            }
            else if (navSectionId == "732")
            {
                TempData["Savemsg"]       = "Insurance Assistance info save successful";
                TempData["SavemsgHeader"] = "Saved";
            }
            else if (navSectionId == "734")
            {
                TempData["Savemsg"]       = "Attachment info save successful";
                TempData["SavemsgHeader"] = "Saved";
            }
            else if (navSectionId == "753")
            {
                TempData["Savemsg"]       = "Medical Out of Pocket info save successful";
                TempData["SavemsgHeader"] = "Saved";
            }
            else if (navSectionId == "708")
            {
                TempData["Savemsg"]       = "Consent&Submit info save successful";
                TempData["SavemsgHeader"] = "Saved";
            }
            else if (navSectionId == "756")
            {
                TempData["Savemsg"]       = "Eligibility info save successful";
                TempData["SavemsgHeader"] = "Saved";
            }
            else if (navSectionId == "759")
            {
                TempData["Savemsg"]       = "SVF info save successful";
                TempData["SavemsgHeader"] = "Saved";
            }
            else
            {
                TempData["Savemsg"]       = "";
                TempData["SavemsgHeader"] = "";
            }

            if (sf.sectionId == 708)
            {
                def_FormResults formResult = formsRepo.GetFormResultById(sf.formResultId);
                IEnumerable <def_FormResults> frElgList = formsRepo.GetFormResultsByFormSubject(18, formResult.subject);

                var adapCaController = new AdapCaController(formsRepo);

                if (!frElgList.Any())
                {
                    adapCaController.CreateElgibility(sf.formResultId);
                }

                adapCaController.CopyToEligibility("C1_FormSubmitEnrollmentSiteName", "C1_MemberSelectedEnrollmentSite", formResult.formResultId, formResult.subject.Value);
                formsRepo.Save();
            }

            //$$ Start of people Picker V2 Functionality

            PeoplePickerHelper objUtility = new PeoplePickerHelper(authClient, formsRepo);

            objUtility.SaveresultsForEnWrkerPicker(sf.sectionId, sf.formResultId);

            //$$ End of people Picker V2 Functionality

            var redirect = frmCllctn["navRedirect"];

            if (!string.IsNullOrWhiteSpace(redirect))
            {
                return(Redirect(redirect));
            }
            else
            {
                return(RedirectToAction("Template", "Results", new { sectionId = navSectionId }));
            }
        }
        public ActionResult UploadCsvGetStubRecords()
        {
            string result = "USE [forms]\nGO\nSET IDENTITY_INSERT [dbo].[def_FormResults] ON\nGO\n";

            using (var csvr = new CsvReader(new StreamReader(Request.InputStream)))
            {
                csvr.ReadHeaderRecord();

                //organize csv headers into a heirarchy similar to the response data schema
                //So for each ItemId, we have a set of ItemVariableIDs, each with one csvHeader.
                Dictionary <int, Dictionary <int, string> > csvHeadersByIvByItem = new Dictionary <int, Dictionary <int, string> >();
                foreach (string csvHeader in csvr.HeaderRecord)
                {
                    string            ivIdent = getItemVariableIdentifierFromCsvHeader(csvHeader);
                    def_ItemVariables iv      = formsRepo.GetItemVariableByIdentifier(ivIdent);
                    if (iv == null)
                    {
                        continue;
                    }
                    int itmId = iv.itemId;
                    if (!csvHeadersByIvByItem.ContainsKey(itmId))
                    {
                        csvHeadersByIvByItem.Add(itmId, new Dictionary <int, string>());
                    }
                    csvHeadersByIvByItem[itmId].Add(iv.itemVariableId, csvHeader);
                }

                ////determine which header is present for assigning uploaded formResults to groups
                //bool useOrgNames;
                //if( csvr.HeaderRecord.Contains( "sub_id" ) )
                //    useOrgNames = false;
                //else if (csvr.HeaderRecord.Contains("org_name"))
                //    useOrgNames = true;
                //else
                //    throw new Exception( "Could not find any headers to link assessments to groups" );

                //iterate through the uploaded csv rows
                while (csvr.HasMoreRecords)
                {
                    AssmntRecord acl = new AssmntRecord(csvr.ReadDataRecord());

                    int formId  = 1;
                    int subject = 0;// acl.getInt("ClientId");
                    int entId   = acl.getInt("ent_id");
                    //int groupId = 460;//one-off 9/2/15////////////////////////////////
                    //if (useOrgNames)
                    //{
                    //    string orgName = acl["org_name"];
                    //    Group group = auth.GetGroupsByGroupNameAndEnterpriseID(orgName, entId).FirstOrDefault();
                    //    if (group == null)
                    //        throw new Exception("could not find group for org_name \"" + orgName + "\"");
                    //    groupId = group.GroupID;
                    //}
                    //else
                    //{
                    int groupId = acl.getInt("sub_id");
                    //}

                    //add new form result in database
                    //int formRsltId = formsRepo.AddFormResult(formResult);

                    int             formRsltId = acl.getInt("sis_id");
                    def_FormResults formResult = formsRepo.GetFormResultById(formRsltId);

                    // if the formResult doesn't already exist, append to the sql script for identity-inserting stub records
                    if (formResult == null)
                    {
                        def_FormResults fr = new def_FormResults();
                        fr.formId        = formId;
                        fr.EnterpriseID  = entId;
                        fr.GroupID       = groupId;
                        fr.subject       = subject;
                        fr.dateUpdated   = DateTime.Now;
                        fr.formStatus    = GetStatus(acl["Status"]);
                        fr.locked        = GetLocked(acl["Status"]);
                        fr.sessionStatus = 0;
                        fr.reviewStatus  = 255;
                        fr.training      = false;

                        string sql = "INSERT INTO [dbo].[def_FormResults]([formResultId],[formId],[formStatus],[sessionStatus],[dateUpdated],[deleted],[locked],"
                                     + "[archived],[EnterpriseID],[GroupID],[subject],[interviewer],[assigned],[training],[reviewStatus],[statusChangeDate])\n"
                                     + "VALUES( '" + formRsltId + "','" + fr.formId + "','" + fr.formStatus + "','" + fr.sessionStatus + "','" + fr.dateUpdated + "','"
                                     + fr.deleted + "','" + fr.locked + "','" + fr.archived + "','" + fr.EnterpriseID + "','" + fr.GroupID + "','" + fr.subject + "','"
                                     + fr.interviewer + "','" + fr.assigned + "','" + fr.training + "','" + fr.reviewStatus + "','" + fr.statusChangeDate + "')\n";


                        result += sql;
                    }

                    //    // Null out the locally allocated objects so the garbage collector disposes of them.
                    //    fr = null;
                    //    acl = null;
                    //    formResult = null;
                    //}

                    ////saveAssessmentScript(formResult);
                    //formsRepo.SaveFormResults(formResult);
                    //formsRepo.GetContext().Dispose();
                    //formsRepo = new FormsRepository();

                    //// Null out the locally allocated objects so the garbage collector disposes of them.
                    //fr = null;
                    //acl = null;
                    //formResult = null;
                }
            }

            result += "SET IDENTITY_INSERT [dbo].[def_FormResults] OFF\nGO\n";

            return(Content(result));
        }
        //Private instance methods

        private void PopulateItems(def_FormResults formResult, def_FormResults previousFormResult, List <ItemToPrepopulate> itemsToPrepopulate)
        {
            List <Tuple <def_Items, ItemToPrepopulate> > itemTuples = new List <Tuple <def_Items, ItemToPrepopulate> >();

            foreach (ItemToPrepopulate itemToPrepopulate in itemsToPrepopulate)
            {
                def_Items item = formsRepo.GetItemByIdentifier(itemToPrepopulate.Title + Constants.CAADAP.IDENTIFIER_SUFFIX);                 //This is coming from cache
                if (item != null)
                {
                    item = new def_Items(item);                     //We can't modify an item from the cache
                    itemTuples.Add(new Tuple <def_Items, ItemToPrepopulate>(item, itemToPrepopulate));
                }
            }
            if (itemTuples.Count == 0)
            {
                return;
            }

            formsRepo.GetItemLabelsResponses(previousFormResult.formResultId, itemTuples.Select(x => x.Item1).ToList());

            foreach (var itemTuple in itemTuples)
            {
                def_Items         item = itemTuple.Item1;
                ItemToPrepopulate itemToPrepopulate  = itemTuple.Item2;
                def_ItemResults   itemResult         = formResult.def_ItemResults.Where(x => x.itemId == item.itemId).FirstOrDefault();
                def_ItemResults   previousItemResult = item.def_ItemResults.FirstOrDefault();
                def_ItemVariables itemVariable       = item.def_ItemVariables.FirstOrDefault();
                if (previousItemResult == null || itemVariable == null)
                {
                    continue;
                }
                def_ResponseVariables previousResponseVariable = itemVariable.def_ResponseVariables.FirstOrDefault();
                if (previousResponseVariable != null && !String.IsNullOrWhiteSpace(previousResponseVariable.rspValue))
                {
                    bool addItemResult       = false;
                    bool addResponseVariable = false;
                    if (itemResult == null)
                    {
                        itemResult = new def_ItemResults()
                        {
                            itemId        = item.itemId,
                            sessionStatus = 0,
                            dateUpdated   = DateTime.Now
                        };
                        addItemResult = true;
                    }
                    def_ResponseVariables responseVariable = itemResult.def_ResponseVariables.FirstOrDefault();
                    if (responseVariable == null)
                    {
                        responseVariable = new def_ResponseVariables {
                            itemVariableId = itemVariable.itemVariableId
                        };
                        addResponseVariable = true;
                    }
                    if (String.IsNullOrWhiteSpace(responseVariable.rspValue))
                    {
                        bool documentCopyFailed = false;
                        if (itemToPrepopulate.Document.HasValue && itemToPrepopulate.Document.Value)
                        {
                            string newSaveDirectoryPath = Assmnts.Business.Uploads.FileUploads.GetSaveDirectoryPath(formResult.formResultId, itemToPrepopulate.Title);
                            string newDocumentPath;
                            if (TryCopyDocument(previousResponseVariable.rspValue, newSaveDirectoryPath, out newDocumentPath))
                            {
                                responseVariable.rspValue = newDocumentPath;
                            }
                            else
                            {
                                documentCopyFailed = true;
                            }
                        }
                        else
                        {
                            //The item is not a document, just copy the value
                            responseVariable.rspValue = previousResponseVariable.rspValue;
                            try {
                                formsRepo.ConvertValueToNativeType(itemVariable, responseVariable);
                            }
                            catch (Exception ex) {
                                Debug.WriteLine("error converting response to native type for itemvariable \""
                                                + itemVariable.identifier + "\": " + ex.Message);
                            }
                        }
                        if (!documentCopyFailed)
                        {
                            if (addResponseVariable)
                            {
                                itemResult.def_ResponseVariables.Add(responseVariable);
                            }
                            if (addItemResult)
                            {
                                itemResult.dateUpdated = DateTime.Now;
                                formResult.def_ItemResults.Add(itemResult);
                            }
                        }
                    }
                }
            }
        }