-
Notifications
You must be signed in to change notification settings - Fork 8
feat: Adds sitemap generation #753
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
c36dba0
Adds sitemap generation
BenjaminMichaelis 4afc52f
Updates logging for Application Insights.
BenjaminMichaelis 9e398c3
Updates WebApplicationFactory usage
BenjaminMichaelis b06a9ea
Improves sitemap generation and route handling.
BenjaminMichaelis 04faf47
Merge branch 'main' into sitemapGeneration
BenjaminMichaelis fab5360
PR Feedback
BenjaminMichaelis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
65 changes: 65 additions & 0 deletions
65
EssentialCSharp.Web.Tests/RouteConfigurationServiceTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| using EssentialCSharp.Web.Services; | ||
| using Microsoft.AspNetCore.Mvc.Testing; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
|
|
||
| namespace EssentialCSharp.Web.Tests; | ||
|
|
||
| public class RouteConfigurationServiceTests : IClassFixture<WebApplicationFactory<Program>> | ||
| { | ||
| private readonly WebApplicationFactory<Program> _Factory; | ||
| private readonly IRouteConfigurationService _RouteConfigurationService; | ||
|
|
||
| public RouteConfigurationServiceTests(WebApplicationFactory<Program> factory) | ||
| { | ||
| _Factory = factory; | ||
|
|
||
| // Get the service from the DI container to test with real routes | ||
| var scope = _Factory.Services.CreateScope(); | ||
| _RouteConfigurationService = scope.ServiceProvider.GetRequiredService<IRouteConfigurationService>(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void GetStaticRoutes_ShouldReturnExpectedRoutes() | ||
| { | ||
| // Act | ||
| var routes = _RouteConfigurationService.GetStaticRoutes().ToList(); | ||
|
|
||
| // Assert | ||
| Assert.NotEmpty(routes); | ||
|
|
||
| // Check for expected routes from the HomeController | ||
| Assert.Contains("home", routes); | ||
| Assert.Contains("about", routes); | ||
| Assert.Contains("guidelines", routes); | ||
| Assert.Contains("announcements", routes); | ||
| Assert.Contains("termsofservice", routes); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void GetStaticRoutes_ShouldIncludeAllHomeControllerRoutes() | ||
BenjaminMichaelis marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| // Act | ||
| var routes = _RouteConfigurationService.GetStaticRoutes().ToHashSet(StringComparer.OrdinalIgnoreCase); | ||
|
|
||
| // Assert - check all expected routes from HomeController | ||
| var expectedRoutes = new[] { "home", "about", "guidelines", "announcements", "termsofservice" }; | ||
|
|
||
| foreach (var expectedRoute in expectedRoutes) | ||
| { | ||
| Assert.True(routes.Contains(expectedRoute), | ||
| $"Expected route '{expectedRoute}' was not found in discovered routes: [{string.Join(", ", routes)}]"); | ||
| } | ||
| } | ||
|
|
||
| [Fact] | ||
| public void GetStaticRoutes_ShouldNotIncludeIdentityRoutes() | ||
| { | ||
| // Act | ||
| var routes = _RouteConfigurationService.GetStaticRoutes(); | ||
|
|
||
| // Assert - ensure no Identity area routes are included | ||
| Assert.DoesNotContain("identity", routes, StringComparer.OrdinalIgnoreCase); | ||
| } | ||
|
|
||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| using Microsoft.AspNetCore.Mvc; | ||
| using Microsoft.AspNetCore.Mvc.Filters; | ||
| using EssentialCSharp.Web.Services; | ||
|
|
||
| namespace EssentialCSharp.Web.Controllers; | ||
|
|
||
| public abstract class BaseController : Controller | ||
| { | ||
| private readonly IRouteConfigurationService _routeConfigurationService; | ||
|
|
||
| protected BaseController(IRouteConfigurationService routeConfigurationService) | ||
| { | ||
| _routeConfigurationService = routeConfigurationService; | ||
| } | ||
|
|
||
| public override void OnActionExecuting(ActionExecutingContext context) | ||
| { | ||
| // Automatically add static routes to all views | ||
| ViewBag.StaticRoutes = System.Text.Json.JsonSerializer.Serialize(_routeConfigurationService.GetStaticRoutes()); | ||
| base.OnActionExecuting(context); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| using DotnetSitemapGenerator; | ||
| using DotnetSitemapGenerator.Serialization; | ||
| using Microsoft.AspNetCore.Mvc.Infrastructure; | ||
|
|
||
| namespace EssentialCSharp.Web.Helpers; | ||
|
|
||
| public static class SitemapXmlHelpers | ||
| { | ||
| private const string RootUrl = "https://essentialcsharp.com/"; | ||
BenjaminMichaelis marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| public static void EnsureSitemapHealthy(List<SiteMapping> siteMappings) | ||
| { | ||
| var groups = siteMappings.GroupBy(item => new { item.ChapterNumber, item.PageNumber }); | ||
| foreach (var group in groups) | ||
| { | ||
| try | ||
| { | ||
| SiteMapping result = group.Single(item => item.IncludeInSitemapXml); | ||
BenjaminMichaelis marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| catch (Exception ex) | ||
| { | ||
| throw new InvalidOperationException($"Sitemap error: Chapter {group.Key.ChapterNumber}, Page {group.Key.PageNumber} has more than one canonical link, or none: {ex.Message}", ex); | ||
BenjaminMichaelis marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
| } | ||
|
|
||
| public static void GenerateAndSerializeSitemapXml(DirectoryInfo wwwrootDirectory, List<SiteMapping> siteMappings, ILogger logger, IActionDescriptorCollectionProvider actionDescriptorCollectionProvider) | ||
| { | ||
| GenerateSitemapXml(wwwrootDirectory, siteMappings, actionDescriptorCollectionProvider, out string xmlPath, out List<SitemapNode> nodes); | ||
| XmlSerializer sitemapProvider = new(); | ||
| sitemapProvider.Serialize(new SitemapModel(nodes), xmlPath, true); | ||
| logger.LogInformation("sitemap.xml successfully written to {XmlPath}", xmlPath); | ||
| } | ||
|
|
||
| public static void GenerateSitemapXml(DirectoryInfo wwwrootDirectory, List<SiteMapping> siteMappings, IActionDescriptorCollectionProvider actionDescriptorCollectionProvider, out string xmlPath, out List<SitemapNode> nodes) | ||
| { | ||
| xmlPath = Path.Combine(wwwrootDirectory.FullName, "sitemap.xml"); | ||
BenjaminMichaelis marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| DateTime newDateTime = DateTime.UtcNow; | ||
|
|
||
| // Start with the root URL | ||
| nodes = new() { | ||
| new($"{RootUrl}") | ||
| { | ||
| LastModificationDate = newDateTime, | ||
| ChangeFrequency = ChangeFrequency.Daily, | ||
| Priority = 1.0M | ||
| } | ||
| }; | ||
|
|
||
| // Add routes dynamically discovered from controllers (excluding Identity routes) | ||
| var controllerRoutes = GetControllerRoutes(actionDescriptorCollectionProvider); | ||
| foreach (var route in controllerRoutes) | ||
| { | ||
| nodes.Add(new($"{RootUrl.TrimEnd('/')}{route}") | ||
| { | ||
| LastModificationDate = newDateTime, | ||
| ChangeFrequency = GetChangeFrequencyForRoute(route), | ||
| Priority = GetPriorityForRoute(route) | ||
| }); | ||
| } | ||
|
|
||
| // Add site mappings from content | ||
| nodes.AddRange(siteMappings.Where(item => item.IncludeInSitemapXml).Select<SiteMapping, SitemapNode>(siteMapping => new($"{RootUrl}{siteMapping.Keys.First()}") | ||
BenjaminMichaelis marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| LastModificationDate = newDateTime, | ||
| ChangeFrequency = ChangeFrequency.Daily, | ||
| Priority = 0.8M | ||
| })); | ||
| } | ||
|
|
||
| private static List<string> GetControllerRoutes(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider) | ||
| { | ||
| var routes = new List<string>(); | ||
|
|
||
| foreach (var actionDescriptor in actionDescriptorCollectionProvider.ActionDescriptors.Items) | ||
| { | ||
| // Skip Identity area routes | ||
| if (actionDescriptor.RouteValues.TryGetValue("area", out var area) && area == "Identity") | ||
| continue; | ||
|
|
||
| // Skip the default fallback route (Index action in HomeController) | ||
| if (actionDescriptor.RouteValues.TryGetValue("action", out var action) && action == "Index") | ||
| continue; | ||
|
|
||
| // Skip Error actions | ||
| if (action == "Error") | ||
| continue; | ||
|
|
||
| // Get the route template or attribute route | ||
| if (actionDescriptor.AttributeRouteInfo?.Template is string template) | ||
| { | ||
| // Clean up the template (remove parameters, etc.) | ||
| var cleanRoute = template.TrimStart('/'); | ||
| if (!string.IsNullOrEmpty(cleanRoute) && !routes.Contains($"/{cleanRoute}")) | ||
| { | ||
| routes.Add($"/{cleanRoute}"); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return routes.Distinct().OrderBy(r => r).ToList(); | ||
| } | ||
|
|
||
| private static ChangeFrequency GetChangeFrequencyForRoute(string route) | ||
| { | ||
| return route.ToLowerInvariant() switch | ||
| { | ||
| "/termsofservice" => ChangeFrequency.Yearly, | ||
| "/announcements" => ChangeFrequency.Monthly, | ||
| "/guidelines" => ChangeFrequency.Monthly, | ||
| _ => ChangeFrequency.Monthly | ||
| }; | ||
| } | ||
|
|
||
| private static decimal GetPriorityForRoute(string route) | ||
| { | ||
| return route.ToLowerInvariant() switch | ||
| { | ||
| "/home" => 0.5M, | ||
| "/about" => 0.5M, | ||
| "/announcements" => 0.5M, | ||
| "/guidelines" => 0.9M, | ||
| "/termsofservice" => 0.2M, | ||
| _ => 0.5M | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| public class InvalidItemException : Exception | ||
| { | ||
| public InvalidItemException(string? message) : base(message) | ||
| { | ||
| } | ||
| public InvalidItemException(string? message, Exception exception) : base(message, exception) | ||
| { | ||
| } | ||
| } | ||
BenjaminMichaelis marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.