private void ProcessAsset(TagHelperOutput output)
        {
            if (string.IsNullOrEmpty(Src))
            {
                return;
            }

            var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext);

            if (!urlHelper.IsLocalUrl(Src))
            {
                output.Attributes.SetAttribute(SRC_ATTRIBUTE_NAME, Src);
                return;
            }

            //remove the application path from the generated URL if exists
            var pathBase = ViewContext.HttpContext?.Request?.PathBase ?? PathString.Empty;

            PathString.FromUriComponent(Src).StartsWithSegments(pathBase, out var sourceFile);

            if (!_assetPipeline.TryGetAssetFromRoute(sourceFile, out var asset))
            {
                asset = _assetPipeline.AddJavaScriptBundle(sourceFile, sourceFile);
            }

            output.Attributes.SetAttribute(SRC_ATTRIBUTE_NAME, $"{Src}?v={asset.GenerateCacheKey(ViewContext.HttpContext)}");
        }
Beispiel #2
0
        static public Link BeginLink(
            this IHtmlHelper html,
            string controllerName,
            string actionName,
            object routeValues,
            object htmlAttributes)
        {
            IUrlHelperFactory urlHelperFactory = new UrlHelperFactory();

            string action;

            if (actionName == null && controllerName == null && routeValues == null)
            {
                var request = html.ViewContext.HttpContext.Request;
                action = request.PathBase + request.Path + request.QueryString;
            }
            else
            {
                var urlHelper = urlHelperFactory.GetUrlHelper(html.ViewContext);
                action = urlHelper.Action(action: actionName, controller: controllerName, values: routeValues);
            }

            var writer = html.ViewContext.Writer;

            TagBuilder linkCore = GenerateLinkCore(action, htmlAttributes);

            if (linkCore != null)
            {
                linkCore.TagRenderMode = TagRenderMode.StartTag;
                writer.WriteLine(linkCore);
            }

            return(new Link(writer));
        }
Beispiel #3
0
        /// <summary>
        /// Tries to resolve the given <paramref name="url"/> value relative to the application's 'webroot' setting.
        /// </summary>
        /// <param name="url">The URL to resolve.</param>
        /// <param name="resolvedUrl">
        /// Absolute URL beginning with the application's virtual root. <c>null</c> if <paramref name="url"/> could
        /// not be resolved.
        /// </param>
        /// <returns><c>true</c> if the <paramref name="url"/> could be resolved; <c>false</c> otherwise.</returns>
        protected bool TryResolveUrl(string url, out IHtmlContent resolvedUrl)
        {
            resolvedUrl = null;
            var start = FindRelativeStart(url);

            if (start == -1)
            {
                return(false);
            }

            var trimmedUrl = CreateTrimmedString(url, start);

            var urlHelper              = UrlHelperFactory.GetUrlHelper(ViewContext);
            var appRelativeUrl         = urlHelper.Content(trimmedUrl);
            var postTildeSlashUrlValue = trimmedUrl.Substring(2);

            if (!appRelativeUrl.EndsWith(postTildeSlashUrlValue, StringComparison.Ordinal))
            {
                throw new InvalidOperationException(
                          Resources.FormatCouldNotResolveApplicationRelativeUrl_TagHelper(
                              url,
                              nameof(IUrlHelper),
                              nameof(IUrlHelper.Content),
                              "removeTagHelper",
                              typeof(UrlResolutionTagHelper).FullName,
                              typeof(UrlResolutionTagHelper).GetTypeInfo().Assembly.GetName().Name));
            }

            resolvedUrl = new EncodeFirstSegmentContent(
                appRelativeUrl,
                appRelativeUrl.Length - postTildeSlashUrlValue.Length,
                postTildeSlashUrlValue);

            return(true);
        }
