/// <summary>
        /// Maps the Umbraco content to the view model.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="latestService">The latest service.</param>
        /// <param name="socialMediaService">The social media service.</param>
        /// <param name="eastSussex1SpaceService">The East Sussex One Space service.</param>
        /// <param name="webChatSettingsService">The web chat settings service.</param>
        /// <param name="relatedLinksService">The related links service.</param>
        /// <param name="contentExperimentSettingsService">The content experiment settings service.</param>
        /// <param name="escisService">The escis service.</param>
        /// <param name="mediaUrlTransformer">The media URL transformer.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// content
        /// or
        /// latestService
        /// or
        /// socialMediaService
        /// or
        /// eastSussex1SpaceService
        /// or
        /// webChatSettingsService
        /// or
        /// relatedLinksService
        /// or
        /// contentExperimentSettingsService
        /// </exception>
        /// <exception cref="ArgumentNullException">content
        /// or
        /// latestService
        /// or
        /// socialMediaService
        /// or
        /// eastSussex1SpaceService
        /// or
        /// webChatSettingsService
        /// or
        /// relatedLinksService</exception>
        /// <remarks>
        /// Method is virtual so that document types which inherit from the 'Location' type can also inherit and extend the controller
        /// </remarks>
        protected virtual LocationViewModel MapUmbracoContentToViewModel(IPublishedContent content, ILatestService latestService, ISocialMediaService socialMediaService, IEastSussex1SpaceService eastSussex1SpaceService, IWebChatSettingsService webChatSettingsService, IRelatedLinksService relatedLinksService, IContentExperimentSettingsService contentExperimentSettingsService, IEscisService escisService, IMediaUrlTransformer mediaUrlTransformer)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }
            if (latestService == null)
            {
                throw new ArgumentNullException("latestService");
            }
            if (socialMediaService == null)
            {
                throw new ArgumentNullException("socialMediaService");
            }
            if (eastSussex1SpaceService == null)
            {
                throw new ArgumentNullException("eastSussex1SpaceService");
            }
            if (webChatSettingsService == null)
            {
                throw new ArgumentNullException("webChatSettingsService");
            }
            if (relatedLinksService == null)
            {
                throw new ArgumentNullException("relatedLinksService");
            }
            if (contentExperimentSettingsService == null)
            {
                throw new ArgumentNullException("contentExperimentSettingsService");
            }

            var model = new LocationViewModel
            {
                Content             = new HtmlString(mediaUrlTransformer.ParseAndTransformMediaUrlsInHtml(content.GetPropertyValue <string>("content_Content"))),
                OpeningHoursDetails = new HtmlString(mediaUrlTransformer.ParseAndTransformMediaUrlsInHtml(content.GetPropertyValue <string>("openingHoursDetails_Content"))),
                Tab1Title           = content.GetPropertyValue <string>("tab1title_Content"),
                Tab1Content         = new HtmlString(mediaUrlTransformer.ParseAndTransformMediaUrlsInHtml(content.GetPropertyValue <string>("tab1content_Content"))),
                Tab2Title           = content.GetPropertyValue <string>("tab2title_Content"),
                Tab2Content         = new HtmlString(mediaUrlTransformer.ParseAndTransformMediaUrlsInHtml(content.GetPropertyValue <string>("tab2content_Content"))),
                Tab3Title           = content.GetPropertyValue <string>("tab3title_Content"),
                Tab3Content         = new HtmlString(mediaUrlTransformer.ParseAndTransformMediaUrlsInHtml(content.GetPropertyValue <string>("tab3content_Content"))),
                Location            = content.GetPropertyValue <AddressInfo>("location_Content"),
                Email1Label         = content.GetPropertyValue <string>("email1label_Content"),
                Email2Label         = content.GetPropertyValue <string>("email2label_Content"),
                Email1      = content.GetPropertyValue <string>("email1_Content"),
                Email2      = content.GetPropertyValue <string>("email2_Content"),
                Phone1Label = content.GetPropertyValue <string>("phone1label_Content"),
                Phone2Label = content.GetPropertyValue <string>("phone2label_Content"),
                Phone1      = content.GetPropertyValue <string>("phone1_Content"),
                Phone2      = content.GetPropertyValue <string>("phone2_Content"),
                Fax1Label   = content.GetPropertyValue <string>("fax1label_Content"),
                Fax2Label   = content.GetPropertyValue <string>("fax2label_Content"),
                Fax1        = content.GetPropertyValue <string>("fax1_Content"),
                Fax2        = content.GetPropertyValue <string>("fax2_Content")
            };

            var relatedLinksGroups = new RelatedLinksModelBuilder().OrganiseAsHeadingsAndSections(relatedLinksService.BuildRelatedLinksViewModelFromUmbracoContent(content, "relatedLinks_Content"));

            foreach (var linkGroup in relatedLinksGroups)
            {
                model.RelatedLinksGroups.Add(linkGroup);
            }

            // Opening times
            model.OpeningHours = DeserialiseOpeningHours(content);
            WorkOutRelativeOpeningTimes(model);
            WorkOutNextOpenRelativeTime(model);

            // Photo
            var imageData = content.GetPropertyValue <IPublishedContent>("photo_Content");

            if (imageData != null)
            {
                model.Photo = new Image()
                {
                    AlternativeText = imageData.Name,
                    ImageUrl        = new Uri(imageData.Url, UriKind.Relative),
                    Width           = imageData.GetPropertyValue <int>("umbracoWidth"),
                    Height          = imageData.GetPropertyValue <int>("umbracoHeight")
                };
                model.Metadata.PageImageUrl = new Uri(Request.Url, model.Photo.ImageUrl).ToString();
            }

            // Add common properties to the model
            var modelBuilder = new BaseViewModelBuilder();

            modelBuilder.PopulateBaseViewModel(model, content, contentExperimentSettingsService, UmbracoContext.Current.InPreviewMode);
            modelBuilder.PopulateBaseViewModelWithInheritedContent(model, latestService, socialMediaService, eastSussex1SpaceService, webChatSettingsService, escisService);

            return(model);
        }
        /// <summary>
        /// The default action to render the front-end view
        /// </summary>
        /// <param name="model"/>
        /// <returns/>
        public new async Task <ActionResult> Index(RenderModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (ExamineManager.Instance.SearchProviderCollection["RightsOfWayModificationsSearcher"] == null)
            {
                throw new ConfigurationErrorsException("The RightsOfWayModificationsSearcher is not configured in Examine config");
            }

            var paging = new PagingController()
            {
                ResultsTextSingular = "application",
                ResultsTextPlural   = "applications",
                PageSize            = 30
            };

            var query = HttpUtility.ParseQueryString(Request.Url.Query);
            var sort  = RightsOfWayModificationsSortOrder.DateReceivedDescending;
            RightsOfWayModificationsSortOrder parsedSort;

            if (Enum.TryParse(query["sort"], true, out parsedSort))
            {
                sort = parsedSort;
            }

            var viewModel = new RightsOfWayModificationsViewModelFromExamine(
                model.Content.Id,
                Request.Url,
                ExamineManager.Instance.SearchProviderCollection["RightsOfWayModificationsSearcher"],
                Request.QueryString["q"],
                new ISearchFilter[] { new SearchTermSanitiser() },
                query["completed"] == "1",
                paging.CurrentPage,
                paging.PageSize,
                sort
                ).BuildModel();

            viewModel.Paging = paging;
            viewModel.Paging.TotalResults = viewModel.TotalModificationOrderApplications;
            viewModel.SortOrder           = sort;
            viewModel.LeadingText         = new HtmlString(model.Content.GetPropertyValue <string>("leadingText"));

            // Add common properties to the model
            var expiryDate   = new ExpiryDateFromExamine(model.Content.Id, ExamineManager.Instance.SearchProviderCollection["ExternalSearcher"], new ExpiryDateMemoryCache(TimeSpan.FromHours(1)));
            var modelBuilder = new BaseViewModelBuilder(new EastSussexGovUKTemplateRequest(Request, webChatSettingsService: new UmbracoWebChatSettingsService(model.Content, new UrlListReader())));
            await modelBuilder.PopulateBaseViewModel(viewModel, model.Content, new ContentExperimentSettingsService(),
                                                     expiryDate.ExpiryDate,
                                                     UmbracoContext.Current.InPreviewMode);

            modelBuilder.PopulateBaseViewModelWithInheritedContent(viewModel,
                                                                   new UmbracoLatestService(model.Content),
                                                                   new UmbracoSocialMediaService(model.Content),
                                                                   null, null);

            // Look for an RSS feed and CSV download
            var rss = model.Content.Children.Where <IPublishedContent>(child => child.DocumentTypeAlias == "RightsOfWayModificationsRss").FirstOrDefault();

            if (rss != null)
            {
                viewModel.RssUrl = new Uri(rss.Url, UriKind.Relative);
            }

            var csv = model.Content.Children.Where <IPublishedContent>(child => child.DocumentTypeAlias == "RightsOfWayModificationsCsv").FirstOrDefault();

            if (csv != null)
            {
                viewModel.CsvUrl = new Uri(csv.Url, UriKind.Relative);
            }

            new HttpCachingService().SetHttpCacheHeadersFromUmbracoContent(model.Content, UmbracoContext.Current.InPreviewMode, Response.Cache, new IExpiryDateSource[] { expiryDate, new ExpiryDateFromPropertyValue(model.Content, "latestUnpublishDate_Latest") });

            return(CurrentTemplate(viewModel));
        }
