public async Task FilterResultsIgnoreCampaignCodeWhenAlreadySet() { // arrange var controller = BuildCourseController("*/*"); var bodyViewModel = new BodyViewModel { CurrentSearchTerm = "Maths", FreeCourseSearch = true, SideBar = new SideBarViewModel(), CourseSearchFilters = new CourseSearchFilters() { CampaignCode = "test", }, IsTest = true, }; // act var result = await controller.FilterResults(bodyViewModel, "TestLocation (Test Area)|-123.45|67.89").ConfigureAwait(false); // assert var viewResult = Assert.IsType <ViewResult>(result); var model = Assert.IsAssignableFrom <BodyViewModel>(viewResult.ViewData.Model); Assert.NotEqual(model.CourseSearchFilters.CampaignCode, CourseController.FreeSearchCampaignCode); controller.Dispose(); }
public async Task <IActionResult> Body(string?article) { var contentPageModel = await GetContentPageAsync(article).ConfigureAwait(false); if (contentPageModel == null) { return(NotFound()); } var viewModel = new BodyViewModel(); viewModel.Category = contentPageModel.Title; var jpsToRetrieveHrefs = contentPageModel.Links?.Where(x => x.LinkValue.Key == nameof(JobProfile).ToLower()).Select(z => z.LinkValue.Value.Href); if (jpsToRetrieveHrefs != null) { var jobProfiles = await Task.WhenAll(jpsToRetrieveHrefs?.Select(x => jobProfilePageContentService.GetByUriAsync(x))).ConfigureAwait(false); if (jobProfiles == null || !jobProfiles.Any()) { return(NoContent()); } viewModel.Profiles = jobProfiles .Where(x => x != null) .Select(x => new JobProfileListItemViewModel(x.Title !, x.CanonicalName !, x.Occupation?.OccupationLabels?.Select(l => l.Title !) ?? null, x.Description !)); } return(this.NegotiateContentResult(viewModel, contentPageModel)); }
private IActionResult ValidateMarkup(BodyViewModel bodyViewModel, JobProfileModel jobProfileModel) { if (bodyViewModel.Segments != null) { foreach (var segmentModel in bodyViewModel.Segments) { var markup = segmentModel.Markup.Value; if (!string.IsNullOrWhiteSpace(markup)) { continue; } switch (segmentModel.Segment) { case JobProfileSegment.Overview: case JobProfileSegment.HowToBecome: case JobProfileSegment.WhatItTakes: throw new InvalidProfileException($"JobProfile with Id {jobProfileModel.DocumentId} is missing markup for segment {segmentModel.Segment.ToString()}"); case JobProfileSegment.RelatedCareers: case JobProfileSegment.CurrentOpportunities: case JobProfileSegment.WhatYouWillDo: case JobProfileSegment.CareerPathsAndProgression: { segmentModel.Markup = segmentService.GetOfflineSegment(segmentModel.Segment).OfflineMarkup; break; } } } } return(this.NegotiateContentResult(bodyViewModel, jobProfileModel.Segments)); }
public async Task <IActionResult> Body(string category, string article) { const string ArticlePlaceholder = "{0}"; logger.LogInformation($"{nameof(Body)} has been called"); var viewModel = new BodyViewModel(); var contentPageModel = await GetContentPageAsync(category, article).ConfigureAwait(false); if (contentPageModel != null) { contentPageModel.Content = contentPageModel.Content.Replace(ArticlePlaceholder, article, StringComparison.OrdinalIgnoreCase); mapper.Map(contentPageModel, viewModel); logger.LogInformation($"{nameof(Body)} has returned content for: {article}"); return(this.NegotiateContentResult(viewModel, contentPageModel)); } var alternateContentPageModel = await GetAlternativeContentPageAsync(category, article).ConfigureAwait(false); if (alternateContentPageModel != null) { var alternateUrl = $"{Request.GetBaseAddress()}{alternateContentPageModel.Category}/{alternateContentPageModel.CanonicalName}"; logger.LogWarning($"{nameof(Body)} has been redirected for: {category}/{article} to {alternateUrl}"); return(RedirectPermanentPreserveMethod(alternateUrl)); } logger.LogWarning($"{nameof(Body)} has not returned any content for: {category}/{article}"); return(NotFound()); }
public async Task ReturnsSuccessForHtmlMediaType(string mediaTypeName) { // Arrange var expectedResult = A.Fake <JobProfileOverviewSegmentModel>(); expectedResult.Data = A.Fake <JobProfileOverviewSegmentDataModel>(); var fakeBodyViewModel = new BodyViewModel { CanonicalName = JobProfileName, SequenceNumber = 123, Data = new BodyDataViewModel(), }; var controller = BuildSegmentController(mediaTypeName); A.CallTo(() => FakeJobProfileOverviewSegmentService.GetByNameAsync(A <string> .Ignored)).Returns(expectedResult); A.CallTo(() => FakeMapper.Map <BodyViewModel>(A <JobProfileOverviewSegmentModel> .Ignored)).Returns(fakeBodyViewModel); // Act var result = await controller.Document(JobProfileName).ConfigureAwait(false); // Assert A.CallTo(() => FakeJobProfileOverviewSegmentService.GetByNameAsync(A <string> .Ignored)).MustHaveHappenedOnceExactly(); A.CallTo(() => FakeMapper.Map <BodyViewModel>(A <JobProfileOverviewSegmentModel> .Ignored)).MustHaveHappenedOnceExactly(); var viewResult = Assert.IsType <ViewResult>(result); Assert.IsAssignableFrom <BodyViewModel>(viewResult.ViewData.Model); controller.Dispose(); }
public async Task <IActionResult> Body(PageRequestModel pageRequestModel) { var(location, article) = PagesControlerHelpers.ExtractPageLocation(pageRequestModel); var viewModel = new BodyViewModel(); var contentPageModel = await pagesControlerHelpers.GetContentPageAsync(location, article).ConfigureAwait(false); if (contentPageModel != null) { mapper.Map(contentPageModel, viewModel); logger.LogInformation($"{nameof(Body)} has returned content for: /{location}/{article}"); return(this.NegotiateContentResult(viewModel, contentPageModel)); } var redirectedContentPageModel = await pagesControlerHelpers.GetRedirectedContentPageAsync(location, article).ConfigureAwait(false); if (redirectedContentPageModel != null) { var pageLocation = $"{Request.GetBaseAddress()}".TrimEnd('/') + redirectedContentPageModel.PageLocation.TrimEnd('/'); var redirectedUrl = $"{pageLocation}/{redirectedContentPageModel.CanonicalName}"; logger.LogWarning($"{nameof(Document)} has been redirected for: /{location}/{article} to {redirectedUrl}"); return(RedirectPermanent(redirectedUrl)); } logger.LogWarning($"{nameof(Body)} has not returned any content for: /{location}/{article}"); return(NotFound()); }
public async Task FilterResultsSetsStartDateValuesWhenPassedIn(string startDateValue, int from, int to, StartDate start) { // arrange var controller = BuildCourseController("*/*"); var bodyViewModel = new BodyViewModel { CurrentSearchTerm = "Maths", SideBar = new SideBarViewModel() { StartDateValue = startDateValue, }, IsTest = true, }; // act var result = await controller.FilterResults(bodyViewModel, "TestLocation (Test Area)|-123.45|67.89").ConfigureAwait(false); // assert var viewResult = Assert.IsType <ViewResult>(result); var model = Assert.IsAssignableFrom <BodyViewModel>(viewResult.ViewData.Model); Assert.Equal(model.CourseSearchFilters.StartDate, start); Assert.Equal(model.CourseSearchFilters.StartDateFrom, DateTime.Today.AddMonths(from)); Assert.Equal(model.CourseSearchFilters.StartDateTo, to == -1 ? DateTime.MinValue : DateTime.Today.AddMonths(to)); controller.Dispose(); }
public async Task BodyThrowsInvalidProfileExceptionWhenCriticalSegmentDoesNotExist() { // Arrange var controller = BuildProfileController(MediaTypeNames.Application.Json); var bodyViewModel = new BodyViewModel { CanonicalName = FakeArticleName, Segments = new List <SegmentModel> { new SegmentModel { Segment = JobProfileSegment.WhatItTakes, Markup = new HtmlString("someContent"), }, new SegmentModel { Segment = JobProfileSegment.HowToBecome, Markup = new HtmlString("someContent"), }, }, }; A.CallTo(() => FakeJobProfileService.GetByNameAsync(A <string> .Ignored)).Returns(A.Fake <JobProfileModel>()); A.CallTo(() => FakeJobProfileService.GetByAlternativeNameAsync(A <string> .Ignored)).Returns((JobProfileModel)null); A.CallTo(() => FakeMapper.Map <BodyViewModel>(A <JobProfileModel> .Ignored)).Returns(bodyViewModel); A.CallTo(() => FakeRedirectionSecurityService.IsValidHost(A <Uri> .Ignored)).Returns(true); // Act await Assert.ThrowsAsync <InvalidProfileException>(async() => await controller.Body(FakeArticleName).ConfigureAwait(false)).ConfigureAwait(false); controller.Dispose(); }
public async Task CourseControllerFilterResultsReturnsSuccess(string mediaTypeName) { var controller = BuildCourseController(mediaTypeName); var bodyViewModel = new BodyViewModel { CurrentSearchTerm = "Maths", SideBar = new SideBarViewModel { DistanceValue = "15 miles", CourseType = new FiltersListViewModel { SelectedIds = new List <string> { "Online" }, }, CourseHours = new FiltersListViewModel { SelectedIds = new List <string> { "Full time" }, }, CourseStudyTime = new FiltersListViewModel { SelectedIds = new List <string> { "Daytime" }, }, QualificationLevels = new FiltersListViewModel { SelectedIds = new List <string> { "1" }, }, }, IsTest = true, }; var returnedCourseData = new CourseSearchResult { Courses = new List <Course> { new Course { Title = "Maths", CourseId = "1", AttendancePattern = "Online", Description = "This is a test description - over 220 chars" + new string(' ', 220) }, }, }; A.CallTo(() => FakeFindACoursesService.GetFilteredData(A <CourseSearchFilters> .Ignored, CourseSearchOrderBy.Relevance, 1)).Returns(returnedCourseData); var result = await controller.FilterResults(bodyViewModel, string.Empty).ConfigureAwait(false); Assert.IsType <ViewResult>(result); controller.Dispose(); }
private IActionResult ValidateJobProfile(BodyViewModel bodyViewModel, JobProfileModel jobProfileModel) { var overviewExists = bodyViewModel.Segments.Any(s => s.Segment == JobProfileSegment.Overview); var howToBecomeExists = bodyViewModel.Segments.Any(s => s.Segment == JobProfileSegment.HowToBecome); var whatItTakesExists = bodyViewModel.Segments.Any(s => s.Segment == JobProfileSegment.WhatItTakes); if (!overviewExists || !howToBecomeExists || !whatItTakesExists) { throw new InvalidProfileException($"JobProfile with Id {jobProfileModel.DocumentId} is missing critical segment information"); } return(this.ValidateMarkup(bodyViewModel, jobProfileModel)); }
public SegmentControllerBodyTitlePrefixTests() { testBodyViewModel = A.Dummy <BodyViewModel>(); testBodyViewModel.Data = A.Dummy <BodyDataViewModel>(); testBodyViewModel.Data.Courses = A.Dummy <BodyCoursesViewModel>(); testSegmentModel = new CurrentOpportunitiesSegmentModel() { Data = new CurrentOpportunitiesSegmentDataModel() { }, }; }
public async Task <IActionResult> Body(string articleName) { logService.LogInformation($"{nameof(this.Body)} has been called"); var model = new BodyViewModel { Content = new HtmlString("Find a course: Body element") }; model.SideBar = GetSideBarViewModel(); model.SideBar.OrderByOptions = ListFilters.GetOrderByOptions(); logService.LogInformation($"{nameof(this.Body)} generated the model and ready to pass to the view"); return(await SearchCourse(string.Empty).ConfigureAwait(true)); }
public async Task <IActionResult> FilterResults(BodyViewModel model) { logService.LogInformation($"{nameof(this.FilterResults)} has been called"); var newBodyViewModel = GenerateModel(model); try { model.Results = await findACourseService.GetFilteredData(newBodyViewModel.CourseSearchFilters, newBodyViewModel.CourseSearchOrderBy, model.RequestPage).ConfigureAwait(false); } catch (Exception ex) { logService.LogError($"{nameof(this.FilterResults)} threw an exception" + ex.Message); } logService.LogInformation($"{nameof(this.FilterResults)} generated the model and ready to pass to the view"); return(Results(model)); }
public async Task <IActionResult> Profile(Guid documentId) { logService.LogInformation($"{nameof(Profile)} has been called"); var viewModel = new BodyViewModel(); var jobProfileModel = await jobProfileService.GetByIdAsync(documentId).ConfigureAwait(false); if (jobProfileModel != null) { mapper.Map(jobProfileModel, viewModel); logService.LogInformation($"{nameof(Profile)} has returned a profile for: {documentId}"); return(this.NegotiateContentResult(viewModel, jobProfileModel)); } logService.LogWarning($"{nameof(Profile)} has not returned a profile for: {documentId}"); return(NoContent()); }
public Task <IActionResult> FilterResults(BodyViewModel model, string location) { logService.LogInformation($"{nameof(this.FilterResults)} has been called"); if (model == null) { logService.LogError($"model is null for method: {nameof(FilterResults)} on controller {nameof(CourseController)}"); return(Task.FromResult <IActionResult>(StatusCode((int)HttpStatusCode.NotFound))); } if (model.SideBar.SuggestedLocation != model.SideBar.TownOrPostcode) { //if the user changed the text for the location invalidate the coordinates model.SideBar.Coordinates = null; } else if (!string.IsNullOrEmpty(location)) { //If the user clicked on one of the suggested locations var indexOfLocationSpliter = location.IndexOf("|", StringComparison.Ordinal); model.SideBar.TownOrPostcode = location.Substring(0, indexOfLocationSpliter); model.SideBar.Coordinates = location[(indexOfLocationSpliter + 1)..];
public bool Create(BodyViewModel model, IDataSourceError error) { if (this.CurrentUser.IsInRole("Company")) { error.Error.AppendLine("公司端不可新增"); return(false); } var body = new Body { CustomerId = model.CustomerId, HealthSpine = model.HealthSpine, HealthBackPain = model.HealthBackPain, HealthOther = model.HealthOther, CurveChest = model.CurveChest, CurveArm = model.CurveArm, CurveButtock = model.CurveButtock, CurveStomachWaistAbdomen = model.CurveStomachWaistAbdomen, CurveThigh = model.CurveThigh, CurveCalf = model.CurveCalf, CurveFatSoft = model.CurveFatSoft, CurveFatHard = model.CurveFatHard, CurveFatOrange = model.CurveFatOrange, CurveFatTangled = model.CurveFatTangled, CurveFatOther = model.CurveFatOther, Diagnosis = model.Diagnosis }; this.DbContext.Bodies.Add(body); bool result = false; try { this.DbContext.SaveChanges(); result = true; } catch { } return(result); }
public async Task <IActionResult> SearchCourse(string searchTerm) { logService.LogInformation($"{nameof(this.SearchCourse)} has been called"); var model = new BodyViewModel(); var courseSearchFilters = new CourseSearchFilters { CourseType = new List <CourseType> { CourseType.All }, CourseHours = new List <CourseHours> { CourseHours.All }, StartDate = StartDate.Anytime, CourseStudyTime = new List <Fac.AttendancePattern> { Fac.AttendancePattern.Undefined }, SearchTerm = string.IsNullOrEmpty(searchTerm) ? string.Empty : searchTerm, }; model.SideBar = GetSideBarViewModel(); model.SideBar.OrderByOptions = ListFilters.GetOrderByOptions(); model.CurrentSearchTerm = searchTerm; model.SideBar.CurrentSearchTerm = searchTerm; model.RequestPage = 1; try { model.Results = await findACourseService.GetFilteredData(courseSearchFilters, CourseSearchOrderBy.StartDate, 1).ConfigureAwait(true); } catch (Exception ex) { logService.LogError($"{nameof(this.SearchCourse)} threw an exception" + ex.Message); } logService.LogInformation($"{nameof(this.SearchCourse)} generated the model and ready to pass to the view"); return(Results(model)); }
public bool?Update(int key, BodyViewModel model, IDataSourceError error) { var body = this.SingleOrDefault(key); if (body == null) { return(this.Create(model, error)); } else { body.HealthSpine = model.HealthSpine; body.HealthBackPain = model.HealthBackPain; body.HealthOther = model.HealthOther; body.CurveChest = model.CurveChest; body.CurveArm = model.CurveArm; body.CurveButtock = model.CurveButtock; body.CurveStomachWaistAbdomen = model.CurveStomachWaistAbdomen; body.CurveThigh = model.CurveThigh; body.CurveCalf = model.CurveCalf; body.CurveFatSoft = model.CurveFatSoft; body.CurveFatHard = model.CurveFatHard; body.CurveFatOrange = model.CurveFatOrange; body.CurveFatTangled = model.CurveFatTangled; body.CurveFatOther = model.CurveFatOther; body.Diagnosis = model.Diagnosis; } bool result = false; try { this.DbContext.SaveChanges(); result = true; } catch { } return(result); }
public async Task FilterResultsSetsLocationFieldsWhenPassedIn() { // arrange var controller = BuildCourseController("*/*"); var bodyViewModel = new BodyViewModel { CurrentSearchTerm = "Maths", SideBar = new SideBarViewModel(), IsTest = true, }; // act var result = await controller.FilterResults(bodyViewModel, "TestLocation (Test Area)|-123.45|67.89").ConfigureAwait(false); // assert var viewResult = Assert.IsType <ViewResult>(result); var model = Assert.IsAssignableFrom <BodyViewModel>(viewResult.ViewData.Model); model.SideBar.TownOrPostcode.Should().Be("TestLocation (Test Area)"); model.SideBar.Coordinates.Should().Be("-123.45|67.89"); controller.Dispose(); }
public async Task <IActionResult> Page(ParamValues paramValues, bool isTest) { logService.LogInformation($"{nameof(this.Page)} has been called"); var isPostcode = !string.IsNullOrEmpty(paramValues.Town) ? (bool?)paramValues.Town.IsPostcode() : null; paramValues.D = isPostcode.HasValue && isPostcode.Value ? 1 : 0; var model = new BodyViewModel { CurrentSearchTerm = paramValues.SearchTerm, SideBar = new SideBarViewModel { TownOrPostcode = paramValues.Town, DistanceValue = paramValues.Distance, CourseType = ConvertStringToFiltersListViewModel(paramValues.CourseType), CourseHours = ConvertStringToFiltersListViewModel(paramValues.CourseHours), CourseStudyTime = ConvertStringToFiltersListViewModel(paramValues.CourseStudyTime), StartDateValue = paramValues.StartDate, CurrentSearchTerm = paramValues.SearchTerm, FiltersApplied = paramValues.FilterA, SelectedOrderByValue = paramValues.OrderByValue, D = paramValues.D, }, RequestPage = paramValues.Page, SelectedDistanceValue = paramValues.Distance, IsNewPage = true, IsTest = isTest, }; logService.LogInformation($"{nameof(this.Page)} generated the model and ready to pass to the view"); model.FromPaging = true; return(await FilterResults(model).ConfigureAwait(false)); }
public async Task CourseControllerFilterResultsThrowsException(string mediaTypeName) { // arrange var controller = BuildCourseController(mediaTypeName); var bodyViewModel = new BodyViewModel { CurrentSearchTerm = "Maths", SideBar = new SideBarViewModel(), IsTest = true, }; A.CallTo(() => FakeFindACoursesService.GetFilteredData(A <CourseSearchFilters> .Ignored, CourseSearchOrderBy.Relevance, 1)).Throws(new Exception()); // act var result = await controller.FilterResults(bodyViewModel).ConfigureAwait(false); // assert var viewResult = Assert.IsType <ViewResult>(result); var model = Assert.IsAssignableFrom <BodyViewModel>(viewResult.ViewData.Model); Assert.Null(model.Results); controller.Dispose(); }
public async Task BodyReturnsOfflineMarkupWhenNonCriticalSegmentsHaveNoMarkup(List <SegmentModel> segments) { // Arrange var controller = BuildProfileController(MediaTypeNames.Application.Json); var bodyViewModel = new BodyViewModel { CanonicalName = FakeArticleName, Segments = segments, }; var offlineSegmentModel = new OfflineSegmentModel { OfflineMarkup = new HtmlString("<h1>Some offline markup for this non-critical segment</h1>"), }; A.CallTo(() => FakeJobProfileService.GetByNameAsync(A <string> .Ignored)).Returns(A.Fake <JobProfileModel>()); A.CallTo(() => FakeJobProfileService.GetByAlternativeNameAsync(A <string> .Ignored)).Returns((JobProfileModel)null); A.CallTo(() => FakeMapper.Map <BodyViewModel>(A <JobProfileModel> .Ignored)).Returns(bodyViewModel); A.CallTo(() => FakeSegmentService.GetOfflineSegment(A <JobProfileSegment> .Ignored)).Returns(offlineSegmentModel); A.CallTo(() => FakeRedirectionSecurityService.IsValidHost(A <Uri> .Ignored)).Returns(true); // Act var result = await controller.Body(FakeArticleName).ConfigureAwait(false); // Assert var okObjectResult = result as OkObjectResult; var resultViewModel = Assert.IsAssignableFrom <BodyViewModel>(okObjectResult?.Value); var nonCriticalSegment = segments.FirstOrDefault(s => s.Segment != JobProfileSegment.Overview && s.Segment != JobProfileSegment.HowToBecome && s.Segment != JobProfileSegment.WhatItTakes); var resultSegmentModel = resultViewModel.Segments.FirstOrDefault(s => s.Segment == nonCriticalSegment?.Segment); Assert.Equal((int)HttpStatusCode.OK, okObjectResult.StatusCode); A.CallTo(() => FakeSegmentService.GetOfflineSegment(A <JobProfileSegment> .Ignored)).MustHaveHappenedOnceExactly(); Assert.Equal(offlineSegmentModel.OfflineMarkup.Value, resultSegmentModel?.Markup.Value); controller.Dispose(); }
public List <BaseItemViewModel> SelectAllEquipment() { var list = new List <BaseItemViewModel>(); using (var con = new SQLiteConnection(_cs)) { con.Open(); using (var cmd = new SQLiteCommand("select * from Equipment", con)) { using (var rdr = cmd.ExecuteReader()) { while (rdr.Read()) { BaseItemViewModel item; var type = (EquipmentType)rdr.GetInt32(2); switch (type) { case EquipmentType.Slot: return(null); case EquipmentType.Mainhand: item = new MainhandViewModel(_messenger); break; case EquipmentType.Offhand: item = new OffhandViewModel(_messenger); break; case EquipmentType.Head: item = new HeadViewModel(_messenger); break; case EquipmentType.Body: item = new BodyViewModel(_messenger); break; case EquipmentType.Neck: item = new NeckViewModel(_messenger); break; case EquipmentType.Ring: item = new RingViewModel(_messenger); break; case EquipmentType.Accessory: item = new AccessoryViewModel(_messenger); break; case EquipmentType.Pet: item = new PetViewModel(_messenger); break; case EquipmentType.Mount: item = new MountViewModel(_messenger); break; default: return(null); } item.ItemName = rdr.GetString(0); item.Tier = rdr.GetInt32(1); item.Slot = (EquipmentType)rdr.GetInt32(2); item.Quality = (ItemQuality)rdr.GetInt32(3); item.Stats = new StatsViewModel { Power = (double)rdr.GetDecimal(5), Stamina = (double)rdr.GetDecimal(6), Agility = (double)rdr.GetDecimal(7), AltPower = (double)rdr.GetDecimal(8), AltStamina = (double)rdr.GetDecimal(9), AltAgility = (double)rdr.GetDecimal(10), DamageBonus = (double)rdr.GetDecimal(11), HealthBonus = (double)rdr.GetDecimal(12), SpeedBonus = (double)rdr.GetDecimal(13), CriticalChance = (double)rdr.GetDecimal(14), CriticalDamage = (double)rdr.GetDecimal(15), DamageEnrage = (double)rdr.GetDecimal(16), DualStrike = (double)rdr.GetDecimal(17), EmpowerChance = (double)rdr.GetDecimal(18), QuadStrike = (double)rdr.GetDecimal(19), EvadeChance = (double)rdr.GetDecimal(20), BlockChance = (double)rdr.GetDecimal(21), LifeSteal = (double)rdr.GetDecimal(22), DeflectChance = (double)rdr.GetDecimal(23), AbsorbChance = (double)rdr.GetDecimal(24), DamageReduction = (double)rdr.GetDecimal(25), RedirectChance = (double)rdr.GetDecimal(26), ItemFind = (double)rdr.GetDecimal(27), GoldFind = (double)rdr.GetDecimal(28), Experience = (double)rdr.GetDecimal(29), MovementSpeed = (double)rdr.GetDecimal(30), CaptureRate = (double)rdr.GetDecimal(31) }; list.Add(item); } } } con.Close(); } return(list); }
public async Task <AjaxModel> AjaxChanged(string appData) { if (string.IsNullOrWhiteSpace(appData)) { throw new ArgumentNullException(nameof(appData)); } var paramValues = System.Text.Json.JsonSerializer.Deserialize <ParamValues>(appData); bool?isPostcode = null; var model = new BodyViewModel { CurrentSearchTerm = paramValues.SearchTerm, SideBar = new SideBarViewModel { TownOrPostcode = paramValues.Town, DistanceValue = paramValues.Distance, CourseType = ConvertStringToFiltersListViewModel(paramValues.CourseType), CourseHours = ConvertStringToFiltersListViewModel(paramValues.CourseHours), CourseStudyTime = ConvertStringToFiltersListViewModel(paramValues.CourseStudyTime), StartDateValue = paramValues.StartDate, CurrentSearchTerm = paramValues.SearchTerm, FiltersApplied = paramValues.FilterA, SelectedOrderByValue = paramValues.OrderByValue, }, RequestPage = paramValues.Page, IsNewPage = true, IsTest = paramValues.IsTest, SelectedDistanceValue = paramValues.Distance, IsResultBody = true, }; var newBodyViewModel = GenerateModel(model); try { model.Results = await findACourseService.GetFilteredData(newBodyViewModel.CourseSearchFilters, newBodyViewModel.CourseSearchOrderBy, model.RequestPage).ConfigureAwait(false); foreach (var item in model.Results.Courses) { if (item.Description.Length > 220) { item.Description = item.Description.Substring(0, 200) + "..."; } } isPostcode = !string.IsNullOrEmpty(paramValues.Town) ? (bool?)paramValues.Town.IsPostcode() : null; if (!model.IsTest) { TempData["params"] = $"{nameof(paramValues.SearchTerm)}={paramValues.SearchTerm}&" + $"{nameof(paramValues.Town)}={paramValues.Town}&" + $"{nameof(paramValues.CourseType)}={paramValues.CourseType}&" + $"{nameof(paramValues.CourseHours)}={paramValues.CourseHours}&" + $"{nameof(paramValues.CourseStudyTime)}={paramValues.CourseStudyTime}&" + $"{nameof(paramValues.StartDate)}={paramValues.StartDate}&" + $"{nameof(paramValues.Distance)}={paramValues.Distance}&" + $"{nameof(paramValues.FilterA)}={paramValues.FilterA}&" + $"{nameof(paramValues.Page)}={paramValues.Page}&" + $"{nameof(paramValues.OrderByValue)}={paramValues.OrderByValue}"; } } catch (Exception ex) { logService.LogError($"{nameof(this.FilterResults)} threw an exception" + ex.Message); } var viewAsString = await viewHelper.RenderViewAsync(this, "~/Views/Course/_results.cshtml", model, true).ConfigureAwait(false); return(new AjaxModel { HTML = viewAsString, Count = model.Results?.ResultProperties != null ? model.Results.ResultProperties.TotalResultCount : 0, IsPostcode = isPostcode }); }
public async Task <AjaxModel> AjaxChanged(string appData) { if (string.IsNullOrWhiteSpace(appData)) { throw new ArgumentNullException(nameof(appData)); } var paramValues = System.Text.Json.JsonSerializer.Deserialize <ParamValues>(appData); var model = new BodyViewModel { CurrentSearchTerm = paramValues.SearchTerm, SideBar = new SideBarViewModel { TownOrPostcode = WebUtility.HtmlEncode(paramValues.Town), DistanceValue = paramValues.Distance, CourseType = ConvertStringToFiltersListViewModel(paramValues.CourseType), CourseHours = ConvertStringToFiltersListViewModel(paramValues.CourseHours), CourseStudyTime = ConvertStringToFiltersListViewModel(paramValues.CourseStudyTime), QualificationLevels = string.IsNullOrEmpty(paramValues.QualificationLevels) ? new FiltersListViewModel() : ConvertStringToFiltersListViewModel(paramValues.QualificationLevels), StartDateValue = paramValues.StartDate, CurrentSearchTerm = paramValues.SearchTerm, FiltersApplied = paramValues.FilterA, SelectedOrderByValue = paramValues.OrderByValue, Coordinates = WebUtility.HtmlEncode(paramValues.Coordinates), }, RequestPage = paramValues.Page, IsNewPage = true, IsTest = paramValues.IsTest, SelectedDistanceValue = paramValues.Distance, IsResultBody = true, CourseSearchFilters = new CourseSearchFilters { CampaignCode = paramValues.CampaignCode, }, }; if (paramValues.CampaignCode == "LEVEL3_FREE") { model.FreeCourseSearch = true; } var newBodyViewModel = await GenerateModelAsync(model).ConfigureAwait(false); try { model.Results = await findACourseService.GetFilteredData(newBodyViewModel.CourseSearchFilters, newBodyViewModel.CourseSearchOrderBy, model.RequestPage).ConfigureAwait(false); foreach (var item in model.Results?.Courses) { if (item.Description.Length > 220) { item.Description = item.Description.Substring(0, 200) + "..."; } } if (!model.IsTest) { TempData["params"] = $"{nameof(paramValues.SearchTerm)}={paramValues.SearchTerm}&" + $"{nameof(paramValues.Town)}={WebUtility.HtmlEncode(paramValues.Town)}&" + $"{nameof(paramValues.CourseType)}={paramValues.CourseType}&" + $"{nameof(paramValues.CourseHours)}={paramValues.CourseHours}&" + $"{nameof(paramValues.CourseStudyTime)}={paramValues.CourseStudyTime}&" + $"{nameof(paramValues.StartDate)}={paramValues.StartDate}&" + $"{nameof(paramValues.Distance)}={paramValues.Distance}&" + $"{nameof(paramValues.FilterA)}={paramValues.FilterA}&" + $"{nameof(paramValues.Page)}={paramValues.Page}&" + $"{nameof(paramValues.OrderByValue)}={paramValues.OrderByValue}&" + $"{nameof(paramValues.Coordinates)}={WebUtility.HtmlEncode(paramValues.Coordinates)}&" + $"{nameof(paramValues.CampaignCode)}={paramValues.CampaignCode}&" + $"{nameof(paramValues.QualificationLevels)}={paramValues.QualificationLevels}"; } } catch (Exception ex) { logService.LogError($"{nameof(this.FilterResults)} threw an exception" + ex.Message); } var viewAsString = await viewHelper.RenderViewAsync(this, "~/Views/Course/_results.cshtml", model, true).ConfigureAwait(false); return(new AjaxModel { HTML = viewAsString, Count = model.Results?.ResultProperties != null ? model.Results.ResultProperties.TotalResultCount : 0, ShowDistanceSelector = newBodyViewModel.CourseSearchFilters.DistanceSpecified, UsingAutoSuggestedLocation = newBodyViewModel.UsingAutoSuggestedLocation, AutoSuggestedTown = newBodyViewModel.SideBar.TownOrPostcode, AutoSuggestedCoordinates = newBodyViewModel.SideBar.Coordinates, DidYouMeanLocations = newBodyViewModel.SideBar.DidYouMeanLocations, }); }
public IActionResult Results(BodyViewModel model) { logService.LogInformation($"{nameof(this.Results)} has been called"); var sideBarViewModel = GetSideBarViewModel(); foreach (var item in sideBarViewModel.DistanceOptions) { if (item.Value == model.SideBar.DistanceValue) { item.Selected = true; break; } } sideBarViewModel.DistanceValue = model.SideBar.DistanceValue; sideBarViewModel.TownOrPostcode = model.SideBar.TownOrPostcode; sideBarViewModel.StartDateValue = model.SideBar.StartDateValue; sideBarViewModel.DistanceValue = model.SelectedDistanceValue; sideBarViewModel.CurrentSearchTerm = model.CurrentSearchTerm; sideBarViewModel.FiltersApplied = model.SideBar.FiltersApplied; sideBarViewModel.SelectedOrderByValue = model.SideBar.SelectedOrderByValue; sideBarViewModel.D = model.SideBar.D; if (model.SideBar.CourseType != null && model.SideBar.CourseType.SelectedIds.Any()) { model.SideBar.CourseType = CheckCheckboxState(model.SideBar.CourseType, sideBarViewModel.CourseType); sideBarViewModel.CourseType.SelectedIds = model.SideBar.CourseType.SelectedIds; } if (model.SideBar.CourseHours != null && model.SideBar.CourseHours.SelectedIds.Any()) { model.SideBar.CourseHours = CheckCheckboxState(model.SideBar.CourseHours, sideBarViewModel.CourseHours); sideBarViewModel.CourseHours.SelectedIds = model.SideBar.CourseHours.SelectedIds; } if (model.SideBar.CourseStudyTime != null && model.SideBar.CourseStudyTime.SelectedIds.Any()) { model.SideBar.CourseStudyTime = CheckCheckboxState(model.SideBar.CourseStudyTime, sideBarViewModel.CourseStudyTime); sideBarViewModel.CourseStudyTime.SelectedIds = model.SideBar.CourseStudyTime.SelectedIds; } if (model.Results?.Courses != null && model.Results.Courses.Any()) { foreach (var item in model.Results.Courses) { if (item.Description.Length > 220) { item.Description = item.Description.Substring(0, 200) + "..."; } } } var town = model.SideBar.TownOrPostcode; var distance = model.SideBar.DistanceValue; var courseType = model.SideBar.CourseType != null && model.SideBar.CourseType.SelectedIds?.Count > 0 ? JsonConvert.SerializeObject(model.SideBar.CourseType.SelectedIds) : null; var courseHours = model.SideBar.CourseHours != null && model.SideBar.CourseHours.SelectedIds?.Count > 0 ? JsonConvert.SerializeObject(model.SideBar.CourseHours.SelectedIds) : null; var courseStudyTime = model.SideBar.CourseStudyTime != null && model.SideBar.CourseStudyTime?.SelectedIds.Count > 0 ? JsonConvert.SerializeObject(model.SideBar.CourseStudyTime.SelectedIds) : null; var startDate = model.SideBar.StartDateValue; var searchTerm = sideBarViewModel.CurrentSearchTerm; var page = model.RequestPage; var filtera = model.SideBar.FiltersApplied; var orderByValue = model.SideBar.SelectedOrderByValue; if (!model.IsTest) { TempData["params"] = $"{nameof(searchTerm)}={searchTerm}&" + $"{nameof(town)}={town}&" + $"{nameof(courseType)}={courseType}&" + $"{nameof(courseHours)}={courseHours}&" + $"{nameof(courseStudyTime)}={courseStudyTime}&" + $"{nameof(startDate)}={startDate}&" + $"{nameof(distance)}={distance}&" + $"{nameof(filtera)}={filtera}&" + $"{nameof(page)}={page}&" + $"{nameof(orderByValue)}={orderByValue}"; } model.SideBar = sideBarViewModel; model.SideBar.OrderByOptions = ListFilters.GetOrderByOptions(); logService.LogInformation($"{nameof(this.Results)} generated the model and ready to pass to the view"); return(View("Body", model)); }
private static BodyViewModel GenerateModel(BodyViewModel model) { var courseTypeList = new List <CourseType>(); var courseHoursList = new List <CourseHours>(); var courseStudyTimeList = new List <Fac.AttendancePattern>(); var selectedStartDateValue = StartDate.Anytime; float selectedDistanceValue = 10; if (model.SelectedDistanceValue != null) { var resultString = Regex.Match(model.SelectedDistanceValue, @"\d+").Value; _ = float.TryParse(resultString, out selectedDistanceValue); } if (model.SideBar.CourseType != null && model.SideBar.CourseType.SelectedIds.Any()) { courseTypeList = ConvertToEnumList <CourseType>(model.SideBar.CourseType.SelectedIds); } if (model.SideBar.CourseHours != null && model.SideBar.CourseHours.SelectedIds.Any()) { courseHoursList = ConvertToEnumList <CourseHours>(model.SideBar.CourseHours.SelectedIds); } if (model.SideBar.CourseStudyTime != null && model.SideBar.CourseStudyTime.SelectedIds.Any()) { courseStudyTimeList = ConvertToEnumList <Fac.AttendancePattern>(model.SideBar.CourseStudyTime.SelectedIds); } if (model.SideBar.SelectedOrderByValue != null) { _ = Enum.TryParse(model.SideBar.SelectedOrderByValue.Replace(" ", string.Empty), true, out CourseSearchOrderBy sortedByCriteria); model.CourseSearchOrderBy = sortedByCriteria; } else { var sortedByCriteria = CourseSearchOrderBy.Relevance; model.CourseSearchOrderBy = sortedByCriteria; } var courseSearchFilters = new CourseSearchFilters { SearchTerm = model.CurrentSearchTerm, CourseType = courseTypeList, CourseHours = courseHoursList, StartDate = selectedStartDateValue, CourseStudyTime = courseStudyTimeList, Distance = selectedDistanceValue, }; model.SideBar.FiltersApplied = model.FromPaging ? model.SideBar.FiltersApplied : true; switch (model.SideBar.StartDateValue) { case "Next 3 months": courseSearchFilters.StartDateTo = DateTime.Today.AddMonths(3); courseSearchFilters.StartDateFrom = DateTime.Today; courseSearchFilters.StartDate = StartDate.SelectDateFrom; break; case "In 3 to 6 months": courseSearchFilters.StartDateFrom = DateTime.Today.AddMonths(3); courseSearchFilters.StartDateTo = DateTime.Today.AddMonths(6); courseSearchFilters.StartDate = StartDate.SelectDateFrom; break; case "More than 6 months": courseSearchFilters.StartDateFrom = DateTime.Today.AddMonths(6); courseSearchFilters.StartDate = StartDate.SelectDateFrom; break; default: courseSearchFilters.StartDate = StartDate.Anytime; break; } if (!string.IsNullOrEmpty(model.SideBar.TownOrPostcode)) { if (model.SideBar.TownOrPostcode.IsPostcode()) { courseSearchFilters.PostCode = NormalizePostcode(model.SideBar.TownOrPostcode); courseSearchFilters.Distance = selectedDistanceValue; courseSearchFilters.DistanceSpecified = true; } else { courseSearchFilters.Town = "\u0022" + model.SideBar.TownOrPostcode + "\u0022"; } } // Enter filters criteria here model.RequestPage = (model.RequestPage > 1) ? model.RequestPage : 1; model.CourseSearchFilters = courseSearchFilters; return(model); }