Beispiel #4
0
        public IUrlHelper GetUrlHelper(ActionContext context)
        {
            var originalUrlHelperFactory = new UrlHelperFactory();
            var originalUrlHelper        = originalUrlHelperFactory.GetUrlHelper(context);

            return(new CustomUrlHelper(context, originalUrlHelper, _urlRoutesOptions));
        }
        public async Task Enrich(ResultExecutingContext response)
        {
            var urlHelper = new UrlHelperFactory().GetUrlHelper(response);

            if (response.Result is OkObjectResult okObjectResult)
            {
                if (okObjectResult.Value is T model)
                {
                    await EnrichModel(model, urlHelper);
                }
                else if (okObjectResult.Value is List <T> collection)
                {
                    ConcurrentBag <T> bag = new ConcurrentBag <T>(collection);
                    Parallel.ForEach(bag, (element) =>
                    {
                        EnrichModel(element, urlHelper);
                    });
                }
                else if (okObjectResult.Value is PagedSearchDTO <T> pageSearch)
                {
                    Parallel.ForEach(pageSearch.List.ToList(), (element) =>
                    {
                        EnrichModel(element, urlHelper);
                    });
                }
            }
            await Task.FromResult <object>(null);
        }
        public void ReturnAUrlHelper_WhenCalledWithANonNullRequestContext()
        {
            var factory   = new UrlHelperFactory();
            var urlHelper = factory.Create(new RequestContext());

            Assert.IsInstanceOf <UrlHelper>(urlHelper);
        }
        /// <summary>
        /// Tries to resolve the given <paramref name="url"/> value relative to the application's 'webroot' setting.
        /// </summary>
        /// <param name="url">The URL to resolve.</param>
        /// <param name="resolvedUrl">
        /// Absolute URL beginning with the application's virtual root. <c>null</c> if <paramref name="url"/> could
        /// not be resolved.
        /// </param>
        /// <returns><c>true</c> if the <paramref name="url"/> could be resolved; <c>false</c> otherwise.</returns>
        protected bool TryResolveUrl(string url, out IHtmlContent resolvedUrl)
        {
            resolvedUrl = null;
            var start = FindRelativeStart(url);

            if (start == -1)
            {
                return(false);
            }

            url = url.Remove(start, 2).Insert(start, $"~/themes/{Theme.Key}/");
            var trimmedUrl = CreateTrimmedString(url, start);



            var urlHelper              = UrlHelperFactory.GetUrlHelper(ViewContext);
            var appRelativeUrl         = urlHelper.Content(trimmedUrl);
            var postTildeSlashUrlValue = trimmedUrl.Substring(2);

            if (!appRelativeUrl.EndsWith(postTildeSlashUrlValue, StringComparison.Ordinal))
            {
                throw new InvalidOperationException("");
            }

            resolvedUrl = new EncodeFirstSegmentContent(
                appRelativeUrl,
                appRelativeUrl.Length - postTildeSlashUrlValue.Length,
                postTildeSlashUrlValue);

            return(true);
        }
Beispiel #8
0
        public void Activate_ActivatesAndContextualizesPropertiesOnViews()
        {
            // Arrange
            var modelMetadataProvider   = new EmptyModelMetadataProvider();
            var modelExpressionProvider = new ModelExpressionProvider(modelMetadataProvider, new ExpressionTextCache());
            var urlHelperFactory        = new UrlHelperFactory();
            var jsonHelper = new JsonHelper(
                new JsonOutputFormatter(new JsonSerializerSettings(), ArrayPool <char> .Shared),
                ArrayPool <char> .Shared);
            var htmlEncoder      = new HtmlTestEncoder();
            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
            var activator        = new RazorPageActivator(
                new EmptyModelMetadataProvider(),
                urlHelperFactory,
                jsonHelper,
                diagnosticSource,
                htmlEncoder,
                modelExpressionProvider);

            var instance = new TestRazorPage();

            var myService = new MyService();
            var helper    = Mock.Of <IHtmlHelper <object> >();

            var serviceProvider = new ServiceCollection()
                                  .AddSingleton(myService)
                                  .AddSingleton(helper)
                                  .AddSingleton(new ExpressionTextCache())
                                  .BuildServiceProvider();
            var httpContext = new DefaultHttpContext
            {
                RequestServices = serviceProvider
            };

            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
            var viewContext   = new ViewContext(
                actionContext,
                Mock.Of <IView>(),
                new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()),
                Mock.Of <ITempDataDictionary>(),
                TextWriter.Null,
                new HtmlHelperOptions());

            var urlHelper = urlHelperFactory.GetUrlHelper(viewContext);

            // Act
            activator.Activate(instance, viewContext);

            // Assert
            Assert.Same(helper, instance.Html);
            Assert.Same(myService, instance.MyService);
            Assert.Same(viewContext, myService.ViewContext);
            Assert.Same(diagnosticSource, instance.DiagnosticSource);
            Assert.Same(htmlEncoder, instance.HtmlEncoder);
            Assert.Same(jsonHelper, instance.Json);
            Assert.Same(urlHelper, instance.Url);
            Assert.Null(instance.MyService2);
        }
