Skip to content

Commit

Permalink
✨ Added helper functions to handle null reference warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
Marthijn van den Heuvel committed Jul 22, 2024
1 parent 4fe3404 commit f9f786a
Show file tree
Hide file tree
Showing 8 changed files with 214 additions and 17 deletions.
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ services.AddDefaultSitemapServices<HttpContextBaseUrlProvider>();
[HttpGet]
public IActionResult Sitemap()
{
var nodes = new List<SitemapNode> { new ("page.html"), new (Url.Action("Index")) };
var nodes = new List<SitemapNode> { new ("page.html"), SitemapNode.Create(Url.Action("Index")) };
var sitemap = new Sitemap(nodes);
return new SitemapResult(sitemap);
}
Expand All @@ -36,8 +36,17 @@ public IActionResult Sitemap()
public IActionResult SitemapIndex()
{
var sitemapIndex = new SitemapIndex();

// basic usage:
sitemapIndex.Add(new SitemapIndexNode(Url.Action("Sitemap1")));
sitemapIndex.Add(new SitemapIndexNode(Url.Action("Sitemap2")));

// or: this extension function fixes the null reference warning
// on the line above:
var addResult = sitemapIndex.TryAdd(Url.Action("Sitemap2"));

// or: use the Create function
sitemapIndex.Add(SitemapIndexNode.Create(Url.Action("Sitemap1")));

return new SitemapResult(sitemapIndex);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ public sealed class SitemapController : Controller
public IActionResult SitemapIndex()
{
var sitemapIndex = new SitemapIndex();
sitemapIndex.Add(new SitemapIndexNode(Url.Action("SitemapHome")));
sitemapIndex.Add(new SitemapIndexNode(Url.Action("SitemapNews")));
sitemapIndex.Add(new SitemapIndexNode(Url.Action("SitemapImages")));
sitemapIndex.Add(new SitemapIndexNode(Url.Action("SitemapVideos")));
_ = sitemapIndex.TryAdd(Url.Action("SitemapHome"));
_ = sitemapIndex.TryAdd(Url.Action("SitemapNews"));
_ = sitemapIndex.TryAdd(Url.Action("SitemapImages"));
_ = sitemapIndex.TryAdd(Url.Action("SitemapVideos"));

return new SitemapResult(sitemapIndex);
}
Expand All @@ -22,8 +22,10 @@ public IActionResult SitemapIndex()
public IActionResult SitemapHome()
{
var sitemap = new Core.Sitemap();
sitemap.Add(new SitemapNode(Url.Action("Index", "Home")));
sitemap.Add(new SitemapNode(Url.Action("Privacy", "Home")));

// handle null warnings by using the TryAdd function
_ = sitemap.TryAdd(Url.Action("Index", "Home"));
_ = sitemap.TryAdd(Url.Action("Privacy", "Home"));

return new SitemapResult(sitemap);
}
Expand All @@ -32,7 +34,13 @@ public IActionResult SitemapHome()
public IActionResult SitemapNews()
{
var sitemap = new Core.Sitemap();
sitemap.Add(new SitemapNewsNode(Url.Action("Article1", "News"), "Article1", "John Doe", "EN", DateTime.UtcNow));

// handle null warnings by checking the URL for null
var url = Url.Action("Article1", "News");
if (url != null)
{
sitemap.Add(new SitemapNewsNode(url, "Article1", "John Doe", "EN", DateTime.UtcNow));
}

return new SitemapResult(sitemap);
}
Expand All @@ -43,7 +51,9 @@ public IActionResult SitemapImages()
var imageLocation = new ImageLocation("non-existing-image.jpg");

var sitemap = new Core.Sitemap();
sitemap.Add(new SitemapImageNode(Url.Action("Index", "Home"), imageLocation));

// handle null warnings by using the Create function
sitemap.Add(SitemapImageNode.Create(Url.Action("Index", "Home"), imageLocation));

return new SitemapResult(sitemap);
}
Expand All @@ -54,7 +64,7 @@ public IActionResult SitemapVideos()
var video = new VideoContent("non-existing-video-thumbnail.jpg", "Video1", "Video1 description", "non-existing-video.mp4", null);