Esempio n. 3
0
        /// <summary>
        /// The default action to render the front-end view
        /// </summary>
        /// <param name="model"/>
        /// <returns/>
        public async new Task <ActionResult> Index(RenderModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var viewModel = new JobAdvertViewModelFromUmbraco(model.Content).BuildModel();

            // Add common properties to the model
            var expiryDate   = new ExpiryDateFromExamine(model.Content.Id, ExamineManager.Instance.SearchProviderCollection["ExternalSearcher"], new ExpiryDateMemoryCache(TimeSpan.FromHours(1)));
            var modelBuilder = new BaseViewModelBuilder(new EastSussexGovUKTemplateRequest(Request, webChatSettingsService: new UmbracoWebChatSettingsService(model.Content, new UrlListReader())));
            await modelBuilder.PopulateBaseViewModel(viewModel, model.Content, new ContentExperimentSettingsService(),
                                                     expiryDate.ExpiryDate,
                                                     UmbracoContext.Current.InPreviewMode);

            modelBuilder.PopulateBaseViewModelWithInheritedContent(viewModel,
                                                                   new UmbracoLatestService(model.Content),
                                                                   new UmbracoSocialMediaService(model.Content),
                                                                   null, null);

            // Redirect non-preferred URL - these are sent out in job alerts until May 2018, and linked from the TalentLink back office
            if (!String.IsNullOrEmpty(Request.QueryString["nPostingTargetID"]))
            {
                var jobsProvider = new JobsDataFromApi(new Uri(ConfigurationManager.AppSettings["JobsApiBaseUrl"]), viewModel.JobsSet, new Uri(model.Content.UrlAbsolute()), new HttpClientProvider(), new MemoryJobCacheStrategy(MemoryCache.Default, Request.QueryString["ForceCacheRefresh"] == "1"));
                viewModel.Job = await jobsProvider.ReadJob(Request.QueryString["nPostingTargetID"]);

                if (viewModel.Job.Id > 0)
                {
                    return(new RedirectResult(viewModel.Job.Url.ToString(), true));
                }
            }
            else
            {
                // Show page for preferred URL
                var jobUrlSegment = Regex.Match(Request.Url.AbsolutePath, "/([0-9]+)/");
                if (jobUrlSegment.Success)
                {
                    var jobsProvider = new JobsDataFromApi(new Uri(ConfigurationManager.AppSettings["JobsApiBaseUrl"]), viewModel.JobsSet, new Uri(model.Content.UrlAbsolute()), new HttpClientProvider(), new MemoryJobCacheStrategy(MemoryCache.Default, Request.QueryString["ForceCacheRefresh"] == "1"));
                    viewModel.Job = await jobsProvider.ReadJob(jobUrlSegment.Groups[1].Value);

                    if (viewModel.Job.Id == 0 || viewModel.Job.ClosingDate < DateTime.Today)
                    {
                        // The job URL looks valid but the job isn't in the index, so it's probably closed.
                        // Find some similar jobs to suggest the user may want to apply for instead.
                        await FindSimilarJobs(jobsProvider, viewModel);
                    }
                }
                else
                {
                    // The page was accessed by its default Umbraco URL with no parameters. Returning HttpNotFoundResult() ends up with a generic browser 404,
                    // so to get our custom one we need to look it up and transfer control to it.

                    // However, we need to check for "alttemplate" because a link from a TalentLink job alert or the TalentLink back office to an expired job
                    // is a link to the default Umbraco URL with just a querystring that doesn't match any data. That in turn will want to load the jobs CSS for
                    // a job that matches nothing, and that request ends up here. We want it to continue and return the JobsCss view, not our 404 page.
                    if (String.IsNullOrEmpty(Request.QueryString["alttemplate"]))
                    {
                        var notFoundUrl = new HttpStatusFromConfiguration().GetCustomUrlForStatusCode(404);
                        if (notFoundUrl != null && Server != null)
                        {
                            Server.TransferRequest(notFoundUrl + "?404;" + HttpUtility.UrlEncode(Request.Url.ToString()));
                        }
                    }
                }
            }

            // The page should expire when the job closes
            var expirySeconds = 86400; // one day

            if (viewModel.Job != null && viewModel.Job.ClosingDate != null)
            {
                var secondsToClosingDate = (int)(viewModel.Job.ClosingDate.Value.AddDays(1).Date.ToUkDateTime() - DateTime.Now.ToUkDateTime()).TotalSeconds;
                if (secondsToClosingDate >= 0)
                {
                    expirySeconds = secondsToClosingDate;
                }
            }
            new HttpCachingService().SetHttpCacheHeadersFromUmbracoContent(model.Content, UmbracoContext.Current.InPreviewMode, Response.Cache, new IExpiryDateSource[] { expiryDate, new ExpiryDateFromPropertyValue(model.Content, "latestUnpublishDate_Latest") }, expirySeconds);

            return(CurrentTemplate(viewModel));
        }