Beispiel #9
0
        public static void setPagesPath(ActionContext ctx, IEnumerable <ControlPage> pages)
        {
            var urlHelper = new UrlHelperFactory().GetUrlHelper(ctx);

            foreach (var page in pages)
            {
                setPagePath(urlHelper, page);
            }
        }
 public RazorPageActivatorTest()
 {
     DiagnosticListener      = new DiagnosticListener("Microsoft.AspNetCore");
     HtmlEncoder             = new HtmlTestEncoder();
     JsonHelper              = Mock.Of <IJsonHelper>();
     MetadataProvider        = new EmptyModelMetadataProvider();
     ModelExpressionProvider = new ModelExpressionProvider(MetadataProvider);
     UrlHelperFactory        = new UrlHelperFactory();
 }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext);

            output.Attributes.SetAttribute("href", urlHelper.Action(new UrlActionContext
            {
                Controller = Controller,
                Action     = Action
            }));

            output.PreContent.SetContent($"{nameof(TestTagHelper)} content.");
        }
 public virtual void Contextualize(ViewContext viewContext)
 {
     ViewContext = viewContext;
     UrlHelper   = UrlHelperFactory.GetUrlHelper(viewContext);
     parents     = (Stack <IWritableItem>)viewContext.HttpContext.Items[ParentStackContextKey];
     if (parents == null)
     {
         parents = new Stack <IWritableItem>(5);
         parents.Push(null);
         viewContext.HttpContext.Items[ParentStackContextKey] = parents;
     }
 }
 public override void Process(TagHelperContext context, TagHelperOutput output)
 {
     if (AngHref != null)
     {
         string href = "{{" + AngHref.GetName() + "}}";
         if (AngHrefRoute != null)
         {
             href = UrlHelperFactory.GetUrlHelper(ViewContext).Content(AngHrefRoute) + href;
         }
         href = $"{AngHrefPrefix}{href}{AngHrefSuffix}";
         output.Attributes.SetAttribute("ng-href", href);
     }
 }
        private string GetFormAction()
        {
            var routeLink  = Route != null;
            var actionLink = Controller != null || Action != null;
            var pageLink   = Page != null || PageHandler != null;

            // make local copy
            var routeValues = new RouteValueDictionary(RouteValues);

            // Unconditionally replace any value from asp-route-area.
            if (Area != null)
            {
                routeValues["area"] = Area;
            }


            var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext);

            if (pageLink)
            {
                return(urlHelper.Page(
                           Page,
                           PageHandler,
                           routeValues,
                           protocol: null,
                           host: null,
                           fragment: Fragment));
            }


            if (routeLink)
            {
                return(urlHelper.RouteUrl(
                           Route,
                           routeValues,
                           protocol: null,
                           host: null,
                           fragment: Fragment));
            }

            return(urlHelper.Action(
                       Action,
                       Controller,
                       routeValues,
                       protocol: null,
                       host: null,
                       fragment: Fragment));
        }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output);
            var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext) as FullUrlHelper;

            if (urlHelper == null)
            {
                return;
            }

            if (output.PostElement != null && !output.PostElement.IsEmptyOrWhiteSpace)
            {
                var content = output.PostElement.GetContent();
                output.PostElement.SetHtmlContent(hrefRegex.Replace(content,
                                                                    match => "src=\"" + urlHelper.Content(match.Groups[1].Value) + "\""));
            }
        }