var sitemap = new Core.Sitemap();
sitemap.Add(new SitemapVideoNode(Url.Action("Index", "Home"), video));
sitemap.Add(SitemapVideoNode.Create(Url.Action("Index", "Home"), video));

return new SitemapResult(sitemap);
}
Expand Down
63 changes: 63 additions & 0 deletions src/Sidio.Sitemap.AspNetCore.Tests/SitemapExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
namespace Sidio.Sitemap.AspNetCore.Tests;

public sealed class SitemapExtensionsTests
{
[Fact]
public void TryAdd_WhenUrlIsValid_SitemapNodeAdded()
{
// arrange
var sitemap = new Core.Sitemap();
const string Url = "/index.html";

// act
var result = sitemap.TryAdd(Url);

// assert
result.Should().BeTrue();
sitemap.Nodes.Count.Should().Be(1);
}

[Fact]
public void TryAdd_WhenUrlIsEmpty_SitemapNodeNotAdded()
{
// arrange
var sitemap = new Core.Sitemap();

// act
var result = sitemap.TryAdd(string.Empty);

// assert
result.Should().BeFalse();
sitemap.Nodes.Should().BeEmpty();
}

[Fact]
public void TryAdd_WhenUrlsAreValid_SitemapNodesAdded()
{
// arrange
var sitemap = new Core.Sitemap();
const string Url = "/index.html";

// act
var result = sitemap.TryAdd(Url, Url, Url);

// assert
result.Should().Be(3);
sitemap.Nodes.Count.Should().Be(3);
}

[Fact]
public void TryAdd_WhenSomeUrlsAreEmpty_SitemapNodeAdded()
{
// arrange
var sitemap = new Core.Sitemap();
const string Url = "/index.html";

// act
var result = sitemap.TryAdd(Url, string.Empty, Url, " ");

// assert
result.Should().Be(2);
sitemap.Nodes.Count.Should().Be(2);
}
}
35 changes: 35 additions & 0 deletions src/Sidio.Sitemap.AspNetCore.Tests/SitemapIndexExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Sidio.Sitemap.Core;

namespace Sidio.Sitemap.AspNetCore.Tests;

public sealed class SitemapIndexExtensionsTests
{
[Fact]
public void TryAdd_WhenUrlIsValid_SitemapIndexNodeAdded()
{
// arrange
var sitemapIndex = new SitemapIndex();
const string Url = "/index.html";

// act
var result = sitemapIndex.TryAdd(Url);

// assert
result.Should().BeTrue();
sitemapIndex.Nodes.Count.Should().Be(1);
}

[Fact]
public void TryAdd_WhenUrlIsEmpty_SitemapIndexNodeNotAdded()
{
// arrange
var sitemapIndex = new SitemapIndex();

// act
var result = sitemapIndex.TryAdd(string.Empty);

// assert
result.Should().BeFalse();
sitemapIndex.Nodes.Should().BeEmpty();
}
}
25 changes: 20 additions & 5 deletions src/Sidio.Sitemap.AspNetCore/Services/ControllerSitemapService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,19 +88,28 @@ public IReadOnlySet<SitemapNode> CreateSitemap(Type controllerType)

private HttpContext HttpContext => _httpContextAccessor.HttpContext ?? throw new InvalidOperationException("HttpContext is null");

