private async Task SetUmbracoRouteValues(ActionExecutingContext context, IPublishedContent content)
        {
            if (content != null)
            {
                IUmbracoContextAccessor umbracoContextAccessor = context.HttpContext.RequestServices.GetRequiredService <IUmbracoContextAccessor>();
                IPublishedRouter        router = context.HttpContext.RequestServices.GetRequiredService <IPublishedRouter>();

                var umbracoContext = umbracoContextAccessor.GetRequiredUmbracoContext();

                IPublishedRequestBuilder requestBuilder = await router.CreateRequestAsync(umbracoContext.CleanedUmbracoUrl);

                requestBuilder.SetPublishedContent(content);
                IPublishedRequest publishedRequest = requestBuilder.Build();

                var routeValues = new UmbracoRouteValues(
                    publishedRequest,
                    (ControllerActionDescriptor)context.ActionDescriptor);

                context.HttpContext.Features.Set(routeValues);
            }
            else
            {
                // if there is no content then it should be a not found
                context.Result = new NotFoundResult();
            }
        }
Esempio n. 2
0
    private async Task SetUmbracoRouteValues(ActionExecutingContext context, IPublishedContent?content)
    {
        if (content != null)
        {
            UriUtility uriUtility = context.HttpContext.RequestServices.GetRequiredService <UriUtility>();

            var originalRequestUrl = new Uri(context.HttpContext.Request.GetEncodedUrl());
            Uri cleanedUrl         = uriUtility.UriToUmbraco(originalRequestUrl);

            IPublishedRouter router = context.HttpContext.RequestServices.GetRequiredService <IPublishedRouter>();

            IPublishedRequestBuilder requestBuilder = await router.CreateRequestAsync(cleanedUrl);

            requestBuilder.SetPublishedContent(content);
            IPublishedRequest publishedRequest = requestBuilder.Build();

            var routeValues = new UmbracoRouteValues(
                publishedRequest,
                (ControllerActionDescriptor)context.ActionDescriptor);

            context.HttpContext.Features.Set(routeValues);
        }
        else
        {
            // if there is no content then it should be a not found
            context.Result = new NotFoundResult();
        }
    }
    private static async Task <Attempt <UrlInfo?> > DetectCollisionAsync(
        ILogger logger,
        IContent content,
        string url,
        string culture,
        IUmbracoContext umbracoContext,
        IPublishedRouter publishedRouter,
        ILocalizedTextService textService,
        IVariationContextAccessor variationContextAccessor,
        UriUtility uriUtility)
    {
        // test for collisions on the 'main' URL
        var uri = new Uri(url.TrimEnd(Constants.CharArrays.ForwardSlash), UriKind.RelativeOrAbsolute);

        if (uri.IsAbsoluteUri == false)
        {
            uri = uri.MakeAbsolute(umbracoContext.CleanedUmbracoUrl);
        }

        uri = uriUtility.UriToUmbraco(uri);
        IPublishedRequestBuilder builder = await publishedRouter.CreateRequestAsync(uri);

        IPublishedRequest pcr =
            await publishedRouter.RouteRequestAsync(builder, new RouteRequestOptions(RouteDirection.Outbound));

        if (!pcr.HasPublishedContent())
        {
            const string logMsg = nameof(DetectCollisionAsync) +
                                  " did not resolve a content item for original url: {Url}, translated to {TranslatedUrl} and culture: {Culture}";
            logger.LogDebug(logMsg, url, uri, culture);

            var urlInfo = UrlInfo.Message(textService.Localize("content", "routeErrorCannotRoute"), culture);
            return(Attempt.Succeed(urlInfo));
        }

        if (pcr.IgnorePublishedContentCollisions)
        {
            return(Attempt <UrlInfo?> .Fail());
        }

        if (pcr.PublishedContent?.Id != content.Id)
        {
            IPublishedContent?o = pcr.PublishedContent;
            var l = new List <string>();
            while (o != null)
            {
                l.Add(o.Name(variationContextAccessor) !);
                o = o.Parent;
            }

            l.Reverse();
            var s = "/" + string.Join("/", l) + " (id=" + pcr.PublishedContent?.Id + ")";

            var urlInfo = UrlInfo.Message(textService.Localize("content", "routeError", new[] { s }), culture);
            return(Attempt.Succeed(urlInfo));
        }

        // no collision
        return(Attempt <UrlInfo?> .Fail());
    }
        public async Task RenderAsync(int pageId, int?altTemplateId, StringWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext();

            // instantiate a request and process
            // important to use CleanedUmbracoUrl - lowercase path-only version of the current URL, though this isn't going to matter
            // terribly much for this implementation since we are just creating a doc content request to modify it's properties manually.
            var requestBuilder = await _publishedRouter.CreateRequestAsync(umbracoContext.CleanedUmbracoUrl);

            var doc = umbracoContext.Content?.GetById(pageId);

            if (doc == null)
            {
                writer.Write("<!-- Could not render template for Id {0}, the document was not found -->", pageId);
                return;
            }

            // in some cases the UmbracoContext will not have a PublishedRequest assigned to it if we are not in the
            // execution of a front-end rendered page. In this case set the culture to the default.
            // set the culture to the same as is currently rendering
            if (umbracoContext.PublishedRequest == null)
            {
                var defaultLanguage = _languageService.GetAllLanguages().FirstOrDefault();

                requestBuilder.SetCulture(defaultLanguage == null
                    ? CultureInfo.CurrentUICulture.Name
                    : defaultLanguage.IsoCode);
            }
            else
            {
                requestBuilder.SetCulture(umbracoContext.PublishedRequest.Culture);
            }

            // set the doc that was found by id
            requestBuilder.SetPublishedContent(doc);

            // set the template, either based on the AltTemplate found or the standard template of the doc
            var templateId = _webRoutingSettings.DisableAlternativeTemplates || !altTemplateId.HasValue
                ? doc.TemplateId
                : altTemplateId.Value;

            if (templateId.HasValue)
            {
                requestBuilder.SetTemplate(_fileService.GetTemplate(templateId.Value));
            }

            // if there is not template then exit
            if (requestBuilder.HasTemplate() == false)
            {
                if (altTemplateId.HasValue == false)
                {
                    writer.Write("<!-- Could not render template for Id {0}, the document's template was not found with id {0}-->", doc.TemplateId);
                }
                else
                {
                    writer.Write("<!-- Could not render template for Id {0}, the altTemplate was not found with id {0}-->", altTemplateId);
                }

                return;
            }

            // First, save all of the items locally that we know are used in the chain of execution, we'll need to restore these
            // after this page has rendered.
            SaveExistingItems(out IPublishedRequest? oldPublishedRequest);

            IPublishedRequest contentRequest = requestBuilder.Build();

            try
            {
                // set the new items on context objects for this templates execution
                SetNewItemsOnContextObjects(contentRequest);

                // Render the template
                ExecuteTemplateRendering(writer, contentRequest);
            }
            finally
            {
                // restore items on context objects to continuing rendering the parent template
                RestoreItems(oldPublishedRequest);
            }
        }