Beispiel #16
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (Controller != null && Action != null)
            {
                var methodParameters = output.Attributes.ToDictionary(attribute => attribute.Name,
                                                                      attribute => attribute.Value);

                // We remove all attributes from the resulting HTML element because they're supposed to
                // be parameters to our final href value.
                output.Attributes.Clear();

                var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext);
                output.Attributes.SetAttribute("href", urlHelper.Action(Action, Controller, methodParameters));

                output.PreContent.SetContent("My ");
            }
        }
Beispiel #17
0
    public void GetUrlHelper_CreatesNewInstance_IfNotAlreadyPresent()
    {
        // Arrange
        var httpContext = new Mock <HttpContext>();

        httpContext.SetupGet(h => h.Features).Returns(new FeatureCollection());
        httpContext.Setup(h => h.Items).Returns(new Dictionary <object, object>());

        var actionContext    = CreateActionContext(httpContext.Object);
        var urlHelperFactory = new UrlHelperFactory();

        // Act
        var urlHelper = urlHelperFactory.GetUrlHelper(actionContext);

        // Assert
        Assert.NotNull(urlHelper);
        Assert.Same(urlHelper, actionContext.HttpContext.Items[typeof(IUrlHelper)] as IUrlHelper);
    }
Beispiel #18
0
        public void AssignThumbnailUrl(FileSystemInfo fileSystemInfo, IClientFileSystemItem clientItem)
        {
            if (clientItem.IsDirectory || !CanGenerateThumbnail(fileSystemInfo))
            {
                return;
            }

            if (!(fileSystemInfo is FileInfo fileInfo))
            {
                return;
            }

            var helper                = UrlHelperFactory.GetUrlHelper(ActionContextAccessor.ActionContext);
            var thumbnail             = GetThumbnail(fileInfo);
            var relativeThumbnailPath = Path.Combine(ThumbnailsDirectory.Name, thumbnail.Directory?.Name, thumbnail.Name);

            clientItem.CustomFields["thumbnailUrl"] = helper.Content(relativeThumbnailPath);
        }
Beispiel #19
0
        /// <summary>
        /// Tries to resolve the given <paramref name="url"/> value relative to the application's 'webroot' setting.
        /// </summary>
        /// <param name="url">The URL to resolve.</param>
        /// <param name="resolvedUrl">Absolute URL beginning with the application's virtual root. <c>null</c> if
        /// <paramref name="url"/> could not be resolved.</param>
        /// <returns><c>true</c> if the <paramref name="url"/> could be resolved; <c>false</c> otherwise.</returns>
        protected bool TryResolveUrl(string url, out string resolvedUrl)
        {
            resolvedUrl = null;
            var start = FindRelativeStart(url);

            if (start == -1)
            {
                return(false);
            }

            var trimmedUrl = CreateTrimmedString(url, start);

            var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext);

            resolvedUrl = urlHelper.Content(trimmedUrl);

            return(true);
        }
        /// <summary>
        /// Tries to resolve the given <paramref name="url"/> value relative to the application's 'webroot' setting.
        /// </summary>
        /// <param name="url">The URL to resolve.</param>
        /// <param name="resolvedUrl">Absolute URL beginning with the application's virtual root. <c>null</c> if
        /// <paramref name="url"/> could not be resolved.</param>
        /// <returns><c>true</c> if the <paramref name="url"/> could be resolved; <c>false</c> otherwise.</returns>
        protected bool TryResolveUrl(string url, out string resolvedUrl)
        {
            resolvedUrl = null;
            var start = FindRelativeStart(url);

            if (start == -1)
            {
                return(false);
            }

            url = url.Remove(start, 2).Insert(start, $"~/themes/{Theme.Key}/");
            var trimmedUrl = CreateTrimmedString(url, start);

            var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext);

            resolvedUrl = urlHelper.Content(trimmedUrl);

            return(true);
        }
        public void Can_Generate_Page_Links()
        {
            //Arrange
            var urlHelper = new Mock<IUrlHelper>();
            urlHelper.SetupSequence(x => x.Action(It.IsAny<UrlActionContext>())
            .Returns("Test/Page1")
            .Returns("Test/Page2")
            .Returns("Test/Page3");

            var urlHelperFactory = new Mock<IUrlHelperFactory>();
            UrlHelperFactory.Setup(f =>
                f.GetUrlHelper(It.IsAny<ActionContext>()))
                .Returns(urlHelper.Object);
            PageLinkTagHelper helper =
                new PageLinkTagHelper(UrlHelperFactory.Object)
                {
                    PageModel = new PagingInfo
                    {
                        CurrentPage = 2,
                        TotalItems = 28,
                        ItemsPerPage = 10
                    },
                    PageAction = "Test"
                };
            TagHelperContext ctx = new TagHelperContext(
                new TagHelperAttributeList(),
                new Dictionary<object, object>(), "");
            var content = new Mock<TagHelperContent>();
            TagHelperOutput output = new TagHelperOutput("div",
                new TagHelperAttributeList(),
                (cache, encoder) => Task.FromResult(content.Object));
            //Act
            helper.Process(ctx, output);
            // Assert
            Assert.Equal(@"<a href=""Test/Page1"">1</a>"
                        + @"<a href=""Test/Page2"">2</a>"
                        + @"<a href=""Test/Page3"">3</a>",
                        output.Content.GetContent());


        }
        /// <summary>
        /// Tries to resolve the given <paramref name="url"/> value relative to the application's 'webroot' setting.
        /// </summary>
        /// <param name="url">The URL to resolve.</param>
        /// <param name="resolvedUrl">Absolute URL beginning with the application's virtual root. <c>null</c> if
        /// <paramref name="url"/> could not be resolved.</param>
        /// <returns><c>true</c> if the <paramref name="url"/> could be resolved; <c>false</c> otherwise.</returns>
        protected bool TryResolveUrl(string url, out string resolvedUrl)
        {
            resolvedUrl = null;
            if (url == null)
            {
                return(false);
            }

            var trimmedUrl = url.Trim(ValidAttributeWhitespaceChars);

            // Before doing more work, ensure that the URL we're looking at is app-relative.
            if (trimmedUrl.Length >= 2 && trimmedUrl[0] == '~' && trimmedUrl[1] == '/')
            {
                var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext);
                resolvedUrl = urlHelper.Content(trimmedUrl);

                return(true);
            }

            return(false);
        }
