/// <summary>
        /// Looks at uas_GroupUserAppPermissions integration webservice permission. If it is enabled, returns true.
        ///
        /// Stores enabled status in session variable to speed it up next time it is run.
        /// </summary>
        /// <returns></returns>
        public static bool IsWebServiceEnabled()
        {
            string webServiceEnabled = SessionHelper.Read <string>("webservice_enabled");

            if (webServiceEnabled != null)
            {
                if (webServiceEnabled.ToLower() == "true")
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            if (UAS_Business_Functions.hasPermission(PermissionConstants.WS_ACCESS, PermissionConstants.INTEGRATION))
            {
                SessionHelper.Write("webservice_enabled", "true");
                return(true);
            }
            else
            {
                SessionHelper.Write("webservice_enabled", "false");
                return(false);
            }
        }
Esempio n. 2
0
        /*
         * Returns the total Session timeout in minutes.
         * Default: sessionState from the web.config
         * If available, from the Enterprise Application Configuration.
         *
         */
        public static int GetTotalTimeoutMinutes(int EnterpriseId)
        {
            SessionStateSection sessionSection = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");
            int timeout = (int)sessionSection.Timeout.TotalMinutes;


            bool VentureMode = SessionHelper.IsVentureMode;

            if (VentureMode)
            {
                return(timeout);
            }


            EntAppConfig timeoutConfig = UAS_Business_Functions.GetEntAppConfig(UAS.Business.ConfigEnumCodes.TIMEOUT, EnterpriseId);

            if (timeoutConfig != null)
            {
                int  time;
                bool convertTimeoutString = Int32.TryParse(timeoutConfig.ConfigValue, out time);
                timeout = (convertTimeoutString) ? time : (int)sessionSection.Timeout.TotalMinutes;
            }

            return(timeout);
        }
Esempio n. 3
0
        public string GenerateQuery(string formTable)
        {
            StringBuilder stringBuilder = new StringBuilder();

            if (formTable == "def_ResponseVariables")
            {
                stringBuilder.Append(" JOIN def_ItemResults on def_ItemResults.itemResultId = def_ResponseVariables.itemResultId");
            }

            if (formTable == "def_ItemResults" || formTable == "def_ResponseVariables")
            {
                stringBuilder.Append(" JOIN def_FormResults on def_FormResults.formResultId = def_ItemResults.formResultId");
            }

            if (formTable == "Recipient")
            {
                stringBuilder.Append(" INNER JOIN def_FormResults on def_FormResults.subject = Recipient.Recipient_ContactID");
            }

            if (formTable == "Contact")
            {
                stringBuilder.Append(" INNER JOIN def_FormResults on def_FormResults.subject = Contact.ContactID");
            }

            if (formTable == "def_FormResults" || formTable == "def_ItemResults" || formTable == "def_ResponseVariables" || formTable == "Recipient" || formTable == "Contact")
            {
                stringBuilder.Append(" WHERE EnterpriseID = " + SessionHelper.LoginStatus.EnterpriseID);

                if (!SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups.Contains(0))
                {
                    stringBuilder.Append(" AND (");

                    for (int i = 0; i < SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups.Count; i++)
                    {
                        stringBuilder.Append("GroupID = " + SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups[i]);

                        if (i < SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups.Count - 1)
                        {
                            stringBuilder.Append(" OR ");
                        }
                    }
                    stringBuilder.Append(")");
                }

                if (!UAS_Business_Functions.hasPermission(PermissionConstants.GROUP_WIDE, PermissionConstants.ASSMNTS))
                {
                    stringBuilder.Append(" AND " + " assigned = " + SessionHelper.LoginStatus.UserID);
                }

                // stringBuilder.Append(" AND " + " deleted = 0");
            }

            return(stringBuilder.ToString());
        }
        private List <spSearchGrid_Result> filterSearchResultsByAuthGroups(List <spSearchGrid_Result> results)
        {
            results = filterSearchResultsByEnterprise(results);

            if (!UAS_Business_Functions.hasPermission(UAS.Business.PermissionConstants.GROUP_WIDE, UAS.Business.PermissionConstants.ASSMNTS))
            {
                results = filterResultsByAssignOnly(results);
            }

            if (SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups[0] == 0)
            {
                return(results);
            }
            List <int> authGroups = SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups;

            int?[] idsToRemove = new int?[results.Count()];

            int i = 0;

            foreach (spSearchGrid_Result r in results)
            {
                if ((r != null) && r.formResultId.HasValue)
                {
                    //def_FormResults fr = formsRepo.GetFormResultById(r.formResultId.Value);
                    if ((r != null) && r.sub_id.HasValue && UAS_Business_Functions.isGroupAuthorized(authGroups, r.sub_id.Value))
                    {
                        continue;
                    }
                    else
                    {
                        idsToRemove[i] = r.formResultId;
                        i++;
                    }
                }
            }

            foreach (int?id in idsToRemove)
            {
                if (id != null)
                {
                    results.Remove(results.Single(r => r.formResultId == id));
                }
                else
                {
                    break;
                }
            }

            return(results);
        }
Esempio n. 5
0
        public TemplateAssmntNavMenu(IFormsRepository formsRepo)
        {
            if (SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets.Count() > 0)
            {
                create   = UAS_Business_Functions.hasPermission(SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet, UAS.Business.PermissionConstants.CREATE, UAS.Business.PermissionConstants.ASSMNTS);
                unlock   = UAS_Business_Functions.hasPermission(SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet, UAS.Business.PermissionConstants.UNLOCK, UAS.Business.PermissionConstants.ASSMNTS);
                delete   = UAS_Business_Functions.hasPermission(SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet, UAS.Business.PermissionConstants.DELETE, UAS.Business.PermissionConstants.ASSMNTS);
                archive  = UAS_Business_Functions.hasPermission(SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet, UAS.Business.PermissionConstants.ARCHIVE, UAS.Business.PermissionConstants.ASSMNTS);
                undelete = UAS_Business_Functions.hasPermission(SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet, UAS.Business.PermissionConstants.UNDELETE, UAS.Business.PermissionConstants.ASSMNTS);
            }

            ventureMode = SessionHelper.IsVentureMode;

            forms = Business.Forms.GetFormsDictionary(formsRepo);
        }
        public bool UploadFile(FormCollection formCollection)
        {
            bool edit       = UAS_Business_Functions.hasPermission(UAS.Business.PermissionConstants.EDIT, UAS.Business.PermissionConstants.ASSMNTS);
            bool editlocked = UAS_Business_Functions.hasPermission(UAS.Business.PermissionConstants.EDIT_LOCKED, UAS.Business.PermissionConstants.ASSMNTS);
            int  fileId     = -1;

            if (edit || editlocked)
            {
                int RelatedEnumId = formsRepo.GetRelatedEnumIdByEnumDescription("formResultId");
                int AttachTypeId  = formsRepo.GetAttachTypeIdByAttachDescription("Generic Upload");

                int formResultId = Convert.ToInt32(formCollection["formResultId"]);
                System.Web.HttpPostedFileWrapper file = (System.Web.HttpPostedFileWrapper)Request.Files["file" + formResultId.ToString()];
                def_FormResults fr = formsRepo.GetFormResultById(formResultId);

                DateTime now    = DateTime.Now;
                string   date   = now.Year.ToString() + ((now.Month < 10) ? "0" : "") + now.Month.ToString() + ((now.Day < 10) ? "0" : "") + now.Day.ToString();
                string   time   = ((now.Hour < 10) ? "0" : "") + now.Hour.ToString() + ((now.Minute < 10) ? "0" : "") + now.Minute.ToString() + ((now.Second < 10) ? "0" : "") + now.Second.ToString();
                string   subDir = date + Path.DirectorySeparatorChar + time;

                fileId = FileUploads.CreateAttachment(formsRepo, file, null, subDir, formResultId, RelatedEnumId, AttachTypeId);

                // check if the file uploaded has a duplicated displayText for this assessment.  i.e., a logical overwrite.
                if (fileId > -1)
                {
                    def_FileAttachment       fa    = formsRepo.GetFileAttachment(fileId);
                    Dictionary <int, string> texts = FileUploads.RetrieveFileDisplayTextsByRelatedId(formsRepo, formResultId, RelatedEnumId, "A", AttachTypeId);

                    foreach (int k in texts.Keys)
                    {
                        if (texts[k].Equals(fa.displayText) && k != fa.FileId)
                        {
                            FileUploads.DeleteFile(formsRepo, k);
                        }
                    }
                }
            }

            if (fileId > -1)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 7
0
        public int CreateFormResult(int formId, int formStatus, int sessionStatus, DateTime dateUpdated,
                                    bool deleted, bool locked, bool archived, int?EnterpriseID, int?GroupID, int?subject, int?interviewer, int?assigned, bool training, int reviewStatus, DateTime?statusChangeDate)
        {
            int grpId = (GroupID == null) ? -1 : (int)GroupID;

            try {
                if (SessionHelper.LoginStatus.EnterpriseID == 0 || SessionHelper.LoginStatus.EnterpriseID == EnterpriseID)
                {
                    if (SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups.Contains(0) || SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups.Contains(grpId))
                    {
                        bool create = UAS_Business_Functions.hasPermission(SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet, UAS.Business.PermissionConstants.CREATE, UAS.Business.PermissionConstants.ASSMNTS);

                        if (create)
                        {
                            def_FormResults formResult = new def_FormResults();

                            formResult.formId           = formId;
                            formResult.formStatus       = (byte)formStatus;
                            formResult.sessionStatus    = (byte)sessionStatus;
                            formResult.dateUpdated      = dateUpdated;
                            formResult.deleted          = deleted;
                            formResult.locked           = locked;
                            formResult.archived         = archived;
                            formResult.EnterpriseID     = EnterpriseID;
                            formResult.GroupID          = GroupID;
                            formResult.subject          = subject;
                            formResult.interviewer      = interviewer;
                            formResult.assigned         = assigned;
                            formResult.training         = training;
                            formResult.reviewStatus     = (byte)reviewStatus;
                            formResult.statusChangeDate = statusChangeDate;

                            formsRepo.AddFormResult(formResult);

                            return(formResult.formResultId);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("CreatFormResult exception: " + ex.Message);
                return(-2);
            }
            return(-1);
        }
Esempio n. 8
0
        public Home()
        {
            LoginID = SessionHelper.LoginInfo.LoginID;
            isAdmin = SessionHelper.LoginStatus.IsAdmin;

            timeout = SessionHelper.SessionTotalTimeoutMinutes;
            try
            {
                if (SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets.Count() > 0)
                {
                    create = UAS_Business_Functions.hasPermission(SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet, UAS.Business.PermissionConstants.CREATE, UAS.Business.PermissionConstants.ASSMNTS);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Missing permission: " + ex.Message);
            }
        }
        public void DeleteFile()
        {
            bool edit       = UAS_Business_Functions.hasPermission(UAS.Business.PermissionConstants.EDIT, UAS.Business.PermissionConstants.ASSMNTS);
            bool editlocked = UAS_Business_Functions.hasPermission(UAS.Business.PermissionConstants.EDIT_LOCKED, UAS.Business.PermissionConstants.ASSMNTS);

            if (edit || editlocked)
            {
                int RelatedEnumId = formsRepo.GetRelatedEnumIdByEnumDescription("formResultId");

                int             formResultId = Convert.ToInt32(Request["formResultId"]);
                int             fileId       = Convert.ToInt32(Request["fileId"]);
                def_FormResults fr           = formsRepo.GetFormResultById(formResultId);

                if (!fr.locked || (fr.locked && editlocked))
                {
                    bool result = FileUploads.DeleteFile(formsRepo, fileId);
                }
            }
        }
Esempio n. 10
0
        public static Dictionary <int, string> GetFormsDictionaryThrow(IFormsRepository formsRepo)
        {
            Dictionary <int, string> forms = null;

            try
            {
                List <string> formIdentifiers = UAS_Business_Functions.GetForms();

                forms = (from i in formsRepo.GetFormsByIdentifiers(formIdentifiers)
                         select i).ToDictionary(i => i.formId, i => i.identifier);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception: GetFormsDictionary: No forms configured for use.");
                throw new Exception("You are not configured to use any SIS forms.");
            }

            return(forms);
        }
        private IQueryable <spSearchGrid_Result> filterSearchResultsByAuthGroups(IQueryable <spSearchGrid_Result> query)
        {
            // Filter by Enterprise, unless Enterprise == 0.
            query = query.Where(srch => srch.ent_id == SessionHelper.LoginStatus.EnterpriseID || SessionHelper.LoginStatus.EnterpriseID == 0);

            if (!UAS_Business_Functions.hasPermission(UAS.Business.PermissionConstants.GROUP_WIDE, UAS.Business.PermissionConstants.ASSMNTS))
            {
                // Filter by Assigned Only
                query = query.Where(srch => srch.assigned == SessionHelper.LoginStatus.UserID);
            }

            if (SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups[0] == 0)
            {
                return(query);
            }
            List <int> authGroups = SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups;

            // Remove any Groups which are not authorized.
            // Check that the sub_id has a value, then compare it to the authGroups, where the authGroup is > -1.
            query = query.Where(srch => srch.sub_id.HasValue && authGroups.Any(ag => ag > -1 && ag == srch.sub_id));

            return(query);
        }
Esempio n. 12
0
        internal static bool ReviewAll()
        {
            string reviewAll = SessionHelper.Read <string>("Review_All");

            if (reviewAll != null)
            {
                if (reviewAll.ToLower().Equals("true"))
                {
                    return(true);
                }
                return(false);
            }

            EntAppConfig reviewAllConfig = UAS_Business_Functions.GetEntAppConfig("REVIEW_ALL", SessionHelper.LoginStatus.EnterpriseID);

            if (reviewAllConfig != null && reviewAllConfig.ConfigValue.ToLower() != "false")
            {
                SessionHelper.Write("Review_All", "true");
                return(true);
            }
            SessionHelper.Write("Review_All", "false");
            return(false);
        }
Esempio n. 13
0
        /// <summary>
        /// To check whether a user is authorized to access the form result id
        /// </summary>
        /// <param name="formresultId"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static bool CACheckUserHasAccesstoFormResult(int formresultId, int userid)
        {
            AuthenticationClient authClient = new AuthenticationClient();

            bool isAuthorizedFrId = false;

            formsEntities dbContext = DataContext.GetDbContext();

            //Will change to constant from constants file after merging the attchments branch
            int enterpriseId = 8;

            List <int> authorizedFormResultIds = new List <int>();

            if (UAS_Business_Functions.hasPermission(PermissionConstants.ASSIGNED, PermissionConstants.ASSMNTS))
            {
                authorizedFormResultIds = dbContext.vFormResultUsers
                                          .Where(fr => (fr.subject == userid) && (fr.EnterpriseID == enterpriseId))
                                          .Select(fr => fr.formResultId)
                                          .ToList();
            }
            else
            {
                //Other
                var groupIds = authClient.GetGroupsInUserPermissions(enterpriseId, SessionHelper.LoginStatus.UserID).GroupBy(x => x.GroupID).Select(x => (int?)x.FirstOrDefault().GroupID);
                authorizedFormResultIds = dbContext.vFormResultUsers
                                          .Where(fr => groupIds.Contains(fr.GroupID) && (fr.EnterpriseID == enterpriseId))
                                          .Select(fr => fr.formResultId)
                                          .ToList();
            }

            if (authorizedFormResultIds.Contains(formresultId))
            {
                isAuthorizedFrId = true;
            }

            return(isAuthorizedFrId);
        }
        public string Login(string userId, string pwrd)
        {
            Debug.WriteLine("Login  userId: " + userId + "     pwrd: " + pwrd);

            LoginInfo loginInfo = new LoginInfo();

            loginInfo.RememberMe = false;

            loginInfo.LoginID  = userId;
            loginInfo.Password = pwrd;

            LoginStatus loginStatus = UAS_Business_Functions.VerifyUser(loginInfo);

            SessionHelper.LoginStatus = loginStatus;
            // SessionHelper.LoginStatus.EnterpriseID = 1;
            // SessionHelper.LoginStatus.GroupID = 3;

            if ((loginStatus.Status == 'A') &&
                (loginStatus.UserID > 0) &&
                // !string.IsNullOrEmpty(loginStatus.PermissionSet)
                (loginStatus.appGroupPermissions.Count > 0)
                )
            {
                loginInfo.IsLoggedIn         = true;
                SessionHelper.IsUserLoggedIn = true;
                SessionHelper.LoginInfo      = loginInfo;
                SessionHelper.LoginStatus    = loginStatus;
                return("You are now logged in.");
            }
            else
            {
                return("Invalid user name or password.");
            }

            // *** RRB 10/29/15 Shouldn't this be returning a boolean or integer so it can be tested for a valid login ??
        }
Esempio n. 15
0
        public static TemplateSisNavMenu getSisNavMenuModel(SessionForm sf, TemplateItems parent, IFormsRepository formsRepo)
        {
            TemplateSisNavMenu result = new TemplateSisNavMenu(formsRepo);

            if (SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets.Count() > 0)
            {
                result.create   = UAS_Business_Functions.hasPermission(SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet, UAS.Business.PermissionConstants.CREATE, UAS.Business.PermissionConstants.ASSMNTS);
                result.unlock   = UAS_Business_Functions.hasPermission(SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet, UAS.Business.PermissionConstants.UNLOCK, UAS.Business.PermissionConstants.ASSMNTS);
                result.delete   = UAS_Business_Functions.hasPermission(SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet, UAS.Business.PermissionConstants.DELETE, UAS.Business.PermissionConstants.ASSMNTS);
                result.archive  = UAS_Business_Functions.hasPermission(SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet, UAS.Business.PermissionConstants.ARCHIVE, UAS.Business.PermissionConstants.ASSMNTS);
                result.undelete = UAS_Business_Functions.hasPermission(SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet, UAS.Business.PermissionConstants.UNDELETE, UAS.Business.PermissionConstants.ASSMNTS);
            }

            result.parent      = parent;
            result.ventureMode = SessionHelper.IsVentureMode;

            result.forms = Assmnts.Business.Forms.GetFormsDictionary(formsRepo);

            try
            {
                def_Forms frm = formsRepo.GetFormById(sf.formId);
                result.assmntTitle    = frm.title;
                result.currentUser    = SessionHelper.LoginInfo.LoginID;
                result.sectionsByPart = new Dictionary <def_Parts, List <def_Sections> >();
                foreach (def_Parts prt in formsRepo.GetFormParts(frm))
                {
                    result.sectionsByPart.Add(prt, formsRepo.GetSectionsInPart(prt));
                }
            }
            catch (Exception xcptn)
            {
                Debug.WriteLine("TemplateMenus getSisNavMenuModel get form, parts, sections exception: " + xcptn.Message);
                throw;
            }

            // LK -- 3/26/15 - #12497 Changed header tracking ID to display tracking ID instead of SIS ID
            // RRB - 9/8/2015 - refactored to handle empty or null sis_track_num
            //          This is all custom SIS code and needs to be moved somewhere else.
            try
            {
                result.trackingNumber = String.Empty;     // Default to blank
                def_ItemVariables trackIV = formsRepo.GetItemVariableByIdentifier("sis_track_num");
                if (trackIV != null)
                {
                    def_ResponseVariables trackRV = formsRepo.GetResponseVariablesByFormResultItemVarId(sf.formResultId, trackIV.itemVariableId);
                    if (trackRV != null)
                    {
                        if (!String.IsNullOrEmpty(trackRV.rspValue))
                        {
                            result.trackingNumber = trackRV.rspValue;
                        }
                    }
                }
            }
            catch (Exception xcptn)
            {
                Debug.WriteLine("SisTemplatesController getSisNavMenuModel trackingNumber exception: " + xcptn.Message);
                throw;
            }

            // BR - added to include the recipient's name on the form when applicable.
            try
            {
                result.recipientName = String.Empty;     // Default to blank
                def_ItemVariables fNameIV = formsRepo.GetItemVariableByIdentifier("sis_cl_first_nm");
                def_ItemVariables lNameIV = formsRepo.GetItemVariableByIdentifier("sis_cl_last_nm");
                if (fNameIV != null)
                {
                    def_ResponseVariables fNameRV = formsRepo.GetResponseVariablesByFormResultItemVarId(sf.formResultId, fNameIV.itemVariableId);
                    if (fNameRV != null)
                    {
                        if (!String.IsNullOrEmpty(fNameRV.rspValue))
                        {
                            result.recipientName = fNameRV.rspValue;
                        }
                    }
                }

                if (lNameIV != null)
                {
                    def_ResponseVariables lNameRV = formsRepo.GetResponseVariablesByFormResultItemVarId(sf.formResultId, lNameIV.itemVariableId);
                    if (lNameRV != null)
                    {
                        if (!String.IsNullOrEmpty(lNameRV.rspValue))
                        {
                            if (!String.IsNullOrEmpty(result.recipientName))
                            {
                                result.recipientName += " ";
                            }
                            result.recipientName += lNameRV.rspValue;
                        }
                    }
                }
            }
            catch (Exception xcptn)
            {
                Debug.WriteLine("TemplateMenus getSisNavMenuModel trackingNumber exception: " + xcptn.Message);
                throw;
            }

            return(result);
        }
        public SearchModel()
        {
            reviewAll = ReviewStatus.ReviewAll();

            permConst = new UAS.Business.PermissionConstants();

            VentureMode = SessionHelper.IsVentureMode;

            timeout = SessionHelper.SessionTotalTimeoutMinutes;

            try
            {
                if (SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets.Count() > 0)
                {
                    string permSet = SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet;
                    edit       = UAS_Business_Functions.hasPermission(permSet, UAS.Business.PermissionConstants.EDIT, UAS.Business.PermissionConstants.ASSMNTS);
                    create     = UAS_Business_Functions.hasPermission(permSet, UAS.Business.PermissionConstants.CREATE, UAS.Business.PermissionConstants.ASSMNTS);
                    unlock     = UAS_Business_Functions.hasPermission(permSet, UAS.Business.PermissionConstants.UNLOCK, UAS.Business.PermissionConstants.ASSMNTS);
                    delete     = UAS_Business_Functions.hasPermission(permSet, UAS.Business.PermissionConstants.DELETE, UAS.Business.PermissionConstants.ASSMNTS);
                    archive    = UAS_Business_Functions.hasPermission(permSet, UAS.Business.PermissionConstants.ARCHIVE, UAS.Business.PermissionConstants.ASSMNTS);
                    undelete   = UAS_Business_Functions.hasPermission(permSet, UAS.Business.PermissionConstants.UNDELETE, UAS.Business.PermissionConstants.ASSMNTS);
                    editLocked = UAS_Business_Functions.hasPermission(permSet, UAS.Business.PermissionConstants.EDIT_LOCKED, UAS.Business.PermissionConstants.ASSMNTS);
                    move       = UAS_Business_Functions.hasPermission(permSet, UAS.Business.PermissionConstants.MOVE, UAS.Business.PermissionConstants.ASSMNTS);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Missing permissoin: " + ex.Message);
            }
            searchPref  = false;
            profilePref = false;
            passPref    = false;

            showSearch = true;

            UASEntities UASContext = DataContext.getUasDbContext();

            numAssmnts = getNumAssmnts(UASContext);

            EntAppConfig patternsForEnterprise = null;

            if (!SessionHelper.IsVentureMode)
            {
                AuthenticationClient webclient = new AuthenticationClient();
                var entConfig = webclient.GetEntAppConfigByEnumAndEnt("PATTERN_CHECK", SessionHelper.LoginStatus.EnterpriseID);
                if (entConfig != null && entConfig.ConfigValue == bool.TrueString)
                {
                    if (
                        UAS_Business_Functions.hasPermission(
                            SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].PermissionSet,
                            PermissionConstants.PATT_CHECK, PermissionConstants.ASSMNTS))
                    {
                        ShowPatternCheck = true;
                    }
                }

                patternsForEnterprise = webclient.GetEntAppConfigByEnumAndEnt("PATTERNS_FOR_ENTERPRISE",
                                                                              SessionHelper.LoginStatus.EnterpriseID);

                if (patternsForEnterprise == null)
                {
                    patternsForEnterprise = webclient.GetEntAppConfigByEnumAndEnt("PATTERNS_FOR_ENTERPRISE", 0);
                }
            }

            //int grpPerm0Id = Assmnts.Infrastructure.SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[0].GroupID;

            //int grpPerm1Id;
            //if (Assmnts.Infrastructure.SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets.Count() > 1)
            //{
            //    grpPerm1Id = Assmnts.Infrastructure.SessionHelper.LoginStatus.appGroupPermissions[0].groupPermissionSets[1].GroupID;
            //}
            //else
            //{
            //    grpPerm1Id = grpPerm0Id;
            //}

            /* **************************************************************
             * The statements below need to be replaced with pulling a variable
             * from the web.config file.
             * 'VentureMode'.
             *
             * Done 2/13/15 LK
             * Move up in function so can use to get timeout value if neccessary
             * 5/15/15 LK #12554
             *
             * **************************************************************
             */
            //if (!String.IsNullOrEmpty(strVentureMode))
            //{
            //    OfflineMode = Convert.ToBoolean(strVentureMode);
            //}

            /* string currentPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
             * OfflineMode = (currentPath.ToLower().Contains("venture")) ? true : false;
             */
            ShowAllAssessmentsForRecipient = false;  // Do not show all assessments for Recipient by default.

            DetailSearchCriteria = new SearchCriteria();

            DetailSearchCriteria.InterviewerList = new List <SelectListItem>();
            DetailSearchCriteria.EnterpriseList  = new List <SelectListItem>();
            DetailSearchCriteria.GroupList       = new List <SelectListItem>();
            DetailSearchCriteria.PatternList     = new List <SelectListItem>();

            DetailSearchCriteria.SelectedInterviewers = new List <string>();
            DetailSearchCriteria.SelectedEnts         = new List <int>();
            DetailSearchCriteria.SelectedGroups       = new List <int>();

            List <string>         interviewers = new List <string>();
            List <uas_Group>      groups       = new List <uas_Group>();
            List <uas_Enterprise> ents         = new List <uas_Enterprise>();

            int entId = Assmnts.Infrastructure.SessionHelper.LoginStatus.EnterpriseID;

            if (entId == 0)
            {
                interviewers = (from i in UASContext.uas_User
                                select i.LoginID).ToList();

                groups = (from g in UASContext.uas_Group
                          select g).ToList();

                ents = (from e in UASContext.uas_Enterprise
                        select e).ToList();
            }
            else
            {
                interviewers = (from i in UASContext.uas_User
                                where i.EnterpriseID == entId
                                select i.LoginID).ToList();

                ents = (from e in UASContext.uas_Enterprise
                        where e.EnterpriseID == entId
                        select e).ToList();


                //if (grpPerm0Id == 0)
                //{
                //    using (var UASContext = new SISEntities())
                //    {
                //        groups = (from g in UASContext.uas_Group
                //                  where g.EnterpriseID == entId
                //                  select g).ToList();
                //    }
                //}
                //else
                //{

                try
                {
                    if (SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups[0] == 0)
                    {
                        groups = UASContext.uas_Group.Where(g => g.EnterpriseID == entId).ToList();

                        //auth.GetGroupsByEnterprise(auth.GetEnterprise(entId)).Select(h => UASContext.uas_Group.FirstOrDefault(g => g.GroupID == h.GroupID)).ToList();
                    }
                    else
                    {
                        AppGroupPermissions agp = SessionHelper.LoginStatus.appGroupPermissions[0];
                        groups = UASContext.uas_Group.Where(g => agp.authorizedGroups.Contains(g.GroupID)).ToList();


                        //auth.GetChildGroups(entId, SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups[0])
                        //.Where(id => id > -1)
                        //.Select(groupId => UASContext.uas_Group.FirstOrDefault(g => g.GroupID == groupId)).ToList();
                        //groups = (from g in UASContext.uas_Group
                        //          where g.EnterpriseID == entId
                        //          && (g.GroupID == grpPerm0Id
                        //            || g.GroupID == grpPerm1Id)
                        //          select g).ToList();
                    }
                }
                //}
                catch (Exception ex) {
                    Debug.WriteLine(ex.Message);
                }
            }

            foreach (string interviewer in interviewers)
            {
                SelectListItem interviewerListItem = new SelectListItem()
                {
                    Text  = interviewer,
                    Value = interviewer
                };
                DetailSearchCriteria.InterviewerList.Add(interviewerListItem);
            }

            foreach (uas_Group group in groups)
            {
                SelectListItem groupListItem = new SelectListItem()
                {
                    Text  = group.GroupName,
                    Value = group.GroupID.ToString()
                };
                DetailSearchCriteria.GroupList.Add(groupListItem);
            }

            bool admin = false;

            foreach (int grp in SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups)
            {
                if (grp == 0)
                {
                    admin = true;
                    break;
                }
            }

            foreach (uas_Enterprise ent in ents)
            {
                SelectListItem entListItem = new SelectListItem()
                {
                    Text  = ent.EnterpriseName,
                    Value = ent.EnterpriseID.ToString()
                };

                // if user is enterprise admin, show enterprise
                if (SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups[0] == 0 || admin)
                {
                    DetailSearchCriteria.EnterpriseList.Add(entListItem);
                }
            }

            // add patterns
            if (!SessionHelper.IsVentureMode && patternsForEnterprise.ConfigValue.Contains("1"))
            {
                DetailSearchCriteria.PatternList.Add(new SelectListItem()
                {
                    Value = "1",
                    Text  = "1. Important To, Important For Utilization Check"
                });
            }
            if (!SessionHelper.IsVentureMode && patternsForEnterprise.ConfigValue.Contains("2"))
            {
                DetailSearchCriteria.PatternList.Add(new SelectListItem()
                {
                    Value = "2",
                    Text  = "2. Learning Job Skills Typical Person Standard Check"
                });
            }

            if (!SessionHelper.IsVentureMode && patternsForEnterprise.ConfigValue.Contains("3"))
            {
                DetailSearchCriteria.PatternList.Add(new SelectListItem()
                {
                    Value = "3",
                    Text  = "3. Transportation Consistency Check"
                });
            }

            if (!SessionHelper.IsVentureMode && patternsForEnterprise.ConfigValue.Contains("4"))
            {
                DetailSearchCriteria.PatternList.Add(new SelectListItem()
                {
                    Value = "4",
                    Text  = "4. Relationship \"Typical Person Standard\" Check"
                });
            }

            if (!SessionHelper.IsVentureMode && patternsForEnterprise.ConfigValue.Contains("5"))
            {
                DetailSearchCriteria.PatternList.Add(new SelectListItem()
                {
                    Value = "5",
                    Text  = "5. Sexual Aggression Community Safety Consistency Check"
                });
            }

            if (!SessionHelper.IsVentureMode && patternsForEnterprise.ConfigValue.Contains("6"))
            {
                DetailSearchCriteria.PatternList.Add(new SelectListItem()
                {
                    Value = "6",
                    Text  = "6. Ambulation Consistency Check"
                });
            }
        }
        public string VerifyUser(string userId, string pwrd, string entId, string grpId)
        {
            Debug.WriteLine("Verify userId: " + userId + "     pwrd: " + pwrd);
            int iEntId, iGrpId;

            try
            {
                iEntId = Int32.Parse(entId);
            }
            catch
            {
                return("Enterprise ID must be a number.");
            }

            try
            {
                iGrpId = Int32.Parse(grpId);
            }
            catch
            {
                return("Group ID must be a number.");
            }

            bool      groupCorrect = false, entCorrect = false;
            LoginInfo loginInfo = new LoginInfo();

            loginInfo.RememberMe = false;

            loginInfo.LoginID  = userId;
            loginInfo.Password = pwrd;

            LoginStatus loginStatus = UAS_Business_Functions.VerifyUser(loginInfo);

            if (loginStatus != null)
            {
                if (loginStatus.EnterpriseID == iEntId)
                {
                    entCorrect = true;
                }

                if (loginStatus.appGroupPermissions != null &&
                    loginStatus.appGroupPermissions.Count > 0 &&
                    loginStatus.appGroupPermissions[0].groupPermissionSets.Count > 0 &&
                    loginStatus.appGroupPermissions[0].groupPermissionSets[0].GroupID == iGrpId)
                {
                    groupCorrect = true;
                }
            }

            if ((loginStatus != null) && (loginStatus.Status == 'A') &&
                (loginStatus.UserID > 0) &&
                // !string.IsNullOrEmpty(loginStatus.PermissionSet)
                (loginStatus.appGroupPermissions.Count > 0) &&
                entCorrect &&
                groupCorrect
                )
            {
                using (var context = DataContext.getUasDbContext())
                {
                    string enterprise = context.uas_Enterprise.Where(e => e.EnterpriseID == loginStatus.EnterpriseID).Select(e => e.EnterpriseDescription).SingleOrDefault();

                    return("The User Login: "******" is valid for " + loginStatus.FirstName + " " + loginStatus.LastName + "  Enterprise: " + enterprise);
                }
            }
            else
            {
                if (loginStatus.appGroupPermissions != null)
                {
                    if (loginStatus.appGroupPermissions.Count == 0 || loginStatus.appGroupPermissions[0].ApplicationID != UAS.Business.Constants.APPLICATIONID || loginStatus.appGroupPermissions[0].groupPermissionSets.Count == 0)
                    {
                        return("User not authorized for this application.");
                    }

                    if (!groupCorrect || !entCorrect)
                    {
                        return("User is not authorized for the Enterprise or Group.");
                    }
                }

                return("Invalid UserId and/or password");
            }
        }
        public string GetHtmlForColumn(int columnIndex)
        {
            switch (columnIndex)
            {
            case 0:     //ramsellId / MemberId
                def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultIdentifier(vfru.formResultId, "C1_MemberIdentifier") ?? formsRepo.GetResponseVariablesByFormResultIdentifier(vfru.formResultId, "ADAP_D9_Ramsell");
                string ramsellId         = (rv == null) ? null : rv.rspValue;
                string ramsellIdDisplayText;
                if ((ramsellId == null) || String.IsNullOrWhiteSpace(ramsellId))
                {
                    if (vfru.EnterpriseID == 8)
                    {
                        ramsellIdDisplayText = @Resources.AdapPortal.NoId;
                    }
                    else
                    {
                        ramsellIdDisplayText = @Resources.AdapPortal.NoRamsellId;
                    }
                }
                else
                {
                    ramsellIdDisplayText = ramsellId;
                }
                if (UAS_Business_Functions.hasPermission(PermissionConstants.EDIT, PermissionConstants.ASSMNTS))
                {
                    return(isHistorical ? ramsellIdDisplayText : "<a href=\"/ADAP/ToTemplate?formResultId=" + Convert.ToString(vfru.formResultId) + "&Update=Y\">" + ramsellIdDisplayText + "</a>");
                }
                else
                {
                    return(ramsellIdDisplayText);
                }

            case 1:     //FirstName
                return(vfru.FirstName);

            case 2:     //Last name
                return(vfru.LastName);

            case 3:     //DOB
                return(vfru.DOB.HasValue ? vfru.DOB.Value.ToString("MM/dd/yyyy") : String.Empty);

            case 4:     //Status
                def_StatusMaster statusMaster = formsRepo.GetStatusMasterByFormId(vfru.formId);
                int statusMasterId            = statusMaster == null ? 1 : statusMaster.statusMasterId;

                string statusDisplayText = formsRepo.GetStatusTextByDetailSortOrder(statusMasterId, vfru.formStatus).displayText;
                return(isHistorical ? statusDisplayText : "<a href=\"/ADAP/UpdateStatus?formResultId=" + Convert.ToString(vfru.formResultId) + "\">" + statusDisplayText + "</a>");

            case 5:     //Status changed
                return(statusChangeDate == null ? String.Empty : statusChangeDate.ToString());

            case 6:     //Next Recert
                DateTime?nextRecertDate = GetRecert(formsRepo, vfru, allVfrus);
                return(nextRecertDate.HasValue ? nextRecertDate.Value.ToString("MMMM yyyy") : "None Pending");

            case 7:     //type
                var form = formsRepo.GetFormByIdentifier(formIdentifier).title;
                return("<div class=\"form-type-text\" data-formIdentifier=\"" + formIdentifier + "\">" + form + "</div>");

            case 8:     //group
                if (vfru.EnterpriseID == 8)
                {
                    string groupDesc = string.Empty;
                    var    context   = DataContext.getUasDbContext();
                    var    group     = (from g in context.uas_Group
                                        where g.GroupID == vfru.GroupID
                                        select g).FirstOrDefault();
                    groupDesc = group.GroupDescription;
                    return(isHistorical ? vfru.GroupName + " - " + groupDesc : "<a href=\"/ADAP/UpdateTeam?formId=" + Convert.ToString(vfru.formResultId) + "\">" + vfru.GroupName + " - " + groupDesc + "</a>");
                }
                else
                {
                    return(isHistorical ? vfru.GroupName : "<a href=\"/ADAP/UpdateTeam?formId=" + Convert.ToString(vfru.formResultId) + "\">" + vfru.GroupName + "</a>");
                }

            case 9:     //contact info
                return
                    ("<div class=\"row\">" +
                     "<div class=\"col-md-12 text-center\">" +
                     "<a href=\"#\" data-toggle=\"modal\" data-target=\"#contactsModal\" data-formresultid=\"" + Convert.ToString(vfru.formResultId) + "\">" +
                     "Contact" +
                     "</a>" +
                     "<span class=\"text-divider\">|</span>" +
                     "<a href=\"#\" data-toggle=\"modal\" data-target=\"#cmmtModal\" data-userid=\"" + vfru.subject.ToString() + "\" data-formresultid=\"" + Convert.ToString(vfru.formResultId) + "\">" +
                     "Comments" +
                     "</a>" +
                     "<span class=\"text-divider\">|</span>" +
                     "<a href=\"/ADAP/StatusHistory?formResultId=" + Convert.ToString(vfru.formResultId) + "\">" +
                     "History" +
                     "</a>" +
                     "</div>" +
                     "</div>");

            case 10:     //print button
                if (isHistorical)
                {
                    if (historicalSnapshot != null)
                    {
                        return("<a class=\"glyphicon glyphicon-print text-primary\" href=\"/Search/DownloadFile?fileId=" + historicalSnapshot.FileId + "&fileDownloadName=snapshot.pdf\"></a>");
                    }
                    else
                    {
                        return("N/A");
                    }
                }
                else
                {
                    return("<a class=\"glyphicon glyphicon-print text-primary\" href=\"../COADAP/BuildPDFReport?formResultId=" + Convert.ToString(vfru.formResultId) + "\"></a>");
                }

            case 11:     //subject (user id number for applicant)
                return(Convert.ToString(vfru.subject));

            case 12:     //upload and download attachments
                if (isHistorical)
                {
                    return(String.Empty);
                }
                else
                {
                    int frId = vfru.formResultId;
                    return("<div>"
                           + "<div id=\"attachment1" + frId + "\">"
                           + "<form class=\"uploadForm\" action=\"/Search/UploadFile\" method=\"post\" enctype=\"multipart/form-data\">"
                           + "<input type=\"hidden\" name=\"formResultId\" value=\"" + frId + "\" />"
                           + "<input type=\"file\" id=\"file" + frId + "\" name=\"file" + frId + "\">"
                           + "<a href=\"#\" onclick=\"$('#Upload" + frId + "').click()\">Upload</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" class=\"viewFiles\" id=\"view" + frId + "\" onclick=\"downloadAttach(" + frId + ")\" hidden=\"hidden\">View Files</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<input type=\"submit\" id=\"Upload" + frId + "\" value=\"Upload\" hidden=\"hidden\" />"
                           + "</form>"
                           + "</div>"
                           + "<div id=\"attachment2" + frId + "\" hidden=\"hidden\">"
                           + "<span id=\"dwnldDDL" + frId + "\" class=\"AttachDDL" + frId + "\" style=\"min-width:10px\"></span> "
                           + "<a href=\"#\" onclick=\"downloadFile(" + frId + ")\">Download</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" onclick=\"deleteAttach(" + frId + ")\">Delete Files</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" onclick=\"cancelAttach(" + frId + ")\">Cancel</a>"
                           + "</div>"
                           + "<div id=\"attachment3" + frId + "\" hidden=\"hidden\">"
                           + "<span id=\"dltDDL" + frId + "\" class=\"AttachDDL" + frId + "\"></span> "
                           + "<a href=\"#\" onclick=\"deleteFile(" + frId + ")\">Delete</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" onclick=\"downloadAttach(" + frId + ")\">Cancel</a>"
                           + "</div>"
                           + "</div>");
                }

            default:
                throw new Exception("invalid column index: " + columnIndex);
            }
        }
Esempio n. 19
0
        //called by all report-building methods
        public FileContentResult BottomBuildReport(int formResultId, SisPdfReportOptions options)
        {
            //construct a report object, containing instructions for building the pdf

            string       logoPath = HostingEnvironment.MapPath("/Content/images/aaidd_logo_full.jpg");
            string       outpath  = HostingEnvironment.MapPath("/Content/report_" + System.DateTime.Now.Ticks + ".pdf");
            SisPdfReport report;

            def_FormResults fr = formsRepo.GetFormResultById(formResultId);

            string entLogoPath = String.Empty;

            try
            {
                // custom enterprise logo is located at /websiteroot/Enterprise/EnterpriseID/logo-left.png
                entLogoPath = Path.Combine(ConfigurationManager.AppSettings["EnterpriseDir"], fr.EnterpriseID.ToString()) + "\\logo-left.png";
            }
            catch (Exception ex)
            {
                Debug.WriteLine("SisPdfRpts: BottomBuildReport: Unable to load custom logo for enterprise. Message: " + ex.Message);
            }
            if (System.IO.File.Exists(entLogoPath))
            {
                logoPath = entLogoPath;
            }
            else
            {
                logoPath = HostingEnvironment.MapPath("/Content/images/aaidd_logo_full.jpg");
            }

            try
            {
                // LK 3/26/2015 #12436 Added check on authorization for group to a central method (hasAccess) and used here

                if (!UAS_Business_Functions.hasAccess(fr))
                {
                    throw new Exception("You do not have access to this assessment record.");
                }

                //build report or reject, based on options and securityset
                if (options.type == SisPdfReportOptions.ReportType.Family)
                {
                    if (!UAS_Business_Functions.hasPermission(PermissionConstants.FAMREP, "reportexp"))//String.IsNullOrEmpty(reportexpSet) || reportexpSet[0] != 'Y')
                    {
                        throw new Exception("You do not have permission to build a family-friendly report");
                    }
                    report = new SisFamilyReport(formsRepo, formResultId, options, logoPath, outpath);
                }
                else if (options.type == SisPdfReportOptions.ReportType.Generic)
                {
                    if (!UAS_Business_Functions.hasPermission(PermissionConstants.GENREP, "reportexp"))//String.IsNullOrEmpty(reportexpSet) || (reportexpSet[1] != 'Y') )
                    {
                        throw new Exception("You do not have permission to build a generic report");
                    }
                    report = new SisGenericReport(formsRepo, formResultId, options, logoPath, outpath);
                }
                else
                {
                    if (!UAS_Business_Functions.hasPermission(PermissionConstants.EXPORT, "reportexp"))//String.IsNullOrEmpty(reportexpSet) || reportexpSet[2] != 'Y')
                    {
                        throw new Exception("You do not have permission to build a default report");
                    }
                    report = new SisShortLongReport(formsRepo, formResultId, options, logoPath, outpath);
                }
            }
            catch (Exception xcptn)
            {
                string msg = "Build Report constructor failed.  Exception: " + xcptn.Message;
                return(new FileContentResult(Encoding.ASCII.GetBytes(msg), "text/html"));
            }

            //build and save the pdf
            //try
            //{
            report.BuildReport();
            //}
            //catch (Exception xcptn)
            //{
            //    string msg = "BuildReport process failed.  Exception: " + xcptn.Message;
            //    return new FileContentResult(Encoding.ASCII.GetBytes(msg), "text/html");
            //}

            FileContentResult result;

            try
            {
                Debug.WriteLine("   SisPdfRptsController outpath:" + outpath);
                report.outputToFile();

                //build a descriptive filename
                string sDate     = DateTime.Now.ToString("MM-dd-yyyy");
                string lastName  = getResponseStringOrEmpty(formResultId, "sis_cl_last_nm");
                string firstName = getResponseStringOrEmpty(formResultId, "sis_cl_first_nm");
                string filename  = String.Format("{0}_{1}_{2}_{3}.pdf", lastName, firstName, formResultId, sDate);

                //build the result object containing the file contents
                result = File(System.IO.File.ReadAllBytes(outpath), "application/pdf", filename);

                //delete the original file
                System.IO.File.Delete(outpath);
            }
            catch (Exception xcptn)
            {
                string msg = "Build Report output failed.  Exception: " + xcptn.Message;
                result = new FileContentResult(Encoding.ASCII.GetBytes(msg), "text/html");
            }

            return(result);
        }
Esempio n. 20
0
        public string GetHtmlForColumn(int columnIndex)
        {
            Uri userAdminUri = new Uri(System.Configuration.ConfigurationManager.AppSettings["UASAdminURL"]);

            switch (columnIndex)
            {
            case 0:     //ramsellId / MemberId
                var    ramsellId = vfru.adap_id;
                string ramsellIdDisplayText;
                if ((ramsellId == null) || String.IsNullOrWhiteSpace(ramsellId))
                {
                    ramsellIdDisplayText = @Resources.AdapPortal.NoId;
                }
                else
                {
                    ramsellIdDisplayText = ramsellId;
                }
                if (UAS_Business_Functions.hasPermission(PermissionConstants.EDIT, PermissionConstants.ASSMNTS))
                {
                    return(isHistorical ? ramsellIdDisplayText : "<a href=\"/ADAP/ToTemplate?formResultId=" + Convert.ToString(vfru.formResultId) + "&Update=Y\">" + ramsellIdDisplayText + "</a>");
                }
                else
                {
                    return(ramsellIdDisplayText);
                }

            case 1:     //FirstName

                string url          = new Uri(userAdminUri, String.Format("Site/Limited/simple_User?UserID={0}", vfru.subject)).ToString();
                string uasEditFirst = "<a target='_blank' href='" + url + "' >" + vfru.FirstName + "  </a>";
                return(uasEditFirst);

            case 2:     //Last name

                string urlEdit     = new Uri(userAdminUri, String.Format("Site/Limited/simple_User?UserID={0}", vfru.subject)).ToString();
                string uasEditLast = "<a target='_blank' href='" + urlEdit + "' >" + vfru.LastName + "  </a>";
                return(uasEditLast);


            case 3:     //Status
                def_StatusMaster statusMaster = formsRepo.GetStatusMasterByFormId(vfru.formId);
                int    statusMasterId         = statusMaster == null ? 1 : statusMaster.statusMasterId;
                var    status            = formsRepo.GetStatusTextByDetailSortOrder(statusMasterId, vfru.formStatus);
                var    permChangeStatus  = UAS_Business_Functions.hasPermission(PermissionConstants.CNGE_STATUS, PermissionConstants.ASSMNTS);
                string statusDisplayText = status != null ? status.displayText : "In Progress";
                return((isHistorical || !permChangeStatus) ? statusDisplayText : "<a href=\"Javascript:StatusRedirect('/AdapCa/UpdateStatus'," + Convert.ToString(vfru.formResultId) + ")\">" + statusDisplayText + "</a>");

            case 4:     //Status changed
                return(statusChangeDate == null ? String.Empty : statusChangeDate.ToString());

            case 5:     // Elibility End Date
                DateTime?eligibilityEndDate = vfru.EligibilityEndDate;
                string   endDate            = "None Pending";
                if (eligibilityEndDate.HasValue)
                {
                    endDate = eligibilityEndDate.Value.ToShortDateString();
                }

                IEnumerable <def_FormResults> frElgList = formsRepo.GetFormResultsByFormSubject(18, vfru.subject);

                if (!frElgList.Any())
                {
                    // create an Eligibility Dashboard
                    AdapCaController adapCa = new AdapCaController(formsRepo);
                    adapCa.CreateElgibility(vfru.formResultId);
                    frElgList = formsRepo.GetFormResultsByFormSubject(18, vfru.subject);
                }

                var frmElgResultId = frElgList.FirstOrDefault().formResultId;
                var endDateLink    = "<a href=\"/ADAP/ToTemplate?formResultId=" + Convert.ToString(frmElgResultId) + "&Update=Y\">"
                                     + endDate + "</a>";

                return(endDateLink);

            case 6:     //Next Recert
                def_ResponseVariables rvSixMonth = formsRepo.GetResponseVariablesBySubjectForm(vfru.subject.Value, 18, "C1_Next6MonthRecertDate");
                DateTime nextRecertDate;
                string   recertDate = "None Pending";
                if (rvSixMonth != null && DateTime.TryParse(rvSixMonth.rspValue, out nextRecertDate))
                {
                    recertDate = nextRecertDate.ToString("MMMM yyyy");
                }
                return(recertDate);

            case 7:
                def_ResponseVariables rvAnuual = formsRepo.GetResponseVariablesBySubjectForm(vfru.subject.Value, 18, "C1_NextAnnualRecertDate");
                DateTime annualDate;
                string   annualDateStr = "None Pending";
                if (rvAnuual != null && DateTime.TryParse(rvAnuual.rspValue, out annualDate))
                {
                    annualDateStr = annualDate.ToString("MMMM yyyy");
                }
                return(annualDateStr);

            case 8:     //type
                var form        = formsRepo.GetFormByIdentifier(formIdentifier).title;
                var formVariant = vfru.formVariant;
                if (!string.IsNullOrWhiteSpace(formVariant))
                {
                    form = formVariant;
                }
                return("<div class=\"form-type-text\" data-formIdentifier=\"" + formIdentifier + "\">" + form + "</div>");

            case 9:     //group
                var permMove = UAS_Business_Functions.hasPermission(PermissionConstants.MOVE, PermissionConstants.ASSMNTS);
                if (vfru.EnterpriseID == 8)
                {
                    string groupDesc = string.Empty;
                    var    context   = DataContext.getUasDbContext();
                    var    group     = (from g in context.uas_Group
                                        where g.GroupID == vfru.GroupID
                                        select g).FirstOrDefault();
                    groupDesc = group.GroupDescription;
                    return((isHistorical || !permMove) ? vfru.GroupName + " - " + groupDesc : "<a href=\"/ADAP/UpdateTeam?formId=" + Convert.ToString(vfru.formResultId) + "\">" + vfru.GroupName + " - " + groupDesc + "</a>");
                }
                else
                {
                    return(isHistorical ? vfru.GroupName : "<a href=\"/ADAP/UpdateTeam?formId=" + Convert.ToString(vfru.formResultId) + "\">" + vfru.GroupName + "</a>");
                }

            case 10:     //contact info
                return
                    ("<div class=\"row\">" +
                     "<div class=\"col-md-12 text-center\">" +
                     "<a href=\"#\" data-toggle=\"modal\" data-target=\"#contactsModal\" data-formresultid=\"" + Convert.ToString(vfru.formResultId) + "\">" +
                     "Contact" +
                     "</a>" +
                     "<span class=\"text-divider\">|</span>" +
                     "<a href=\"#\" data-toggle=\"modal\" data-target=\"#cmmtModal\" data-userid=\"" + vfru.subject.ToString() + "\" data-formresultid=\"" + Convert.ToString(vfru.formResultId) + "\">" +
                     "Comments" +
                     "</a>" +
                     "<span class=\"text-divider\">|</span>" +
                     "<a href=\"Javascript:StatusRedirect('/AdapCa/StatusHistory'," + Convert.ToString(vfru.formResultId) + ")\">" +
                     "History" +
                     "</a>" +
                     "<br/><br/>" +
                     "<a href=\"Javascript:clientHandoutRedirect('/Results/ClientHandout'," + Convert.ToString(vfru.formResultId) + ")\">" +
                     "Client Handout" +
                     "</a>" +
                     "</div>" +
                     "</div>");

            case 11:     //DOB
                return(vfru.DOB.HasValue ? vfru.DOB.Value.ToString("MM/dd/yyyy") : String.Empty);

            case 12:     //print button
                if (isHistorical)
                {
                    if (historicalSnapshot != null)
                    {
                        return("<a class=\"glyphicon glyphicon-print text-primary\" href=\"/Search/DownloadFile?fileId=" + historicalSnapshot.FileId + "&fileDownloadName=snapshot.pdf\"></a>");
                    }
                    else
                    {
                        return("N/A");
                    }
                }
                else
                {
                    return("<a class=\"glyphicon glyphicon-print text-primary\" href=\"../COADAP/BuildPDFReport?formResultId=" + Convert.ToString(vfru.formResultId) + "\"></a>");
                }

            case 13:     //subject (user id number for applicant)
                return(Convert.ToString(vfru.subject));

            case 14:     //upload and download attachments
                if (isHistorical)
                {
                    return(String.Empty);
                }
                else
                {
                    int frId = vfru.formResultId;
                    return("<div>"
                           + "<div id=\"attachment1" + frId + "\">"
                           + "<form class=\"uploadForm\" action=\"/Search/UploadFile\" method=\"post\" enctype=\"multipart/form-data\">"
                           + "<input type=\"hidden\" name=\"formResultId\" value=\"" + frId + "\" />"
                           + "<input type=\"file\" id=\"file" + frId + "\" name=\"file" + frId + "\">"
                           + "<a href=\"#\" onclick=\"$('#Upload" + frId + "').click()\">Upload</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" class=\"viewFiles\" id=\"view" + frId + "\" onclick=\"downloadAttach(" + frId + ")\" hidden=\"hidden\">View Files</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<input type=\"submit\" id=\"Upload" + frId + "\" value=\"Upload\" hidden=\"hidden\" />"
                           + "</form>"
                           + "</div>"
                           + "<div id=\"attachment2" + frId + "\" hidden=\"hidden\">"
                           + "<span id=\"dwnldDDL" + frId + "\" class=\"AttachDDL" + frId + "\" style=\"min-width:10px\"></span> "
                           + "<a href=\"#\" onclick=\"downloadFile(" + frId + ")\">Download</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" onclick=\"deleteAttach(" + frId + ")\">Delete Files</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" onclick=\"cancelAttach(" + frId + ")\">Cancel</a>"
                           + "</div>"
                           + "<div id=\"attachment3" + frId + "\" hidden=\"hidden\">"
                           + "<span id=\"dltDDL" + frId + "\" class=\"AttachDDL" + frId + "\"></span> "
                           + "<a href=\"#\" onclick=\"deleteFile(" + frId + ")\">Delete</a>"
                           + "&nbsp;&nbsp;&nbsp;"
                           + "<a href=\"#\" onclick=\"downloadAttach(" + frId + ")\">Cancel</a>"
                           + "</div>"
                           + "</div>");
                }

            default:
                throw new Exception("invalid column index: " + columnIndex);
            }
        }
        private List <int> GetAuthorizedFormResultIds(IFormsSql formsSql)
        {
            DataTable dtFormResults = new DataTable();

            for (int j = 0; j < SessionHelper.LoginStatus.appGroupPermissions.Count; j++)
            {
                StringBuilder stringBuilder = new StringBuilder("SELECT formResultId FROM def_FormResults");

                stringBuilder.Append(" WHERE EnterpriseID = " + SessionHelper.LoginStatus.EnterpriseID);
                if (!SessionHelper.LoginStatus.appGroupPermissions[j].authorizedGroups.Contains(0))
                {
                    stringBuilder.Append(" AND (");

                    for (int i = 0; i < SessionHelper.LoginStatus.appGroupPermissions[j].authorizedGroups.Count; i++)
                    {
                        stringBuilder.Append("GroupID = " + SessionHelper.LoginStatus.appGroupPermissions[j].authorizedGroups[i]);

                        if (i < SessionHelper.LoginStatus.appGroupPermissions[j].authorizedGroups.Count - 1)
                        {
                            stringBuilder.Append(" OR ");
                        }
                    }
                    stringBuilder.Append(")");
                }

                if (!UAS_Business_Functions.hasPermission(PermissionConstants.GROUP_WIDE, j, PermissionConstants.ASSMNTS))
                {
                    stringBuilder.Append(" AND " + " assigned = " + SessionHelper.LoginStatus.UserID);
                }

                stringBuilder.Append(" AND formStatus < " + (int)FormResults_formStatus.COMPLETED);

                String qry = stringBuilder.ToString();

                try
                {
                    SqlConnection sqlConn = new SqlConnection(formsSql.GetConnectionString());
                    sqlConn.Open();
                    SqlCommand cmd = new SqlCommand(qry, sqlConn);

                    if (j == 0)
                    {
                        dtFormResults.Load(cmd.ExecuteReader());
                    }
                    else
                    {
                        DataTable dt = new DataTable();
                        dt.Load(cmd.ExecuteReader());
                        dtFormResults.Merge(dt);
                    }
                    sqlConn.Close();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("GetAuthorizedFormResultIds: " + ex.Message);
                    return(null);
                }
            }

            List <int> formResultIds = (from fr in dtFormResults.Select()
                                        select fr.Field <int>(0)).ToList();

            return(formResultIds);
        }
        public ActionResult Template(int?sectionIdOverride = null, List <string> validationMessages = null)
        {
            mLogger.Debug("* * *  ResultsController:Template method  * * *");

            if (!SessionHelper.IsUserLoggedIn)
            {
                return(RedirectToAction("Index", "Account", null));
            }

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

            if (Session["form"] != null && !string.IsNullOrWhiteSpace(Session["form"].ToString()))
            {
                int formId = SessionHelper.SessionForm.formId;
                formId = int.Parse(Session["form"].ToString());
                def_Forms frm = formsRepo.GetFormById(formId);
                SessionHelper.SessionForm.formId         = formId;
                SessionHelper.SessionForm.formIdentifier = frm.identifier;
                var oldFrmResult = formsRepo.GetFormResultById(SessionHelper.SessionForm.formResultId);
                var newFrmResult = formsRepo.GetFormResultsByFormSubject(formId, oldFrmResult.subject).OrderByDescending(f => f.dateUpdated);
                if (newFrmResult.Any())
                {
                    // use most recent form result
                    SessionHelper.SessionForm.formResultId = newFrmResult.FirstOrDefault().formResultId;
                }

                Session["form"] = null;
                int part = int.Parse(Session["part"].ToString());
                SessionHelper.SessionForm.partId = part;
            }

            SessionForm sessionForm = SessionHelper.SessionForm;

            // set language ID in session based on meta-data (default to English) + other session vars
            CultureInfo   ci      = Thread.CurrentThread.CurrentUICulture;
            string        isoName = (ci == null) ? "en" : ci.TwoLetterISOLanguageName.ToLower();
            def_Languages lang    = formsRepo.GetLanguageByTwoLetterISOName(isoName);

            if (lang == null)
            {
                throw new Exception("could not find def_Language entry for iso code \"" + isoName + "\"");
            }
            else
            {
                sessionForm.langId = lang.langId;
            }



            // This is the master or top level sectionId, there can be mulitple subSections below this section.
            // The subSections will be in the SectionItems
            string sectionId = (sectionIdOverride == null) ? Request["sectionId"] as string : sectionIdOverride.ToString();

            mLogger.Debug("* * *  Results Template sectionId: {0}", sectionId);
            Session["section"] = sectionId;
            def_Sections sctn = formsRepo.GetSectionById(Convert.ToInt32(sectionId));

            sessionForm.sectionId = sctn.sectionId;

            // Create a new Assessments Model Template (AMT) that is used by the .cshtml template (Razor code)
            TemplateItems amt;

            if (sctn.href != null && (sctn.href.EndsWith("spprtNeedsScale.cshtml") || sctn.href.EndsWith("excptnlMedSpprtNeed.cshtml")))
            {
                amt = new QuestionListForm();
            }
            else
            {
                amt = new GeneralForm();
            }


            amt.thisSection   = sctn;
            amt.thisSectionId = sctn.sectionId;
            amt.formsRepo     = formsRepo;
            amt.formResultId  = sessionForm.formResultId;
            amt.currentUser   = SessionHelper.LoginInfo.LoginID;

            //amt.items = new List<def_Items>();
            amt.subSections = new List <def_Sections>();
            amt.fldLabels   = new Dictionary <string, string>();
            amt.itmPrompts  = new Dictionary <string, string>();
            amt.rspValues   = new Dictionary <string, string>();
            mLogger.Debug("* * *  ResultsController:Template sessionForm.formResultId: {0}", sessionForm.formResultId);
            def_FormResults fr = formsRepo.GetFormResultById(sessionForm.formResultId);

            mLogger.Debug("* * *  ResultsController:Template fr.formResultId: {0}", fr.formResultId);

            if (fr != null)
            {
                if (fr.formStatus == (byte)FormResults_formStatus.IN_PROGRESS)
                {
                    amt.inProgress = true;
                }
                if (fr.formStatus == (byte)FormResults_formStatus.NEW)
                {
                    amt.newAssmnt = true;
                }
            }



            //Start: added for enhancement Bug 13663 to be refactored

            amt.updatedDate = fr.dateUpdated;

            amt.formStatus = fr.formStatus;

            int statusMasterId = 0;

            def_StatusMaster statusMaster = formsRepo.GetStatusMasterByFormId(fr.formId);

            if (statusMaster != null)
            {
                statusMasterId = statusMaster.statusMasterId;

                def_StatusDetail statusdetails = formsRepo.GetStatusDetailBySortOrder(statusMasterId, fr.formStatus);

                amt.formSatusText = statusdetails.def_StatusText
                                    .Where(sd => sd.EnterpriseID == 8 && sd.langId == 1)
                                    .Select(z => z.displayText)
                                    .FirstOrDefault();
            }
            else
            {
                //This is used as currently we are showing In Progress for all items which do not have status
                amt.formSatusText = "In Progress";
            }

            amt.CanUserChangeStatus = true;

            if (UAS_Business_Functions.hasPermission(PermissionConstants.ASSIGNED, PermissionConstants.ASSMNTS))
            {
                amt.CanUserChangeStatus = false;
            }
            else if (amt.formSatusText.ToLower() == "needs review" || amt.formSatusText.ToLower().Contains("approved"))
            {
                if (!UAS_Business_Functions.hasPermission(PermissionConstants.APPROVE, PermissionConstants.ASSMNTS))
                {
                    amt.CanUserChangeStatus = false;
                }
            }
            else if (amt.formId == 18)
            {
                amt.CanUserChangeStatus = false;
            }



            var    formType    = formsRepo.GetResponseVariablesByFormResultIdentifier(fr.formResultId, "C1_FormType");
            string formVariant = string.Empty;

            if (formType != null && formType.rspValue != null && formType.rspValue != String.Empty)
            {
                formVariant          = formType.rspValue;
                amt.FormVariantTitle = formVariant;
            }
            else
            {
                formsEntities context = new Assmnts.formsEntities();

                amt.FormVariantTitle = context.def_FormVariants
                                       .Where(fv => fv.formID == fr.formId)
                                       .Select(fv => fv.title)
                                       .FirstOrDefault();
            }

            //get the subject id from form result id
            if (fr.subject != null)
            {
                int subject = (int)fr.subject;

                var elgEndDate = formsRepo.GetResponseVariablesBySubjectForm(subject, 18, "C1_ProgramEligibleEndDate");

                string endDate = elgEndDate != null ? elgEndDate.rspValue : string.Empty;

                amt.EligibilityEnddate = endDate;

                amt.formResultUser = authClient.GetUserDisplay(subject);

                amt.clientId = authClient.GetExistingAdapIdentifier(amt.formResultUser.UserID, 8);
            }



            //End: added for enhancement Bug 13663 to be refactored


            amt.formId = sessionForm.formId;

            formsRepo.SortSectionItems(sctn);                   // This is both loading and sorting the SectionItems.

            // Get the Items in the SubSections *** NOTE: this only goes ONE level deep ***  Should be made recursive for unlimited levels !!!
            // amt.sections = new List<def_Sections>();
            foreach (def_SectionItems sctnItm in sctn.def_SectionItems.OrderBy(si => si.order))
            {
                if (sctnItm.subSectionId.GetValueOrDefault(0) == 0 || sctnItm.display == false)
                {
                    continue;
                }
                // def_Sections subSctns = sctnItm.def_SubSections.def_Sections;
                def_Sections subSctns = formsRepo.GetSubSectionById(sctnItm.subSectionId);

                //do not add notes section to the section list, (if there is a notes item, it will later be set as amt.notesItem)
                if (subSctns.multipleItemsPerPage == false)
                {
                    continue;
                }

                formsRepo.SortSectionItems(subSctns);                       // Load and sort the SectionItems
                amt.subSections.Add(subSctns);
                // GetItemLabelsResponses(fr.formResultId, amt, formsRepo.GetSectionItems(sctnItm.def_SubSections.def_Sections));
            }

            // RRB 5/28/15 *** This is only necessary for the Profile screens
            //             *** Getting and sorting the SectionItems above is only necessary for Question forms
            //             ***   In fact, it may duplicate what is being done in the templates
            formsRepo.GetItemListIncludingSubSections(sctn, amt);
            //GetItemListIncludingSubSections(sctn, amt);

            // Get the Notes items
            formsRepo.GetItemListForNotes(sctn, amt);

            formsRepo.GetItemLabelsResponses(fr.formResultId, amt, amt.items);

            //determine whether or not this user will be shown itemvariable identifiers as tooltips
            //TODO this is a DEV mode only thing
            amt.showItemVariableIdentifiersAsTooltips = Convert.ToBoolean(ConfigurationManager.AppSettings["showItemVariableIdentifiersAsTooltips"]);            // true;//new UAS.Business.UAS_Business_Functions().hasPermission(7,"assmnts");

            //save response values in session variable to later determine which ones were modified
            ////List<string> keysToClear = new List<string>();
            ////foreach (string key in Session.Keys)
            ////    if (key.StartsWith("frmOriginal___"))
            ////        keysToClear.Add(key);
            ////foreach (string key in keysToClear)
            ////    Session.Remove(key);
            //DateTime oneHourFromNow = DateTime.Now.AddHours(1);
            //foreach (string key in amt.rspValues.Keys)
            //{
            //Response.Cookies["frmOriginal___" + key].Value = amt.rspValues[key];
            //Response.Cookies["frmOriginal___" + key].Expires = oneHourFromNow;
            //}

            mLogger.Debug("* * *  AFTER GetItemLabelsResponses amt.items.Count: {0}", amt.items.Count);

            mLogger.Debug("* * *  amt.rspValues.Count (Total): {0}", amt.rspValues.Count);

            //populate required and readonly dictionaries
            amt.fldRequired = new Dictionary <string, bool>();
            amt.fldReadOnly = new Dictionary <string, bool>();
            List <def_SectionItems> siList = formsRepo.GetSectionItemsBySectionIdEnt(sctn.sectionId, SessionHelper.LoginStatus.EnterpriseID);

            if (amt.items != null)
            {
                foreach (def_Items itm in amt.items)
                {
                    if (amt.fldRequired.ContainsKey(itm.identifier))
                    {
                        throw new Exception("Found duplicate item identifier \"" + itm.identifier + "\"");
                    }
                    def_SectionItems si = siList.FirstOrDefault(s => (!s.subSectionId.HasValue && s.itemId == itm.itemId));

                    amt.fldRequired.Add(itm.identifier, (si == null) ? false : si.requiredForm);
                    amt.fldReadOnly.Add(itm.identifier, (si == null) ? false : si.readOnly);
                }
            }

            amt.isProfile = false;

            string[] uriSegments      = sctn.href.Split('/');
            string   templateFileName = uriSegments[uriSegments.Count() - 1];

            switch (templateFileName)
            {
            case "idprof1.cshtml":
            case "idprof2.cshtml":
            case "idprof2_Child.cshtml":
                if (mLogger.IsDebugEnabled)
                {
                    mLogger.Debug("showing section item identifiers:");
                    foreach (def_SectionItems si in siList)
                    {
                        mLogger.Debug("\t{0}", si.def_Items.identifier);
                    }
                }
                amt.notesItem            = siList.Single(si => si.def_Items.identifier.EndsWith("PageNotes_item")).def_Items;
                sessionForm.templateType = TemplateType.StdSectionItems;
                amt.isProfile            = true;
                break;

            default:                                // "SIS/section1a":     Default to the item list
                sessionForm.templateType = TemplateType.MultipleCommonItems;
                break;
            }

            // Setup the Previous / Next screens
            amt.prevScreenTitle = amt.prevScreenHref = String.Empty;
            amt.nextScreenTitle = amt.nextScreenHref = String.Empty;

            def_Parts prt = formsRepo.GetPartById(Convert.ToInt32(Session["part"]));



            List <def_Sections> partSections = formsRepo.GetSectionsInPart(prt);

            mLogger.Debug("* * *  ResultsController:Template method  * * * partSections.Count: {0}", partSections.Count);

            //get a list of parts in the current form

            def_Forms        form          = formsRepo.GetFormById(amt.formId);
            List <def_Parts> partsInForm   = formsRepo.GetFormParts(form);
            List <int>       partIdsInForm = partsInForm.Select(p => p.partId).ToList();
            // List<def_Parts> partsInForm = formsRepo.getFormParts(fr.def_Forms);



            //these variables will be assigned int he loop below
            int currentSectionIndex = 0;
            int prevSectionIndex    = 0;
            int nextSectionIndex    = 0;

            //start by assuming the previous and next section will be in the same part
            int currentPartId = (prt == null) ? sessionForm.partId : prt.partId;

            amt.thisPartId = currentPartId;

            amt.navPartId = currentPartId.ToString();
            int prevPartId = currentPartId;
            int nextPartId = currentPartId;

            //in a special cases one of these will be set to true
            bool veryFirst = false;
            bool veryLast  = false;

            bool foundSectionId = false;

            //iterate through possible section ids
            for (int idx = 0; idx < partSections.Count; idx++)
            {
                if (partSections[idx].sectionId == sessionForm.sectionId)
                {
                    //found the current section id, start with some assumptions about previous and next section ids
                    foundSectionId      = true;
                    currentSectionIndex = idx;
                    prevSectionIndex    = idx - 1;
                    nextSectionIndex    = idx + 1;

                    //we may have to link to the last section of the previous part
                    if (prevSectionIndex < 0)
                    {
                        //special case where we're on the first section of the first part
                        if (partIdsInForm.IndexOf(prt.partId) == 0)                        //currentPartId == 1)
                        {
                            //veryFirst = true;
                            int partIndexInForm = partsInForm.Count();
                            List <def_Sections> prevPartSections = formsRepo.GetSectionsInPart(partsInForm[partIndexInForm - 1]);
                            prevPartId       = partsInForm[partIndexInForm - 1].partId;
                            prevSectionIndex = prevPartSections.Count - 1;
                        }
                        else
                        {
                            int partIndexInForm = partIdsInForm.IndexOf(prt.partId);
                            // occasionally a part with no sections may need to be skipped, which can happen with PartSectionsEnt records.
                            int listIndex = 0;
                            for (int i = 1; i < partIndexInForm; i++)
                            {
                                if (formsRepo.GetSectionsInPart(partsInForm[partIndexInForm - i]).Count() > 0)
                                {
                                    listIndex = partIndexInForm - i;
                                    break;
                                }
                            }

                            List <def_Sections> prevPartSections = formsRepo.GetSectionsInPart(partsInForm[listIndex]);
                            prevPartId       = partsInForm[listIndex].partId;
                            prevSectionIndex = prevPartSections.Count - 1;
                        }
                    }

                    // Oliver - same here the PartSections are ordered - just use the first one in the List.
                    // you can press F12 in Visual Studio and it will take you to the method.
                    // Data/Concrete/FormsRepository line 200
                    // The defined Interfaces are in Data/Abstract/IFormsRepository.cs

                    //we may have to link to he first section of the next part
                    if (nextSectionIndex > (partSections.Count - 1))
                    {
                        int partIndexInForm = partIdsInForm.IndexOf(prt.partId);
                        if (partIndexInForm == (partsInForm.Count() - 1))                          //formsRepo.GetPartById(nextPartId) == null)
                        {
                            //veryLast = true;
                            nextPartId       = partsInForm[0].partId;
                            nextSectionIndex = 0;
                        }
                        else
                        {
                            // occasionally a part with no sections may need to be skipped, which can happen with PartSectionsEnt records.
                            int listIndex = 0;
                            for (int i = 1; i < partsInForm.Count() - 1 - partIndexInForm; i++)
                            {
                                if (formsRepo.GetSectionsInPart(partsInForm[partIndexInForm + i]).Count() > 0)
                                {
                                    listIndex = partIndexInForm + i;
                                    break;
                                }
                            }

                            nextPartId       = partsInForm[listIndex].partId;
                            nextSectionIndex = 0;
                        }
                    }

                    break;
                }
            }

            if (!foundSectionId)
            {
                string msg = "current section id (" + sessionForm.sectionId + ") could not be found.\r\nListing candidates: (identifier / sectionId)";
                foreach (def_Sections sct in partSections)
                {
                    msg += (sct == null) ? "null" : ("\r\n" + sct.identifier + " / " + sct.sectionId);
                }
                throw new Exception(msg);
            }

            //print some debugging info
            if (mLogger.IsDebugEnabled)
            {
                mLogger.Debug("* * *  ResultsController:Template method  * * * " +
                              (veryFirst ? "this is the very first part/section" : "prevPartId: " + prevPartId.ToString() +
                               ", prevSectionIndex: " + prevSectionIndex.ToString()));
                mLogger.Debug("* * *  ResultsController:Template method  * * * " +
                              (veryLast ? "this is the very last part/section" : "nextPartId: " + nextPartId.ToString() +
                               ", nextSectionIndex: " + nextSectionIndex.ToString()));
            }
            if (partSections.Count > 0)
            {
                int    idxPeriod      = prt.identifier.IndexOf('.');
                string partShortTitle = (idxPeriod < 0) ? prt.identifier : prt.identifier.Substring(0, idxPeriod);
                // amt.thisScreenCaption = partShortTitle + " - " + partSections[thisIdx].identifier;
                amt.thisScreenCaption = partShortTitle + " - " + partSections[currentSectionIndex].identifier;
                amt.thisScreenTitle   = partSections[currentSectionIndex].title;

                if (!veryFirst)
                {
                    List <def_Sections> prevPartSections = formsRepo.GetSectionsInPart(formsRepo.GetPartById(prevPartId));
                    amt.prevScreenTitle     = prevPartSections[prevSectionIndex].title;
                    amt.prevScreenPartId    = prevPartId.ToString();
                    amt.prevScreenSectionId = prevPartSections[prevSectionIndex].sectionId.ToString();
                    amt.prevScreenHref      = "Template?partId=" + nextPartId + "&sectionId=" + amt.prevScreenSectionId;
                    //if (prevPartId != currentPartId)
                    //    amt.previousScreenHref = "Parts?formResultId=" + formsRepo.GetPartById(prevPartId).partId.ToString() + amt.previousScreenHref;
                }

                if (!veryLast)
                {
                    def_Parts tempPart = formsRepo.GetPartById(nextPartId);
                    if (tempPart != null)
                    {
                        List <def_Sections> tempPartSections = formsRepo.GetSectionsInPart(tempPart);
                        amt.nextScreenTitle     = tempPartSections[nextSectionIndex].title;
                        amt.nextScreenPartId    = nextPartId.ToString();
                        amt.nextScreenSectionId = tempPartSections[nextSectionIndex].sectionId.ToString();
                        amt.nextScreenHref      = "Template?partId=" + nextPartId + "&sectionId=" + amt.nextScreenSectionId;
                    }
                }
            }

            //pass a NavMenu model as a field in this items Model
            sessionForm.formIdentifier = form.identifier;
            amt.navMenuModel           = getNavMenuModel(sessionForm, amt);


            //Start: added for enhancement Bug 13663 to be refactored
            amt.navMenuModel.formResultUser      = amt.formResultUser;
            amt.navMenuModel.clientId            = amt.clientId;
            amt.navMenuModel.formSatusText       = amt.formSatusText;
            amt.navMenuModel.EligibilityEnddate  = amt.EligibilityEnddate;
            amt.navMenuModel.FormVariantTitle    = amt.FormVariantTitle;
            amt.navMenuModel.updatedDate         = amt.updatedDate;
            amt.navMenuModel.CanUserChangeStatus = amt.CanUserChangeStatus;
            amt.navMenuModel.formResultId        = amt.formResultId;
            //End: added for enhancement Bug 13663 to be refactored



            amt.ventureMode = SessionHelper.IsVentureMode;

            //special case for reports sections
            if ((sctn.identifier.EndsWith("Report") /*&& (Request["ignoreValidation"] as string) == null*/) ||
                sctn.href.Equals("~/Views/Templates/SIS/reportErrors.cshtml")
                )
            {
                if (!ValidateFormResult(fr, amt))
                {
                    return(View("~/Views/Templates/SIS/reportErrors.cshtml", amt));
                }
            }

            //add messages to the mdoel if necessary
            amt.validationMessages = validationMessages;             //validationMessages from method params, normally null

            //add a message to the model if necessary
            string message = Request["message"] as string;

            if (message != null)
            {
                if (amt.validationMessages == null)
                {
                    amt.validationMessages = new List <string>();
                }
                amt.validationMessages.Add(message);
            }

            // *** RRB 10/27/15 - added to fix problems with Venture and to be more efficient.
            if (!SessionHelper.IsVentureMode)
            {
                if (templateFileName.Equals("reportOptions.cshtml"))
                {
                    amt.reportOptions = AJBoggs.Sis.Reports.SisReportOptions.BuildPdfReportOptions(fr.EnterpriseID);
                }
            }

            // * * * OT 3/24/16 - for SIS supplemental questions, pre-populate sis_s41f with some item prompts from section 1A
            //  Don't do anything if there is already a response for sis_s41f
            //  (Bug 13132, #4 in description)
            if (sctn.identifier == "SQ" && amt.rspValues.ContainsKey("sis_s41f") && String.IsNullOrWhiteSpace(amt.rspValues["sis_s41f"]))
            {
                amt.rspValues["sis_s41f"] = String.Empty;

                //iterate through all section 1A items
                int          itmCount         = 0;
                bool         isSisCAssessment = fr.def_Forms.identifier.Equals("SIS-C");
                def_Sections sct1A            = formsRepo.GetSectionByIdentifier(isSisCAssessment ? "SIS-C 1A" : "SIS-A 1A");
                formsRepo.SortSectionItems(sct1A);
                foreach (def_SectionItems si in sct1A.def_SectionItems)
                {
                    def_Sections subSct = formsRepo.GetSubSectionById(si.subSectionId);
                    formsRepo.SortSectionItems(subSct);
                    foreach (def_SectionItems subSi in subSct.def_SectionItems)
                    {
                        //for items that have an itemVariable with suffix "_ExMedSupport", check if that itemVariable have a response of "2"
                        def_Items itm = subSi.def_Items;
                        itmCount++;
                        def_ItemVariables exMedSupIv = itm.def_ItemVariables.Where(iv => iv.identifier.EndsWith("_ExMedSupport")).FirstOrDefault();
                        if (exMedSupIv != null)
                        {
                            def_ResponseVariables rv = formsRepo.GetResponseVariablesByFormResultItemVarId(fr.formResultId, exMedSupIv.itemVariableId);
                            if (rv != null && !String.IsNullOrWhiteSpace(rv.rspValue) && rv.rspValue == "2")
                            {
                                //append the item prompt to the pre-populated response for sis_s41f
                                amt.rspValues["sis_s41f"] += itmCount + ". " + itm.prompt + "\n";
                            }
                        }
                    }
                }
            }

            // *** OT 11/23/15 - added as test for Bug 12910 - Comparison: what changed from last approved application?
            //if we're on the ADAP form...
            if (form.identifier.Contains("ADAP"))
            {
                //get the previous formresult
                int?sortOrder = formsRepo.GetStatusDetailByMasterIdentifier(1, "CANCELLED").sortOrder;
                int userId    = fr.subject.HasValue ? fr.subject.Value : -1;
                if (userId < 1)
                {
                    mLogger.Warn("subject < 1 for form result having formResultId = {0}.", fr.formResultId);
                }
                // * * * OT 1-19-16 added stipulation that "prevRes" is not the current formResult "fr"
                def_FormResults prevRes = null;
                if (sortOrder.HasValue && userId > 0)
                {
                    prevRes = formsRepo.GetEntities <def_FormResults>(
                        x => x.formId == fr.formId &&
                        x.formResultId != fr.formResultId &&
                        x.subject == userId &&
                        x.formStatus != sortOrder)
                              .OrderByDescending(x => x.dateUpdated)
                              .FirstOrDefault();
                }
                // * * * OT 1-19-16 in order to duplicate existing behavior and avoid crashes,
                // default to using the current formResult as the previous if no others are applicable
                if (prevRes == null)
                {
                    prevRes = fr;
                }

                List <string> remainingIdentifiers = amt.rspValues.Keys.ToList();

                IList <def_ItemResults> previousItemResults = formsRepo.GetItemResults(prevRes.formResultId);
                foreach (def_ItemResults ir in previousItemResults)
                {
                    foreach (def_ResponseVariables rv in ir.def_ResponseVariables)
                    {
                        if (rv.def_ItemVariables == null)
                        {
                            continue;
                        }

                        remainingIdentifiers.Remove(rv.def_ItemVariables.identifier);
                        string rspValue = HttpUtility.HtmlDecode(rv.rspValue);

                        amt.rspValues.Add("PREVIOUS_" + rv.def_ItemVariables.identifier, rspValue);
                    }
                }

                //populate amt with empty responses for fields Bmissing from previous formResult
                foreach (string ident in remainingIdentifiers)
                {
                    amt.rspValues.Add("PREVIOUS_" + ident, "");
                }
            }

            SessionHelper.ResponseValues = amt.rspValues;

            //Displays save message
            ViewBag.Notify        = "";
            ViewBag.NotifyMessage = "";
            if (Session["IsPageLoad"] != null)
            {
                if (!(bool)Session["IsPageLoad"])
                {
                    if (TempData["Savemsg"] != null && TempData["SavemsgHeader"] != null)
                    {
                        if (TempData["Savemsg"].ToString() != "" && TempData["SavemsgHeader"].ToString() != "")
                        {
                            ViewBag.Notify        = TempData["SavemsgHeader"].ToString();
                            ViewBag.NotifyMessage = TempData["Savemsg"].ToString();
                        }
                    }
                }
            }


            TempData["SavemsgHeader"] = "";
            TempData["Savemsg"]       = "";
            return(View(sctn.href, amt));
        }
Esempio n. 23
0
        private IQueryable <vSearchGrid> DetailSearch(SearchCriteria searchCriteria)
        {
            IQueryable <vSearchGrid> tmpResult = null;
            var  context = DataContext.getSisDbContext();
            bool previousSearchResult    = false;
            bool previousRecSearchResult = false;
            bool debug = false; // set to true to display record counts after each parameter is added.

            List <long>   RecipientIDs = new List <long>();
            List <int>    SISIds       = new List <int>();
            List <string> TrackList    = null;

            //
            if (!string.IsNullOrWhiteSpace(searchCriteria.sisIds))
            {
                List <string> tempSisIdlist = new List <string>(searchCriteria.sisIds.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
                foreach (var tempSis in tempSisIdlist)
                {
                    int tempSisInt = 0;
                    if (Int32.TryParse(tempSis, out tempSisInt))
                    {
                        SISIds.Add(tempSisInt);
                    }
                }

                if (SISIds.Count > 0)
                {
                    previousSearchResult = true;
                }
            }

            if (!string.IsNullOrWhiteSpace(searchCriteria.recIds))
            {
                List <string> tempRecIdList = new List <string>(searchCriteria.recIds.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
                foreach (var tempRecId in tempRecIdList)
                {
                    int tempRecIDInt = 0;
                    if (Int32.TryParse(tempRecId, out tempRecIDInt))
                    {
                        RecipientIDs.Add(tempRecIDInt);
                    }
                }

                if (RecipientIDs.Count > 0)
                {
                    previousRecSearchResult = true;
                }
            }

            if (!string.IsNullOrWhiteSpace(searchCriteria.trackingNumber))
            {
                TrackList = new List <string>(searchCriteria.trackingNumber.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
                //// List<int> tempList = new List<int>();

                //List<int> tempList = (from a in context.vSisDefRaws
                //                      where
                //                      (
                //                        (a.rspValue != null && a.identifier == "sis_track_num")
                //                        &&
                //                        (tempTrackList.Contains(a.rspValue) && a.identifier == "sis_track_num")
                //                      )
                //                      select a.formResultId).ToList();

                //// if previous search result returned a result, only get the result that also exist in this result.
                //// this will simulate "AND" search for all search criteria
                //if (previousSearchResult)
                //{
                //    SISIds = (from a in SISIds
                //              join b in tempList on a equals b
                //              select a).ToList();
                //}
                //else
                //{
                //    SISIds.AddRange(tempList);
                //}

                //if (tempList.Count > 0)
                //    previousSearchResult = true;
            }

            bool isFirstNameNull = string.IsNullOrWhiteSpace(searchCriteria.FirstName);
            bool isLastNameNull  = string.IsNullOrWhiteSpace(searchCriteria.LastName);

            if (!isFirstNameNull || !isLastNameNull)
            {
                //Recipient Search
                // List<long> tempRecList = new List<long>();
                List <long> tempRecList = (from r in context.Recipients
                                           where (
                                               (isFirstNameNull || (r.Contact.FirstName.Contains(searchCriteria.FirstName))) &&
                                               (isLastNameNull || (r.Contact.LastName.Contains(searchCriteria.LastName)))
                                               )
                                           select r.Recipient_ContactID).ToList();

                if (previousRecSearchResult)
                {
                    RecipientIDs = (from a in RecipientIDs
                                    join b in tempRecList on a equals b
                                    select a).ToList();
                }
                else
                {
                    RecipientIDs.AddRange(tempRecList);
                }

                if (tempRecList.Count > 0)
                {
                    previousRecSearchResult = true;
                }

                // SIS Search
                List <int> tempList = new List <int>();
                if (!isLastNameNull)
                {
                    tempList.AddRange((from a in context.vSisDefRaws
                                       where
                                       (
                                           (a.rspValue != null && a.identifier == "sis_cl_last_nm")
                                           &&
                                           (a.rspValue.Contains(searchCriteria.LastName) && a.identifier == "sis_cl_last_nm")
                                       )
                                       select a.formResultId).ToList());
                }

                if (!isFirstNameNull)
                {
                    tempList.AddRange((from a in context.vSisDefRaws
                                       where
                                       (
                                           (a.rspValue != null && a.identifier == "sis_cl_first_nm")
                                           &&
                                           (a.rspValue.Contains(searchCriteria.FirstName) && a.identifier == "sis_cl_first_nm")
                                       )
                                       select a.formResultId).ToList());
                }

                if (!isFirstNameNull && !isLastNameNull)
                {
                    tempList = (tempList.GroupBy(x => x).Where(group => group.Count() > 1).Select(group => group.Key)).ToList();
                }

                // if previous search result returned a result, only get the result that also exist in this result.
                // this will simulate "AND" search for all search criteria
                if (previousSearchResult)
                {
                    SISIds = (from a in SISIds
                              join b in tempList on a equals b
                              select a).ToList();
                }
                // Next line was causing search for first and last name not to work.
                else
                {
                    SISIds.AddRange(tempList);
                }

                if (tempList.Count > 0)
                {
                    previousSearchResult = true;
                }
            }

            bool getAllAssessmentsForEachRecipient = false;

            if (searchCriteria.allForEachRecipient)
            {
                getAllAssessmentsForEachRecipient = true;
            }

            // *** Required filters ***
            // Set up the query.
            if (SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups[0] != 0)
            {
                // Remove any Groups which are not authorized.
                List <int> authGroups = SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups;

                // Check that the sub_id has a value, then compare it to the authGroups, where the authGroup is > -1.
                tmpResult = context.vSearchGrids.AsNoTracking().Where(srch => srch.sub_id.HasValue && authGroups.Any(ag => ag > -1 && ag == srch.sub_id));
                if (debug)
                {
                    Debug.WriteLine("DetailSearch Initial Count after authgroups: " + tmpResult.Count());
                }
            }
            else
            {
                tmpResult = context.vSearchGrids.AsNoTracking();
                if (debug)
                {
                    Debug.WriteLine("DetailSearch Initial record Count: " + tmpResult.Count());
                }
            }

            // Filter by Enterprise, unless Enterprise == 0.
            tmpResult = tmpResult.Where(srch => srch.ent_id == SessionHelper.LoginStatus.EnterpriseID || SessionHelper.LoginStatus.EnterpriseID == 0);
            if (debug)
            {
                Debug.WriteLine("DetailSearch limit by Enterprise record Count: " + tmpResult.Count());
            }

            if (!UAS_Business_Functions.hasPermission(UAS.Business.PermissionConstants.GROUP_WIDE, UAS.Business.PermissionConstants.ASSMNTS))
            {
                // Filter by Assigned Only
                tmpResult = tmpResult.Where(srch => srch.assigned == SessionHelper.LoginStatus.UserID);
            }
            if (debug)
            {
                Debug.WriteLine("DetailSearch Assign Only record Count: " + tmpResult.Count());
            }
            //*** End Required Filters

            // If statement ensures 0 results will be returned when no records are found.
            if (!String.IsNullOrWhiteSpace(searchCriteria.sisIds) || !String.IsNullOrWhiteSpace(searchCriteria.recIds) ||
                !String.IsNullOrWhiteSpace(searchCriteria.FirstName) || !String.IsNullOrWhiteSpace(searchCriteria.LastName))
            {
                tmpResult = tmpResult.Where(srch => SISIds.Any(sis => sis == srch.formResultId) || RecipientIDs.Any(recip => recip == srch.Recipient_ContactID));
            }
            if (debug)
            {
                Debug.WriteLine("DetailSearch SISIds and RecipientIds record Count: " + tmpResult.Count());
            }

            // Filter by Tracking number
            if (TrackList != null && TrackList.Count() > 0)
            {
                tmpResult = tmpResult.Where(srch => TrackList.Any(trk => trk.Equals(srch.TrackingNumber)));
            }
            if (debug)
            {
                Debug.WriteLine("DetailSearch Tracking Number record Count: " + tmpResult.Count());
            }

            // Filter by Interviewers
            if (searchCriteria.SelectedInterviewers != null && searchCriteria.SelectedInterviewers.Count() > 0)
            {
                tmpResult = tmpResult.Where(srch => searchCriteria.SelectedInterviewers.Contains(srch.InterviewerLoginID));
            }
            if (debug)
            {
                Debug.WriteLine("DetailSearch Selected Interviewers record Count: " + tmpResult.Count());
            }

            // Filter by Group
            if (searchCriteria.SelectedGroups != null && searchCriteria.SelectedGroups.Count() > 0)
            {
                tmpResult = tmpResult.Where(srch => searchCriteria.SelectedGroups.Any(sg => srch.sub_id == sg));
            }
            if (debug)
            {
                Debug.WriteLine("DetailSearch Selected Group record Count: " + tmpResult.Count());
            }

            // Filter by Selected Enterprises, unless the SelectedEnts list is empty or null.
            if (searchCriteria.SelectedEnts != null && searchCriteria.SelectedEnts.Count() > 0)
            {
                tmpResult = tmpResult.Where(srch => searchCriteria.SelectedEnts.Any(se => srch.ent_id == se));
            }
            if (debug)
            {
                Debug.WriteLine("DetailSearch Selected Enterprise record Count: " + tmpResult.Count());
            }

            // Filter by patterns
            if (searchCriteria.SelectedPatterns != null && searchCriteria.SelectedPatterns.Any())
            {
                tmpResult = from t in tmpResult
                            join p in context.PatternChecks on t.formResultId equals p.formResultId
                            where searchCriteria.SelectedPatterns.Contains(p.PatternId)
                            select t;
            }
            else if (searchCriteria.PatternCheck)
            {
                tmpResult = from t in tmpResult
                            join p in context.PatternChecks on t.formResultId equals p.formResultId
                            select t;
            }

            if (debug)
            {
                Debug.WriteLine("DetailSearch Selected Pattern record Count: " + tmpResult.Count());
            }

            // Search by Date Updated
            if (searchCriteria.updatedDateFrom != null || searchCriteria.updatedDateTo != null)
            {
                if (searchCriteria.updatedDateFrom != null)
                {
                    DateTime dt = Convert.ToDateTime(searchCriteria.updatedDateFrom);
                    tmpResult = from t in tmpResult
                                join fr in context.def_FormResults on t.formResultId equals fr.formResultId
                                where fr.dateUpdated >= dt
                                select t;
                }

                if (searchCriteria.updatedDateTo != null)
                {
                    DateTime dt = Convert.ToDateTime(searchCriteria.updatedDateTo);
                    tmpResult = from t in tmpResult
                                join fr in context.def_FormResults on t.formResultId equals fr.formResultId
                                where fr.dateUpdated <= dt
                                select t;
                }

                if (debug)
                {
                    Debug.WriteLine("DetailSearch Updated Date From/To record Count: " + tmpResult.Count());
                }
            }

            // Search by Interview Date Range
            if (searchCriteria.interviewDateFrom != null)
            {
                DateTime dt = Convert.ToDateTime(searchCriteria.interviewDateFrom);
                tmpResult = tmpResult.Where(srch => srch.InterviewDate >= dt);
            }
            if (searchCriteria.interviewDateTo != null)
            {
                DateTime dt = Convert.ToDateTime(searchCriteria.interviewDateTo);
                tmpResult = tmpResult.Where(srch => srch.InterviewDate <= dt);
            }
            if (debug)
            {
                Debug.WriteLine("DetailSearch Interview Date Range record Count: " + tmpResult.Count());
            }

            // Check Level of Completion checkboxes, include records where appropriate.  Text is hardcoded into a database view, inaccessible through Assessments.
            tmpResult = tmpResult.Where(srch => (searchCriteria.statusNew && srch.Status.Equals("New")) ||
                                        (searchCriteria.statusInProgress && srch.Status.Equals("In Progress")) ||
                                        (searchCriteria.statusCompleted && srch.Status.Equals("Completed")) ||
                                        (searchCriteria.statusAbandoned && srch.Status.Equals("Abandoned")));

            if (debug)
            {
                Debug.WriteLine("DetailSearch Count after Level of Completion: " + tmpResult.Count());
            }

            // Check QA Review Status.  Include every result when nothing is checked, except Pre-QA.
            tmpResult = tmpResult.Where(srch => (!(searchCriteria.reviewStatusToBeReviewed || searchCriteria.reviewStatusPreQA || searchCriteria.reviewStatusReviewed || searchCriteria.reviewStatusApproved) && !srch.reviewStatus.Equals(ReviewStatus.PRE_QA.ToString())) ||
                                        (searchCriteria.reviewStatusToBeReviewed && srch.reviewStatus.Equals(ReviewStatus.TO_BE_REVIEWED.ToString())) ||
                                        (searchCriteria.reviewStatusPreQA && srch.reviewStatus.Equals(ReviewStatus.PRE_QA.ToString()) && searchCriteria.statusCompleted) ||
                                        (searchCriteria.reviewStatusReviewed && srch.reviewStatus.Equals(ReviewStatus.REVIEWED.ToString())) ||
                                        (searchCriteria.reviewStatusApproved && srch.reviewStatus.Equals(ReviewStatus.APPROVED.ToString())));
            if (debug)
            {
                Debug.WriteLine("DetailSearch Count after QA Review: " + tmpResult.Count());
            }

            // Check typically hidden records.  Hide deleted or archived unless those boxes are checked.
            tmpResult = tmpResult.Where(srch => (!searchCriteria.deleted && !searchCriteria.archived && ((!srch.deleted || srch.deleted == null) && (!srch.archived || srch.archived == null))) ||
                                        (searchCriteria.deleted && srch.deleted) ||
                                        (searchCriteria.archived && srch.archived) ||
                                        (searchCriteria.deleted && searchCriteria.archived && (srch.deleted || srch.archived)));
            if (debug)
            {
                Debug.WriteLine("DetailSearch Count after Hidden Records: " + tmpResult.Count());
            }

            tmpResult = tmpResult.GroupBy(x => x.formResultId).Select(g => g.FirstOrDefault());

            if (debug)
            {
                Debug.WriteLine("DetailSearch Count after Group By: " + tmpResult.Count());
            }

            if (!searchCriteria.adultSis || !searchCriteria.childSis)
            {
                // 3-22-16 MR fixed logic to accurately search for adults or child assessments
                if (!searchCriteria.adultSis)
                {
                    tmpResult = tmpResult.Where(x => (x.formId != 1) && (x.formId != null));
                }

                if (!searchCriteria.childSis)
                {
                    tmpResult = tmpResult.Where(x => (x.formId != 2) && (x.formId != null));
                }
            }
            if (debug)
            {
                Debug.WriteLine("DetailSearch Count after SIS-A/SIS-C filter: " + tmpResult.Count());
            }


            return(tmpResult.OrderByDescending(a => a.Rank));
        }