/// <summary>
		/// Builds the QuestionSearchCriteria. Used both from Search Button and from Service
		/// </summary>
		public static AddendumSearchCriteriaV2 BuildSearchCriteriaObject(ThinkgateUser user, CriteriaController criteriaController, string requestedSortField = null)
		{

			/* Sort */
			string sortField = null;
			NameValue nvSortField = SortFields().Find(x => x.Name == requestedSortField);   // ensure that the user given value for sort is in the defined list of options
			if (nvSortField != null) sortField = nvSortField.Value;

			/* Item Banks - Remove from master list based on filter if given */
			var itemBanks = ItemBankMasterList.GetItemBanksForUser(user);

            if (TestCategory != null && TestCategory == AssessmentCategories.District.ToString())
            {
                for (var rowIndex = itemBanks.Rows.Count - 1; rowIndex >= 0; rowIndex--)
                {
                    if (itemBanks.Rows[rowIndex]["Label"].ToString() == "Personal")
                    { itemBanks.Rows[rowIndex].Delete(); }
                }
            }

            var selectedItemBanks = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("ItemBank").Select(x => x.Text);
			if (selectedItemBanks.Any()) itemBanks.DeleteByLabel(selectedItemBanks);

			/* Text Search */
			string searchText = string.Empty;
			string searchOption = string.Empty;
			var txtSearchList = criteriaController.ParseCriteria<TextWithDropdown.ValueObject>("TextSearch");
			if (txtSearchList.Count > 0)
			{
				// we ensure that the value the user gave us for text search type is a valid option
				var confirmedOption = TextSearchDropdownValues().Find(x => x.Name == txtSearchList[0].Option) ?? TextSearchDropdownValues().First();
				if (!String.IsNullOrEmpty(txtSearchList[0].Text))
				{
					searchText = txtSearchList[0].Text;
					searchOption = confirmedOption.Value;
				}
			}

			/* Courses */
			var selectedGrades = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Grade").Select(x => x.Text).ToList();
			var selectedSubjects = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Subject").Select(x => x.Text).ToList();
			var selectedCourses = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Course").Select(x => x.Text).ToList();
			var selectedStandardSets = new drGeneric_String(criteriaController.ParseCriteria<CheckBoxList.ValueObject>("StandardSet").Select(x => x.Text));     // take straight to drGeneric_String because it's going to SQL
			var filteredCourses = CourseMasterList.GetStandardCoursesForUser(user).FilterByGradesSubjectsStandardSetsAndCourse(selectedGrades, selectedSubjects, selectedStandardSets, selectedCourses);


			/* Type/Genre */
			var selectedAddendumGenres = new drGeneric_String();
			var selectedAddendumTypes = new drGeneric_String();
			var selectedTypesGenres = criteriaController.ParseCriteria<AddendumType.ValueObject>("AddendumType");
			foreach (var selectedTypesGenre in selectedTypesGenres)
			{
				if (selectedTypesGenre.Genre != null)
				{
					selectedAddendumGenres.Add(selectedTypesGenre.Genre);
				}
				else
				{
					selectedAddendumTypes.Add(selectedTypesGenre.Text);
				}
			}
			if (selectedAddendumGenres.Count > 0)
				selectedAddendumTypes.Add("Passage");


		    var selectedExpirationStatus = criteriaController.ParseCriteria<DropDownList.ValueObject>("ExpirationStatus").FirstOrDefault() != null ? 
                criteriaController.ParseCriteria<DropDownList.ValueObject>("ExpirationStatus").FirstOrDefault().Value : "I";
            if (!ShowExpiredItems)
            {
                selectedExpirationStatus = "E";

            }
            drGeneric_String_String selectedExpirationDateRange = new drGeneric_String_String();
            foreach (var val in criteriaController.ParseCriteria<DateRange.ValueObject>("ExpirationDateRange"))
            {
                selectedExpirationDateRange.Add(val.Type == "Start" ? "CreatedDateStart" : "CreatedDateEnd", val.Date);
            }


			/* Build Criteria Object */
            var asc = new AddendumSearchCriteriaV2()
                                             {
                                                 ItemBanks = itemBanks,
                                                 CourseList = filteredCourses,
                                                 AddendumType = selectedAddendumTypes,
                                                 AddendumGenre = selectedAddendumGenres,
                                                 UserAccessItemReservations = "",
                                                 Text = searchText,
                                                 TextOpt = searchOption,                                                 
                                                 SortKeyword = sortField,
                                                 courseSelected = selectedCourses.Count > 0 ? true : false,
                                                 ExpirationStatus = selectedExpirationStatus,
                                                 ExpirationDateRange = selectedExpirationDateRange
                                             };

			return asc;
		}
        public static List<Thinkgate.Base.Classes.Resource> SearchResourcesWithCriteria(ThinkgateUser user, CriteriaController criteriaController)
        {
            var selectedCategories = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Category").Select(x => x.Value);
            var selectedTypes = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Type").Select(x => x.Value);
            var selectedSubTypes = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Subtype").Select(x => x.Value);

            string resourceName = string.Empty;
            var resourceNameList = criteriaController.ParseCriteria<E3Criteria.Text.ValueObject>("ResourceName");
            if (resourceNameList.Count > 0) resourceName = resourceNameList[0].Text;

            string searchText = string.Empty;
            string searchOption = string.Empty;
            var txtSearchList = criteriaController.ParseCriteria<E3Criteria.TextWithDropdown.ValueObject>("TextSearch");
            if (txtSearchList.Count > 0)
            {
                var confirmedOption = TextSearchDropdownValues().Find(x => x.Name == txtSearchList[0].Option) ?? TextSearchDropdownValues().First();
                if (!String.IsNullOrEmpty(txtSearchList[0].Text))
                {
                    searchText = txtSearchList[0].Text;
                    searchOption = confirmedOption.Value;
                }
            }
            var selectedStandards = new ArrayList();
            var associationType = string.Empty;
            var associationField1 = string.Empty;
            var associationField2 = string.Empty;
            var associationField3 = string.Empty;
            var associatedCurriculum = criteriaController.ParseCriteria<Curriculum.ValueObject>("Curriculum");
            var associatedStandards = criteriaController.ParseCriteria<E3Criteria.Associations.Standards.ValueObject>("Standards");
            var associatedClasses = criteriaController.ParseCriteria<E3Criteria.Associations.Classes.ValueObject>("Classes");
            var associatedDocuments = criteriaController.ParseCriteria<E3Criteria.Associations.Documents.ValueObject>("Documents");
            var associatedSchools = criteriaController.ParseCriteria<E3Criteria.Associations.Schools.ValueObject>("Schools");
            var associatedStudents = criteriaController.ParseCriteria<E3Criteria.Associations.Students.ValueObject>("Students");
            var associatedTeachers = criteriaController.ParseCriteria<E3Criteria.Associations.Teachers.ValueObject>("Teachers"); 
            if (associatedCurriculum.Count > 0)
            {
                associationType = "Curriculum";
                associationField1 = associatedCurriculum[0].Grade;
                associationField2 = associatedCurriculum[0].Subject;
                associationField3 = associatedCurriculum[0].Curriculum;
            }
            else if (associatedStandards.Count > 0 && associatedStandards[0].Standards != null && associatedStandards[0].Standards.Count > 0)
            {
                associationType = "Standards"; 
                selectedStandards = associatedStandards[0].Standards;
            }
            else if (associatedClasses.Count > 0)
            {
                associationType = "Classes";
                associationField1 = associatedClasses[0].Grade;
                associationField2 = associatedClasses[0].Subject;
                associationField3 = associatedClasses[0].Course;
            }
            else if (associatedDocuments.Count > 0)
            {
                associationType = "Documents";
                associationField1 = associatedDocuments[0].TemplateType;
                associationField2 = associatedDocuments[0].TemplateName;
                associationField3 = associatedDocuments[0].DocumentName;
            }
            else if (associatedSchools.Count > 0)
            {
                associationType = "Schools";
                associationField1 = associatedSchools[0].SchoolType;
                associationField2 = associatedSchools[0].School;
                associationField3 = associatedSchools[0].SchoolId;
            }
            else if (associatedStudents.Count > 0)
            {
                associationType = "Students";
                associationField1 = associatedStudents[0].Name;
                associationField2 = associatedStudents[0].Id;
                associationField3 = associatedStudents[0].Grade;
            }
            else if (associatedTeachers.Count > 0)
            {
                associationType = "Teachers";
                associationField1 = associatedTeachers[0].Name;
                associationField2 = associatedTeachers[0].UserType;
                associationField3 = associatedTeachers[0].UserId;
            }
            
            
           

            return Thinkgate.Base.Classes.Resource.SearchAdvanced(selectedCategories, selectedTypes, selectedSubTypes, resourceName, searchText, searchOption,
                associationType, associationField1, associationField2, associationField3, selectedStandards);
        }
		protected ReferenceSearchCriteria GetSelectedCriteria(CriteriaController criteriaController)
		{
			/* Get selected user group criteria value */
			ReferenceSearchCriteria referenceSearchCriteria = new ReferenceSearchCriteria();
			string documentSearchCriteria = string.Empty;
			List<Thinkgate.Controls.E3Criteria.DropDownList.ValueObject> selectedCriteria = null;

			selectedCriteria = criteriaController.ParseCriteria<Thinkgate.Controls.E3Criteria.DropDownList.ValueObject>("UserGroup").ToList();
			if (selectedCriteria.Count > 0)
			{
                /* TFS 9069 In case of 'All' UserGroup option selected, the default search is be run. Skip condition in this case. */
                if (selectedCriteria[0].Value != Convert.ToInt32(LookupDetail.All).ToString() && selectedCriteria[0].Text != LookupDetail.All.ToString())
                {
                    documentSearchCriteria += " UserGroup = '" + selectedCriteria[0].Value + "' ";
                }
			}
			selectedCriteria = criteriaController.ParseCriteria<Thinkgate.Controls.E3Criteria.DropDownList.ValueObject>("Category").ToList();
			if (selectedCriteria.Count > 0)
			{
				documentSearchCriteria += string.IsNullOrWhiteSpace(documentSearchCriteria) ? string.Empty : " AND ";
				documentSearchCriteria += " CategoryList = '" + selectedCriteria[0].Value + "' ";
			}
			selectedCriteria = criteriaController.ParseCriteria<Thinkgate.Controls.E3Criteria.DropDownList.ValueObject>("Component").ToList();
			if (selectedCriteria.Count > 0)
			{
				documentSearchCriteria += string.IsNullOrWhiteSpace(documentSearchCriteria) ? string.Empty : " AND ";
				documentSearchCriteria += " Component = '" + selectedCriteria[0].Value + "' ";
			}
			selectedCriteria = criteriaController.ParseCriteria<Thinkgate.Controls.E3Criteria.DropDownList.ValueObject>("Type").ToList();
			if (selectedCriteria.Count > 0)
			{
				documentSearchCriteria += string.IsNullOrWhiteSpace(documentSearchCriteria) ? string.Empty : " AND ";
				documentSearchCriteria += " FileTypes = '" + selectedCriteria[0].Value + "' ";
			}
          
			string searchText = string.Empty;
			string searchOption = string.Empty;
			List<TextWithDropdown.ValueObject> textSearchList = criteriaController.ParseCriteria<TextWithDropdown.ValueObject>("TextSearch");
			if (textSearchList.Count > 0)
			{
				NameValue confirmedOption = TextSearchDropdownValues().Find(x => x.Name == textSearchList[0].Option) ?? TextSearchDropdownValues().First();
				if (!String.IsNullOrEmpty(textSearchList[0].Text))
				{
					searchText = textSearchList[0].Text;
					searchOption = confirmedOption.Value;
					string[] searchWords = System.Text.RegularExpressions.Regex.Split(searchText, " ");
					string[] searchColumns = new string[] { "Title", "Description", "Keyword" };

					documentSearchCriteria += string.IsNullOrWhiteSpace(documentSearchCriteria) ? string.Empty : " AND ";

					if (searchOption == "key")
					{
						documentSearchCriteria += " (Keyword LIKE '%" + searchText + "%') ";
					}
					else if (searchOption == "any")
					{
						string anyWordsCondition = TextSearchCondition(searchWords, searchColumns, true);
						documentSearchCriteria += anyWordsCondition;
					}
					else if (searchOption == "all")
					{
						string allWordsCondition = TextSearchCondition(searchWords, searchColumns, false);
						documentSearchCriteria += allWordsCondition;
					}
					else if (searchOption == "exact")
					{
						documentSearchCriteria += " ( Title LIKE '%" + searchText + "%' ";
						documentSearchCriteria += " OR Keyword LIKE '%" + searchText + "%' ";
						documentSearchCriteria += " OR Description LIKE '%" + searchText + "%') ";
					}
				}
			}
            
			var dateSelected = criteriaController.ParseCriteria<Thinkgate.Controls.E3Criteria.DateRange.ValueObject>("DateAdded").ToList();
			if (dateSelected.Count > 0)
			{
                documentSearchCriteria += string.IsNullOrWhiteSpace(documentSearchCriteria) ? string.Empty : " AND ";
               
                Master.ChangeCriteriaOrder(ref dateSelected);
                if (dateSelected[0].Type == "Start")
                {
                    documentSearchCriteria += " (convert(varchar,DateAdded,111) >= convert(datetime,'" + dateSelected[0].Date + "',111) ";
                    if (dateSelected.Count > 1 && !string.IsNullOrEmpty(dateSelected[1].Date))
                        documentSearchCriteria += " And convert(varchar,DateAdded,111) <= convert(datetime,'" + dateSelected[1].Date + "',111)) ";
                    else
                        documentSearchCriteria += ")";
                }
                else if (!string.IsNullOrEmpty(dateSelected[0].Date))
                { documentSearchCriteria += " (convert(varchar,DateAdded,111) <= convert(datetime,'" + dateSelected[0].Date + "',111))"; }

			}
			referenceSearchCriteria.SearchCriteria = documentSearchCriteria;
			return referenceSearchCriteria;
		}
        /// <summary>
        /// Builds the QuestionSearchCriteria. Used both from Search Button and from Service
        /// </summary>
        public static ItemImageSearchCriteriaV2 BuildSearchCriteriaObject(ThinkgateUser user, CriteriaController criteriaController, string requestedSortField = null)
        {
            
            /* Sort */
            string sortField = null;
            NameValue nvSortField = SortFields().Find(x => x.Name == requestedSortField);   // ensure that the user given value for sort is in the defined list of options
            if (nvSortField != null) sortField = nvSortField.Value;

            /* Item Banks - Remove from master list based on filter if given */
            var itemBanks = ItemBankMasterList.GetItemBanksForUser(user);
            var selectedItemBanks = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("ItemBank").Select(x => x.Text);
            if (selectedItemBanks.Any()) itemBanks.DeleteByLabel(selectedItemBanks);

            /* Text Search */
            string searchText = string.Empty;
            string searchOption = string.Empty;
            var txtSearchList = criteriaController.ParseCriteria<TextWithDropdown.ValueObject>("TextSearch");
            if (txtSearchList.Count > 0)
            {
                // we ensure that the value the user gave us for text search type is a valid option
                var confirmedOption = TextSearchDropdownValues().Find(x => x.Name == txtSearchList[0].Option) ?? TextSearchDropdownValues().First();
                if (!String.IsNullOrEmpty(txtSearchList[0].Text))
                {
                    searchText = txtSearchList[0].Text;
                    searchOption = confirmedOption.Value;
                }
            }

            /* Courses */
            var selectedGrades = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Grade").Select(x => x.Text).ToList();
            var selectedSubjects = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Subject").Select(x => x.Text).ToList();
            var selectedCourses = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Course").Select(x => x.Text).ToList();
            var selectedStandardSets = new drGeneric_String(criteriaController.ParseCriteria<CheckBoxList.ValueObject>("StandardSet").Select(x => x.Text));     // take straight to drGeneric_String because it's going to SQL
            var filteredCourses = CourseMasterList.GetStandardCoursesForUser(user).FilterByGradesSubjectsStandardSetsAndCourse(selectedGrades, selectedSubjects, selectedStandardSets, selectedCourses);

            var selectedExpirationStatus = criteriaController.ParseCriteria<DropDownList.ValueObject>("ExpirationStatus").FirstOrDefault() != null ?
            criteriaController.ParseCriteria<DropDownList.ValueObject>("ExpirationStatus").FirstOrDefault().Value : "I";
            if (!ShowExpiredItems)
            {
                selectedExpirationStatus = "E";

            }
            drGeneric_String_String selectedExpirationDateRange = new drGeneric_String_String();
            foreach (var val in criteriaController.ParseCriteria<DateRange.ValueObject>("ExpirationDateRange"))
            {
                selectedExpirationDateRange.Add(val.Type == "Start" ? "CreatedDateStart" : "CreatedDateEnd", val.Date);
            }




            /* Build Criteria Object */
            var asc = new ItemImageSearchCriteriaV2()
                                             {
                                                 ItemBanks = itemBanks,
                                                 StandardCourses = filteredCourses,
                                                 TextWords = searchText,
                                                 TextWordsOpt = searchOption,
                                                 GradeLimited = selectedGrades.Count > 0,
                                                 SubjectLimited = selectedSubjects.Count > 0,
                                                 CourseLimited = selectedCourses.Count > 0,
                                                 SortBy = sortField == "ItemBank" || sortField == "Standard"
                                                     ? null
                                                     : sortField,
                                                 ExpirationStatus = selectedExpirationStatus,
                                                 ExpirationDateRange = selectedExpirationDateRange
                                             };
            
            return asc;
        }
		/// <summary>
		/// Gets criteria lookup data from Kentico.
		/// </summary>
		/// <returns></returns>
        //List<LookupDetails> GetLookupDetailsFromCMS()
        //{
        //    List<LookupDetails> lookupData = new List<LookupDetails>();
        //    DataClassInfo customTable = DataClassInfoProvider.GetDataClass("TG.LookupDetails");
        //    if (customTable != null)
        //    {
        //        string kenticoUserName = KenticoHelper.getKenticoUser(SessionObject.LoggedInUser.ToString());
        //        UserInfo userInfo = UserInfoProvider.GetUserInfo(kenticoUserName);

        //        DataSet lookupDataSet = (new CMS.SiteProvider.CustomTableItemProvider(userInfo)).GetItems("TG.LookupDetails", string.Empty, string.Empty);
        //        if (lookupDataSet != null && lookupDataSet.Tables.Count > 0 && lookupDataSet.Tables[0].Rows.Count > 0)
        //        {
        //            foreach (DataRow row in lookupDataSet.Tables[0].Rows)
        //            {
        //                LookupDetails lookupTableEntity = new LookupDetails();

        //                lookupTableEntity.ID = DataIntegrity.ConvertToInt(row["ItemID"]);
        //                lookupTableEntity.Description = row["Description"].ToString();
        //                lookupTableEntity.Enum = DataIntegrity.ConvertToInt(row["Enum"]);
        //                lookupTableEntity.LookupEnum = (LookupType)Enum.Parse(typeof(LookupType), row["LookupEnum"].ToString());

        //                lookupData.Add(lookupTableEntity);
        //            }
        //            return lookupData;
        //        }
        //    }
        //    return null;
        //}

		#endregion

		#region " Extract criteria controls criteria as WHERE condition "

		/// <summary>
		/// Should be moved to BL
		/// </summary>
		/// <param name="criteriaController"></param>
		/// <returns></returns>
		MessageSearchCriteria GetSelectedCriteria(CriteriaController criteriaController)
		{
			/* Get selected user group criteria value */
			MessageSearchCriteria messageSearchCriteria = new MessageSearchCriteria();
			string documentSearchCriteria = string.Empty;
			List<Thinkgate.Controls.E3Criteria.DropDownList.ValueObject> selectedCriteria = null;

			selectedCriteria = criteriaController.ParseCriteria<Thinkgate.Controls.E3Criteria.DropDownList.ValueObject>("UserGroup").ToList();
			if (selectedCriteria.Count > 0)
			{
				documentSearchCriteria += " UserGroupEnum = '" + selectedCriteria[0].Value + "' ";
			}

           

			selectedCriteria = criteriaController.ParseCriteria<Thinkgate.Controls.E3Criteria.DropDownList.ValueObject>("Type").ToList();
            if (selectedCriteria.Count > 0)
            {
                documentSearchCriteria = AppendSQLClause(documentSearchCriteria);
                documentSearchCriteria += " MessageCenterEnum = '" + selectedCriteria[0].Value + "' ";
            }
            

			string searchText = string.Empty;
			string searchOption = string.Empty;
			List<TextWithDropdown.ValueObject> textSearchList = criteriaController.ParseCriteria<TextWithDropdown.ValueObject>("TextSearch");
			if (textSearchList.Count > 0)
			{
				NameValue confirmedOption = TextSearchDropdownValues().Find(x => x.Name == textSearchList[0].Option) ?? TextSearchDropdownValues().First();
				if (!String.IsNullOrEmpty(textSearchList[0].Text))
				{
					searchText = textSearchList[0].Text;
					searchOption = confirmedOption.Value;
					string[] searchWords = System.Text.RegularExpressions.Regex.Split(searchText, " ");
					string[] searchColumns = new string[] { "Title", "Description", "Keyword" };

					documentSearchCriteria = AppendSQLClause(documentSearchCriteria);

					if (searchOption == "key")
					{
						documentSearchCriteria += " (Keyword LIKE '%" + searchText + "%') ";
					}
					else if (searchOption == "any")
					{
						string anyWordsCondition = TextSearchCondition(searchWords, searchColumns, true);
						documentSearchCriteria += anyWordsCondition;
					}
					else if (searchOption == "all")
					{
						string allWordsCondition = TextSearchCondition(searchWords, searchColumns, false);
						documentSearchCriteria += allWordsCondition;
					}
					else if (searchOption == "exact")
					{
						documentSearchCriteria += " ( Title LIKE '%" + searchText + "%' ";
						documentSearchCriteria += " OR Keyword LIKE '%" + searchText + "%' ";
						documentSearchCriteria += " OR Description LIKE '%" + searchText + "%') ";
					}
				}
			}
			var dateSelected = criteriaController.ParseCriteria<Thinkgate.Controls.E3Criteria.DateRange.ValueObject>("DateAdded").ToList();
			if (dateSelected.Count > 0)
			{
                documentSearchCriteria = AppendSQLClause(documentSearchCriteria);
                Master.ChangeCriteriaOrder(ref dateSelected);
                if (dateSelected[0].Type == "Start")
                {                    
                    documentSearchCriteria += " (convert(varchar,DateAdded,111) >= convert(datetime,'" + dateSelected[0].Date + "',111) ";
                    if (dateSelected.Count > 1 && !string.IsNullOrEmpty(dateSelected[1].Date))
                        documentSearchCriteria += " And convert(varchar,DateAdded,111) <= convert(datetime,'" + dateSelected[1].Date + "',111)) ";
                    else
                        documentSearchCriteria += ")";
                }
                else if (!string.IsNullOrEmpty(dateSelected[0].Date))
                { documentSearchCriteria += " (convert(varchar,DateAdded,111) <= convert(datetime,'" + dateSelected[0].Date + "',111))"; }
			}
			var dateSelected1 = criteriaController.ParseCriteria<Thinkgate.Controls.E3Criteria.DateRange.ValueObject>("PostOn").ToList();
			if (dateSelected1.Count > 0)
			{
                documentSearchCriteria = AppendSQLClause(documentSearchCriteria);
                Master.ChangeCriteriaOrder(ref dateSelected1);
                if (dateSelected1[0].Type == "Start")
                {
                    documentSearchCriteria += " (convert(varchar,PostOn,111) >= convert(datetime,'" + dateSelected1[0].Date + "',111) ";
                    if (dateSelected1.Count > 1 && !string.IsNullOrEmpty(dateSelected1[1].Date))
                        documentSearchCriteria += " And PostOn <= convert(datetime,'" + dateSelected1[1].Date + "',111)) ";
                    else
                        documentSearchCriteria += ")";
                }
                else if(!string.IsNullOrEmpty(dateSelected1[0].Date))
                { documentSearchCriteria += " (convert(varchar,PostOn,111) <=  convert(datetime,'" + dateSelected1[0].Date + "',111))"; }
			}
			var dateSelected2 = criteriaController.ParseCriteria<Thinkgate.Controls.E3Criteria.DateRange.ValueObject>("RemoveOn").ToList();
			if (dateSelected2.Count > 0)
			{
                documentSearchCriteria = AppendSQLClause(documentSearchCriteria);
                Master.ChangeCriteriaOrder(ref dateSelected2);
                if (dateSelected2[0].Type == "Start")
                {
                    documentSearchCriteria += " (convert(varchar,RemoveOn,111) >= convert(datetime,'" + dateSelected2[0].Date + "',111) ";
                    if (dateSelected2.Count > 1 && !string.IsNullOrEmpty(dateSelected2[1].Date))
                        documentSearchCriteria += " And convert(varchar,RemoveOn,111) <= convert(datetime,'" + dateSelected2[1].Date + "',111)) ";                    
                    else    
                        documentSearchCriteria += ")";
                }
                else if (!string.IsNullOrEmpty(dateSelected2[0].Date))
                { documentSearchCriteria += " (convert(varchar,RemoveOn,111) <= convert(datetime,'" + dateSelected2[0].Date + "',111))";}
			}
            if (!string.IsNullOrEmpty(documentSearchCriteria))
            {
                string lastString = documentSearchCriteria.Trim().Substring(documentSearchCriteria.Trim().Length - 3);
                documentSearchCriteria = lastString.ToUpper() == "AND" ? documentSearchCriteria.Trim().Substring(0, documentSearchCriteria.Trim().Length - 3) : documentSearchCriteria;
            }
			messageSearchCriteria.SearchCriteria = documentSearchCriteria;
			return messageSearchCriteria;
		}
 /// <summary>
 /// This method populates a StudentSearchCriteria object with values from the Criteria Controller
 /// </summary>
 /// <param name="criteriaController"></param>
 /// <returns></returns>
 private StudentSearchCriteria GetStudentCriteriaFromController(CriteriaController criteriaController)
 {
     var studentSearchCriteria = new StudentSearchCriteria();
     var studentName = criteriaController.ParseCriteria<Text.ValueObject>("StudentName").FirstOrDefault();
     studentSearchCriteria.StudentName = studentName == null ? string.Empty : studentName.Text;
     var studentId = criteriaController.ParseCriteria<Text.ValueObject>("StudentID").FirstOrDefault();
     studentSearchCriteria.StudentID = studentId == null ? string.Empty : studentId.Text;
     var inactiveRti =
         criteriaController.ParseCriteria<CheckBoxList.ValueObject>("RTI").Find(x => x.Text == RtiFormerYear);
     studentSearchCriteria.InactiveRTI = inactiveRti == null ? string.Empty : inactiveRti.Text;
     var tier1Rti = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("RTI")
         .Find(x => x.Text == RtiTier1);
     studentSearchCriteria.Tier1RTI = tier1Rti == null ? string.Empty : tier1Rti.Text;
     var tier2Rti = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("RTI")
         .Find(x => x.Text == RtiTier2);
     studentSearchCriteria.Tier2RTI = tier2Rti == null ? string.Empty : tier2Rti.Text;
     var tier3Rti = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("RTI")
         .Find(x => x.Text == RtiTier3);
     studentSearchCriteria.Tier3RTI = tier3Rti == null ? string.Empty : tier3Rti.Text;
     studentSearchCriteria.Cluster = string.Join(",",
         criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Cluster").Select(x => x.Text).ToList());
     studentSearchCriteria.SchoolTypes = string.Join(",",
         criteriaController.ParseCriteria<CheckBoxList.ValueObject>("SchoolType").Select(x => x.Text).ToList());
     studentSearchCriteria.School =
         Convert.ToInt32(criteriaController.ParseCriteria<DropDownList.ValueObject>("School")
             .Select(x => x.Value)
             .ToList()
             .FirstOrDefault());
     studentSearchCriteria.Grades = string.Join(",",
         criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Grade").Select(x => x.Text).ToList());
     var demo1 = criteriaController.ParseCriteria<Demographics.ValueObject>("Demographics").Find(x => x.DemoField == "1");
     studentSearchCriteria.Demo1 = demo1 == null ? string.Empty : demo1.DemoValue;
     var demo2 = criteriaController.ParseCriteria<Demographics.ValueObject>("Demographics").Find(x => x.DemoField == "2");
     studentSearchCriteria.Demo2 = demo2 == null ? string.Empty : demo2.DemoValue;
     var demo3 = criteriaController.ParseCriteria<Demographics.ValueObject>("Demographics").Find(x => x.DemoField == "3");
     studentSearchCriteria.Demo3 = demo3 == null ? string.Empty : demo3.DemoValue;
     var demo4 = criteriaController.ParseCriteria<Demographics.ValueObject>("Demographics").Find(x => x.DemoField == "4");
     studentSearchCriteria.Demo4 = demo4 == null ? string.Empty : demo4.DemoValue;
     var demo5 = criteriaController.ParseCriteria<Demographics.ValueObject>("Demographics").Find(x => x.DemoField == "5");
     studentSearchCriteria.Demo5 = demo5 == null ? string.Empty : demo5.DemoValue;
     var demo6 = criteriaController.ParseCriteria<Demographics.ValueObject>("Demographics").Find(x => x.DemoField == "6");
     studentSearchCriteria.Demo6 = demo6 == null ? string.Empty : demo6.DemoValue;
     var demo7 = criteriaController.ParseCriteria<Demographics.ValueObject>("Demographics").Find(x => x.DemoField == "7");
     studentSearchCriteria.Demo7 = demo7 == null ? string.Empty : demo7.DemoValue;
     var demo8 = criteriaController.ParseCriteria<Demographics.ValueObject>("Demographics").Find(x => x.DemoField == "8");
     studentSearchCriteria.Demo8 = demo8 == null ? string.Empty : demo8.DemoValue;
     var demo9 = criteriaController.ParseCriteria<Demographics.ValueObject>("Demographics").Find(x => x.DemoField == "9");
     studentSearchCriteria.Demo9 = demo9 == null ? string.Empty : demo9.DemoValue;
     var demo10 = criteriaController.ParseCriteria<Demographics.ValueObject>("Demographics").Find(x => x.DemoField == "10");
     studentSearchCriteria.Demo10 = demo10 == null ? string.Empty : demo10.DemoValue;
     studentSearchCriteria.ClassID = Convert.ToInt32(criteriaController.ParseCriteria<DropDownList.ValueObject>("Class").Select(x => x.Value).ToList().FirstOrDefault());
     return studentSearchCriteria;
 }
 /// <summary>
 /// This method populates a StudentSearchCriteria object with values from the Criteria Controller
 /// </summary>
 /// <param name="criteriaController"></param>
 /// <returns></returns>
 private IMStudentSearchCriteria GetStudentCriteriaFromController(CriteriaController criteriaController)
 {
     var studentSearchCriteria = new IMStudentSearchCriteria();
     var studentName = criteriaController.ParseCriteria<Text.ValueObject>("StudentName").FirstOrDefault();
     studentSearchCriteria.StudentName = studentName == null ? string.Empty : studentName.Text;
     var studentId = criteriaController.ParseCriteria<Text.ValueObject>("StudentID").FirstOrDefault();
     studentSearchCriteria.StudentID = studentId == null ? string.Empty : studentId.Text;
     var inactiveRti =
         criteriaController.ParseCriteria<CheckBoxList.ValueObject>("RTI").Find(x => x.Text == RtiFormerYear);
     studentSearchCriteria.InactiveRTI = inactiveRti == null ? string.Empty : inactiveRti.Text;
     var tier1Rti = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("RTI")
         .Find(x => x.Text == RtiTier1);
     studentSearchCriteria.Tier1RTI = tier1Rti == null ? string.Empty : tier1Rti.Text;
     var tier2Rti = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("RTI")
         .Find(x => x.Text == RtiTier2);
     studentSearchCriteria.Tier2RTI = tier2Rti == null ? string.Empty : tier2Rti.Text;
     var tier3Rti = criteriaController.ParseCriteria<CheckBoxList.ValueObject>("RTI")
         .Find(x => x.Text == RtiTier3);
     studentSearchCriteria.Tier3RTI = tier3Rti == null ? string.Empty : tier3Rti.Text;
     studentSearchCriteria.Cluster = string.Join(",",
         criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Cluster").Select(x => x.Text).ToList());
     studentSearchCriteria.SchoolTypes = string.Join(",",
         criteriaController.ParseCriteria<CheckBoxList.ValueObject>("SchoolType").Select(x => x.Text).ToList());
     studentSearchCriteria.School =
         Convert.ToInt32(criteriaController.ParseCriteria<DropDownList.ValueObject>("School")
             .Select(x => x.Value)
             .ToList()
             .FirstOrDefault());
     studentSearchCriteria.Grades = string.Join(",",
         criteriaController.ParseCriteria<CheckBoxList.ValueObject>("Grade").Select(x => x.Text).ToList());
     studentSearchCriteria.ClassID = Convert.ToInt32(criteriaController.ParseCriteria<DropDownList.ValueObject>("Class").Select(x => x.Value).ToList().FirstOrDefault());
     ClassId = studentSearchCriteria.ClassID > 0 ? studentSearchCriteria.ClassID : ClassId;
     studentSearchCriteria.GroupID = Convert.ToInt32(criteriaController.ParseCriteria<DropDownList.ValueObject>("Group").Select(x => x.Value).ToList().FirstOrDefault());
     GroupId = studentSearchCriteria.GroupID > 0 ? studentSearchCriteria.GroupID : GroupId;
     return studentSearchCriteria;
 }
        public void BindRadGridResults(CriteriaController model)
        {
            this.dvEmpty.Visible = false;

            this.radParentStudentAccess.Visible = false;
            this.divChildGrid.Visible = false;
            radStudentInformation.Visible = false;
            divStudentGrid.Visible = false;

            string schoolType = string.Join(",", model.ParseCriteria<E3Criteria.RadDropDownList.ValueObject>(this.ddlSchoolType.CriteriaName).Select(x => x.Value));
            string schoolId = string.Join(",", model.ParseCriteria<E3Criteria.RadDropDownList.ValueObject>(this.ddlSchool.CriteriaName).Select(x => x.Value));
            string grade = string.Join(",", model.ParseCriteria<E3Criteria.RadDropDownList.ValueObject>(this.ddlStudentGrade.CriteriaName).Select(x => x.Value));
            string studentId = string.Join(",", model.ParseCriteria<E3Criteria.RadDropDownList.ValueObject>(this.ddlStudentId.CriteriaName).Select(x => x.Value));
            string studentName = string.Join(",", model.ParseCriteria<E3Criteria.RadDropDownList.ValueObject>(this.ddlStudentName.CriteriaName).Select(x => x.Text));

            ViewState["schoolType"] = schoolType;
            ViewState["schoolId"] = schoolId;
            ViewState["grade"] = grade;
            ViewState["studentId"] = studentId;

            if (ViewState["studentName"] != null)
            {
                if (!string.IsNullOrEmpty(Convert.ToString(ViewState["studentName"])))
                {
                    if (Convert.ToString(ViewState["studentName"]) == studentName)
                    {
                        this.radParentStudentAccess.Visible = true;
                        this.divChildGrid.Visible = true;
                        radStudentInformation.Visible = true;
                        divStudentGrid.Visible = true;
                    }
                }
            }

            ViewState["studentName"] = studentName;

            var data = this.ViewModel.GetParentStudentPortalAdministrationReport(schoolType, schoolId, grade, studentId, studentName);

            var sb = SchoolMasterList.GetSchoolsForUser(SessionObject.LoggedInUser).Select(x => x.Name).Distinct().ToList();

            if (data != null & data.Rows.Count > 0)
            {
                var filteredDataforloggedInUser =
                    data.AsEnumerable()
                        .Where(x => sb.Contains(Convert.ToString(x["SchoolName"])))
                        .CopyToDataTable();


                if (filteredDataforloggedInUser != null
                    && filteredDataforloggedInUser.Rows.Count > 0)
                {
                    ParentData = filteredDataforloggedInUser;
                    lblNoResult.Visible = false;
                    this.radParentGrid.Visible = true;
                    this.divsave.Visible = true;

                    radParentGrid.CurrentPageIndex = 0;

                    this.radParentGrid.DataSource = filteredDataforloggedInUser;
                    this.radParentGrid.DataBind();
                }
                else
                {
                    lblNoResult.Visible = true;
                    this.radParentGrid.Visible = false;
                    this.divsave.Visible = false;
                    this.divChildGrid.Visible = false;
                    this.divStudentGrid.Visible = false;
                    this.imgExport.Visible = false;
                }
            }
            else
            {
                lblNoResult.Visible = true;
                this.radParentGrid.Visible = false;
                this.divsave.Visible = false;
                this.divChildGrid.Visible = false;
                this.divStudentGrid.Visible = false;
                this.imgExport.Visible = false;

            }
        }