Beispiel #23
0
        public async Task Format(ResultExecutingContext context)
        {
            var urlHelper = new UrlHelperFactory().GetUrlHelper(context);

            if (context.Result is OkObjectResult okObjectResult)
            {
                if (okObjectResult.Value is T model)
                {
                    await FormatModel(model, urlHelper);
                }
                else if (okObjectResult.Value is List <T> collection)
                {
                    ConcurrentBag <T> bag = new ConcurrentBag <T>(collection);
                    Parallel.ForEach(bag, (element) =>
                    {
                        FormatModel(element, urlHelper);
                    });
                }
            }
            await Task.FromResult <object>(null);
        }
        public async Task Enrich(ResultExecutingContext response) //Ela precisa ser asincrona, por ser multiplas exec simultanea
        {
            var urlHelper = new UrlHelperFactory().GetUrlHelper(response);

            if (response.Result is OkObjectResult okObjectResult)
            {
                if (okObjectResult.Value is T model)
                {
                    await EnrichModel(model, urlHelper);
                }
                else if (okObjectResult.Value is List <T> collection)
                {
                    ConcurrentBag <T> bag = new ConcurrentBag <T>(collection);
                    Parallel.ForEach(bag, (element) =>
                    {
                        EnrichModel(element, urlHelper);
                    });
                }
            }
            await Task.FromResult <object>(null);
        }