private SitemapNode CreateNode(ControllerActionDescriptor action)
private SitemapNode? CreateNode(ControllerActionDescriptor action)
{
var url = _linkGenerator.GetUriByAction(HttpContext, action.ActionName, action.ControllerName);

if (_logger.IsEnabled(LogLevel.Trace))
if (_logger.IsEnabled(LogLevel.Warning) && string.IsNullOrWhiteSpace(url))
{
_logger.LogWarning(
"Unable to create sitemap URL for action `{Action}` in controller `{Controller}`",
action.ActionName,
action.ControllerName);
}

if (_logger.IsEnabled(LogLevel.Trace) && !string.IsNullOrWhiteSpace(url))
{
_logger.LogTrace(
"Created sitemap URL for action `{Action}` in controller `{Controller}`",
action.ActionName,
action.ControllerName);

}

return new SitemapNode(url);
return !string.IsNullOrWhiteSpace(url) ? new SitemapNode(url) : null;
}

private HashSet<SitemapNode> GetControllerMethodsOptIn(Type controllerType, IEnumerable<ControllerActionDescriptor> actions)
Expand All @@ -114,7 +123,10 @@ private HashSet<SitemapNode> GetControllerMethodsOptIn(Type controllerType, IEnu
if (includeFunction)
{
var node = CreateNode(action);
nodes.Add(node);
if (node != null)
{
nodes.Add(node);
}
}
else
{
Expand Down Expand Up @@ -153,7 +165,10 @@ private HashSet<SitemapNode> GetControllerMethodsOptOut(Type controllerType, IEn
if (!excludeFunction)
{
var node = CreateNode(action);
nodes.Add(node);
if (node != null)
{
nodes.Add(node);
}
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Sidio.Sitemap.Core" Version="2.3.0" />
<PackageReference Include="Sidio.Sitemap.Core" Version="2.5.0" />
</ItemGroup>

</Project>
40 changes: 40 additions & 0 deletions src/Sidio.Sitemap.AspNetCore/SitemapExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System.Diagnostics;
using Sidio.Sitemap.Core;

namespace Sidio.Sitemap.AspNetCore;

/// <summary>
/// The Sitemap extensions.
/// </summary>
public static class SitemapExtensions
{
/// <summary>
/// Adds a nullable URL to the sitemap.
/// </summary>
/// <param name="sitemap">The sitemap.</param>
/// <param name="url">The URL.</param>
/// <returns>Returns <c>true</c> when the url was added.</returns>
public static bool TryAdd(this Core.Sitemap sitemap, string? url)
{
if (string.IsNullOrWhiteSpace(url))
{
return false;
}

return sitemap.Add(new SitemapNode(url)) == 1;
}

/// <summary>
/// Adds a range of nullable URLs to the sitemap.
/// </summary>
/// <param name="sitemap">The sitemap.</param>
/// <param name="urls">The urls.</param>
/// <returns>Returns actual the number of nodes that were added.</returns>
public static int TryAdd(this Core.Sitemap sitemap, params string?[] urls)
{
var nonNullableUrls = urls.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => new SitemapNode(x ?? throw new UnreachableException())).Cast<ISitemapNode>().ToArray();

return nonNullableUrls.Length > 0 ? sitemap.Add(nonNullableUrls) : 0;
}
}
25 changes: 25 additions & 0 deletions src/Sidio.Sitemap.AspNetCore/SitemapIndexExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Sidio.Sitemap.Core;

namespace Sidio.Sitemap.AspNetCore;

/// <summary>
/// The Sitemap-index extensions.
/// </summary>
public static class SitemapIndexExtensions
{
/// <summary>
/// Adds a nullable URL to the sitemap index.
/// </summary>
/// <param name="sitemapIndex">The sitemap index.</param>
/// <param name="url">The URL.</param>
/// <returns>Returns <c>true</c> when the url was added.</returns>
public static bool TryAdd(this SitemapIndex sitemapIndex, string? url)
{
if (string.IsNullOrWhiteSpace(url))
{
return false;
}

return sitemapIndex.Add(new SitemapIndexNode(url)) == 1;
}
}

0 comments on commit f9f786a

Please sign in to comment.