Esempio n. 5
0
        public PartialViewResult GetPreviewMarkup([FromForm] PreviewData data, [FromQuery] int pageId)
        {
            var page = default(IPublishedContent);

            // If the page is new, then the ID will be zero
            if (pageId > 0)
            {
                // Get page container node
                page = _contentQuery.Content(pageId);
                if (page == null)
                {
                    // If unpublished, then fake PublishedContent
                    page = new UnpublishedContent(pageId, _contentService, _contentTypeService, _dataTypeService, _propertyEditorCollection, _publishedContentTypeFactory);
                }
            }


            if (_umbracoContext.UmbracoContext.PublishedRequest == null)
            {
                var request = _router.CreateRequestAsync(new Uri(Request.GetDisplayUrl())).Result;
                request.SetPublishedContent(page);
                _umbracoContext.UmbracoContext.PublishedRequest = request.Build();
            }

            // Set the culture for the preview
            if (page != null && page.Cultures != null)
            {
                var currentCulture = string.IsNullOrWhiteSpace(data.Culture) ? page.GetCultureFromDomains() : data.Culture;
                if (currentCulture != null && page.Cultures.ContainsKey(currentCulture))
                {
                    var culture = new CultureInfo(page.Cultures[currentCulture].Culture);
                    // _umbracoContext.UmbracoContext.PublishedRequest.Culture = culture; // TODO: Not sure if this is needed?
                    System.Threading.Thread.CurrentThread.CurrentCulture   = culture;
                    System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
                    _umbracoContext.UmbracoContext.VariationContextAccessor.VariationContext = new VariationContext(culture.Name);
                }
            }

            // Get content node object
            var content = _dtgeHelper.ConvertValueToContent(data.Id, data.ContentTypeAlias, data.Value);

            // Construct preview model
            var model = new PreviewModel
            {
                Page            = page,
                Item            = content,
                EditorAlias     = data.EditorAlias,
                PreviewViewPath = data.PreviewViewPath,
                ViewPath        = data.ViewPath
            };


            // Render view

            var partialName = "~/App_Plugins/DocTypeGridEditor/Render/DocTypeGridEditorPreviewer.cshtml";

            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());

            viewData.Model = model;
            return(new PartialViewResult()
            {
                ViewName = partialName,
                ViewData = viewData
            });
        }