Beispiel #25
0
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var actionContext = Accessor.ActionContext;
            var urlHelper     = UrlHelperFactory.GetUrlHelper(actionContext);

            output.TagName = "ul";
            var content = await output.GetChildContentAsync();

            if (string.IsNullOrWhiteSpace(content.GetContent()) == false)
            {
                var tags = content.GetContent().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var sb   = new StringBuilder();
                foreach (var tag in tags)
                {
                    sb.AppendFormat("<li class='d-inline p-1'><a href='{0}' class='btn btn-success'>{1}</a></li>",
                                    urlHelper.Page("index", "tag", new { tag = tag }), tag);
                }

                output.Content.SetHtmlContent(sb.ToString());
            }
        }
        public async Task Enrich(ResultExecutingContext response)
        {
            var urlHelper = new UrlHelperFactory().GetUrlHelper(response);

            if (response.Result is OkObjectResult okObjectResult)
            {
                if (okObjectResult.Value is T model)
                {
                    /*await*/ EnrichModel(model, urlHelper);    //await removido gerando bug
                }
                else if (okObjectResult.Value is List <T> collection)
                {
                    ConcurrentBag <T> bag = new ConcurrentBag <T>(collection);
                    Parallel.ForEach(bag, (element) =>
                    {
                        EnrichModel(element, urlHelper);
                    });
                }
                await Task.FromResult <object>(null);
            }
        }
        /// <summary>
        /// Tries to resolve the given <paramref name="url"/> value relative to the application's 'webroot' setting.
        /// </summary>
        /// <param name="url">The URL to resolve.</param>
        /// <param name="resolvedUrl">
        /// Absolute URL beginning with the application's virtual root. <c>null</c> if <paramref name="url"/> could
        /// not be resolved.
        /// </param>
        /// <returns><c>true</c> if the <paramref name="url"/> could be resolved; <c>false</c> otherwise.</returns>
        protected bool TryResolveUrl(string url, out IHtmlContent resolvedUrl)
        {
            resolvedUrl = null;
            if (url == null)
            {
                return(false);
            }

            var trimmedUrl = url.Trim(ValidAttributeWhitespaceChars);

            // Before doing more work, ensure that the URL we're looking at is app-relative.
            if (trimmedUrl.Length >= 2 && trimmedUrl[0] == '~' && trimmedUrl[1] == '/')
            {
                var urlHelper              = UrlHelperFactory.GetUrlHelper(ViewContext);
                var appRelativeUrl         = urlHelper.Content(trimmedUrl);
                var postTildeSlashUrlValue = trimmedUrl.Substring(2);

                if (!appRelativeUrl.EndsWith(postTildeSlashUrlValue, StringComparison.Ordinal))
                {
                    throw new InvalidOperationException(
                              Resources.FormatCouldNotResolveApplicationRelativeUrl_TagHelper(
                                  url,
                                  nameof(IUrlHelper),
                                  nameof(IUrlHelper.Content),
                                  "removeTagHelper",
                                  typeof(UrlResolutionTagHelper).FullName,
                                  typeof(UrlResolutionTagHelper).GetTypeInfo().Assembly.GetName().Name));
                }

                resolvedUrl = new EncodeFirstSegmentContent(
                    appRelativeUrl,
                    appRelativeUrl.Length - postTildeSlashUrlValue.Length,
                    postTildeSlashUrlValue);

                return(true);
            }

            return(false);
        }
Beispiel #28
0
    public void GetUrlHelper_ReturnsSameInstance_IfAlreadyPresent()
    {
        // Arrange
        var expectedUrlHelper = CreateUrlHelper();
        var httpContext       = new Mock <HttpContext>();

        httpContext.SetupGet(h => h.Features).Returns(new FeatureCollection());
        var mockItems = new Dictionary <object, object>
        {
            { typeof(IUrlHelper), expectedUrlHelper }
        };

        httpContext.Setup(h => h.Items).Returns(mockItems);

        var actionContext    = CreateActionContext(httpContext.Object);
        var urlHelperFactory = new UrlHelperFactory();

        // Act
        var urlHelper = urlHelperFactory.GetUrlHelper(actionContext);

        // Assert
        Assert.Same(expectedUrlHelper, urlHelper);
    }
Beispiel #29
0
        public virtual async Task <RssChannel> GetChannel(CancellationToken cancellationToken = default(CancellationToken))
        {
            var project = await ProjectService.GetCurrentProjectSettings();

            if (project == null)
            {
                return(null);
            }

            var itemsToGet         = project.DefaultFeedItems;
            var requestedFeedItems = ContextAccessor.HttpContext?.Request.Query["maxItems"].ToString();

            if (!string.IsNullOrWhiteSpace(requestedFeedItems))
            {
                int.TryParse(requestedFeedItems, out itemsToGet);
                if (itemsToGet > project.MaxFeedItems)
                {
                    itemsToGet = project.MaxFeedItems;
                }
            }

            var posts = await BlogService.GetRecentPosts(itemsToGet);

            if (posts == null)
            {
                return(null);
            }

            var channel = new RssChannel
            {
                Title         = project.Title,
                Copyright     = project.CopyrightNotice,
                Generator     = Name,
                RemoteFeedUrl = project.RemoteFeedUrl,
                RemoteFeedProcessorUseAgentFragment = project.RemoteFeedProcessorUseAgentFragment
            };

            if (!string.IsNullOrEmpty(project.Description))
            {
                channel.Description = project.Description;
            }
            else
            {
                // prevent error, channel desc cannot be empty
                channel.Description = "Welcome to my blog";
            }

            if (!string.IsNullOrEmpty(project.ChannelCategoriesCsv))
            {
                var channelCats = project.ChannelCategoriesCsv.Split(',');
                foreach (var cat in channelCats)
                {
                    channel.Categories.Add(new RssCategory(cat));
                }
            }

            var urlHelper = UrlHelperFactory.GetUrlHelper(ActionContextAccesor.ActionContext);

            if (!string.IsNullOrEmpty(project.Image))
            {
                channel.Image.Url = new Uri(urlHelper.Content(project.Image));
            }
            if (!string.IsNullOrEmpty(project.LanguageCode))
            {
                channel.Language = new CultureInfo(project.LanguageCode);
            }

            var baseUrl = string.Concat(
                ContextAccessor.HttpContext.Request.Scheme,
                "://",
                ContextAccessor.HttpContext.Request.Host.ToUriComponent()
                );

            // asp.net bug? the comments for this method say it returns an absolute fully qualified url but it returns relative
            // looking at latest code seems ok so maybe just a bug in rc1
            //https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/UrlHelperExtensions.cs
            //https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/Routing/UrlHelper.cs

            var indexUrl = urlHelper.RouteUrl(BlogRoutes.BlogIndexRouteName);

            if (indexUrl == null)
            {
                indexUrl = urlHelper.Action("Index", "Blog");
            }

            if (indexUrl.StartsWith("/"))
            {
                indexUrl = string.Concat(baseUrl, indexUrl);
            }
            channel.Link = new Uri(indexUrl);
            if (!string.IsNullOrEmpty(project.ManagingEditorEmail))
            {
                channel.ManagingEditor = project.ManagingEditorEmail;
            }

            if (!string.IsNullOrEmpty(project.ChannelRating))
            {
                channel.Rating = project.ChannelRating;
            }

            var feedUrl = string.Concat(
                ContextAccessor.HttpContext.Request.Scheme,
                "://",
                ContextAccessor.HttpContext.Request.Host.ToUriComponent(),
                ContextAccessor.HttpContext.Request.PathBase.ToUriComponent(),
                ContextAccessor.HttpContext.Request.Path.ToUriComponent(),
                ContextAccessor.HttpContext.Request.QueryString.ToUriComponent());

            channel.SelfLink = new Uri(feedUrl);

            channel.TimeToLive = project.ChannelTimeToLive;
            if (!string.IsNullOrEmpty(project.WebmasterEmail))
            {
                channel.Webmaster = project.WebmasterEmail;
            }

            DateTime mostRecentPubDate = DateTime.MinValue;
            var      items             = new List <RssItem>();

            foreach (var post in posts)
            {
                if (!post.PubDate.HasValue)
                {
                    continue;
                }

                if (post.PubDate.Value > mostRecentPubDate)
                {
                    mostRecentPubDate = post.PubDate.Value;
                }
                var rssItem = new RssItem
                {
                    Author = post.Author
                };

                if (post.Categories.Count > 0)
                {
                    foreach (var c in post.Categories)
                    {
                        rssItem.Categories.Add(new RssCategory(c));
                    }
                }

                var postUrl = await BlogUrlResolver.ResolvePostUrl(post, project).ConfigureAwait(false);

                if (string.IsNullOrEmpty(postUrl))
                {
                    //TODO: log
                    continue;
                }

                if (postUrl.StartsWith("/"))
                {
                    //postUrl = urlHelper.Content(postUrl);
                    postUrl = string.Concat(
                        ContextAccessor.HttpContext.Request.Scheme,
                        "://",
                        ContextAccessor.HttpContext.Request.Host.ToUriComponent(),
                        postUrl);
                }

                var filteredResult = ContentProcessor.FilterHtmlForRss(post, project, baseUrl);
                rssItem.Description = filteredResult.FilteredContent;
                if (!filteredResult.IsFullContent)
                {
                    //TODO: localize
                    var readMore = " <a href='" + postUrl + "'>...read more</a>";
                    rssItem.Description += readMore;
                }

                //rssItem.Enclosures

                rssItem.Guid            = new RssGuid(postUrl, true);
                rssItem.Link            = new Uri(postUrl);
                rssItem.PublicationDate = post.PubDate.Value;
                //rssItem.Source
                rssItem.Title = post.Title;

                items.Add(rssItem);
            }

            channel.PublicationDate = mostRecentPubDate;
            channel.Items           = items;

            return(channel);
        }
Beispiel #30
0
        /// <inheritdoc />
        /// <remarks>Does nothing if user provides an <c>formaction</c> attribute.</remarks>
        /// <exception cref="InvalidOperationException">
        /// Thrown if <c>formaction</c> attribute is provided and <see cref="Action"/>, <see cref="Controller"/>,
        /// <see cref="Fragment"/> or <see cref="Route"/> are non-<c>null</c> or if the user provided <c>asp-route-*</c> attributes.
        /// Also thrown if <see cref="Route"/> and one or both of <see cref="Action"/> and <see cref="Controller"/>
        /// are non-<c>null</c>
        /// </exception>
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            // If "formaction" is already set, it means the user is attempting to use a normal button or input element.
            if (output.Attributes.ContainsName(FormAction))
            {
                if (Action != null ||
                    Controller != null ||
                    Area != null ||
                    Page != null ||
                    PageHandler != null ||
                    Fragment != null ||
                    Route != null ||
                    (_routeValues != null && _routeValues.Count > 0))
                {
                    // User specified a formaction and one of the bound attributes; can't override that formaction
                    // attribute.
                    throw new InvalidOperationException(
                              Resources.FormatFormActionTagHelper_CannotOverrideFormAction(
                                  FormAction,
                                  output.TagName,
                                  RouteValuesPrefix,
                                  ActionAttributeName,
                                  ControllerAttributeName,
                                  AreaAttributeName,
                                  FragmentAttributeName,
                                  RouteAttributeName,
                                  PageAttributeName,
                                  PageHandlerAttributeName));
                }

                return;
            }

            var routeLink  = Route != null;
            var actionLink = Controller != null || Action != null;
            var pageLink   = Page != null || PageHandler != null;

            if ((routeLink && actionLink) || (routeLink && pageLink) || (actionLink && pageLink))
            {
                var message = string.Join(
                    Environment.NewLine,
                    Resources.FormatCannotDetermineAttributeFor(FormAction, '<' + output.TagName + '>'),
                    RouteAttributeName,
                    ControllerAttributeName + ", " + ActionAttributeName,
                    PageAttributeName + ", " + PageHandlerAttributeName);

                throw new InvalidOperationException(message);
            }

            RouteValueDictionary routeValues = null;

            if (_routeValues != null && _routeValues.Count > 0)
            {
                routeValues = new RouteValueDictionary(_routeValues);
            }

            if (Area != null)
            {
                if (routeValues == null)
                {
                    routeValues = new RouteValueDictionary();
                }

                // Unconditionally replace any value from asp-route-area.
                routeValues["area"] = Area;
            }

            var    urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext);
            string url;

            if (pageLink)
            {
                url = urlHelper.Page(Page, PageHandler, routeValues, protocol: null, host: null, fragment: Fragment);
            }
            else if (routeLink)
            {
                url = urlHelper.RouteUrl(Route, routeValues, protocol: null, host: null, fragment: Fragment);
            }
            else
            {
                url = urlHelper.Action(Action, Controller, routeValues, protocol: null, host: null, fragment: Fragment);
            }

            output.Attributes.SetAttribute(FormAction, url);
        }