Skip to content

Commit

Permalink
Upgrade to v8.1
Browse files Browse the repository at this point in the history
  • Loading branch information
mythz committed Feb 6, 2024
1 parent 54a7d41 commit 2a896ca
Show file tree
Hide file tree
Showing 11 changed files with 61 additions and 80 deletions.
14 changes: 4 additions & 10 deletions MyApp/Configure.AppHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,20 @@

namespace MyApp;

public class AppHost : AppHostBase, IHostingStartup
public class AppHost() : AppHostBase("MyApp"), IHostingStartup
{
public void Configure(IWebHostBuilder builder) => builder
.ConfigureServices(services => {
// Configure ASP.NET Core IOC Dependencies
});

public AppHost() : base("MyApp", typeof(MyServices).Assembly) {}

public override void Configure(Funq.Container container)
public override void Configure()
{
ConfigurePlugin<NativeTypesFeature>(feature =>
{
feature.MetadataTypesConfig.ExportAttributes.Add(typeof(FieldAttribute));
});
}
}

public class Hello : IReturn<StringResponse> {}
public class Hello : IGet, IReturn<StringResponse> {}
public class MyServices : Service
{
public object Any(Hello request) => new StringResponse { Result = $"Hello, World!" };
}
}
3 changes: 1 addition & 2 deletions MyApp/Configure.Ssg.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@ public void Configure(IWebHostBuilder builder) => builder
var videos = appHost.Resolve<MarkdownVideos>();
var meta = appHost.Resolve<MarkdownMeta>();
meta.Features = new() { pages, whatsNew, videos };
meta.Features.ForEach(x => x.VirtualFiles = appHost.VirtualFiles);
meta.Features = [pages, whatsNew, videos];
pages.LoadFrom("_pages");
whatsNew.LoadFrom("_whatsnew");
Expand Down
3 changes: 1 addition & 2 deletions MyApp/Markdown.Meta.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace MyApp;

public class MarkdownMeta
{
public List<IMarkdownPages> Features { get; set; } = new();
public List<IMarkdownPages> Features { get; set; } = [];

public async Task RenderToAsync(string metaDir, string baseUrl)
{
Expand Down Expand Up @@ -57,5 +57,4 @@ public async Task RenderToAsync(string metaDir, string baseUrl)
await File.WriteAllTextAsync(metaDir.CombineWith($"{year}/all.json"), JSON.stringify(yearDocs));
}
}

}
27 changes: 12 additions & 15 deletions MyApp/Markdown.Pages.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
// run node postinstall.js to update to latest version
using ServiceStack.IO;
using ServiceStack.Logging;

namespace Ssg;
namespace MyApp;

public class MarkdownPages : MarkdownPagesBase<MarkdownFileInfo>
public class MarkdownPages(ILogger<MarkdownPages> log, IWebHostEnvironment env, IVirtualFiles fs)
: MarkdownPagesBase<MarkdownFileInfo>(log, env, fs)
{
public override string Id => "pages";

public virtual string? DefaultMenuIcon { get; set; } =
"<svg class='h-6 w-6 shrink-0 text-sky-500' fill='none' viewBox='0 0 24 24' stroke-width='1.5' stroke='currentColor' aria-hidden='true'><path stroke-linecap='round' stroke-linejoin='round' d='M2.25 12l8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25'></path></svg>";

public MarkdownPages(ILogger<MarkdownPages> log, IWebHostEnvironment env) : base(log,env) {}

List<MarkdownFileInfo> Pages { get; set; } = new();
public List<MarkdownFileInfo> GetVisiblePages(string? prefix=null, bool allDirectories=false) => prefix == null
? Pages.Where(x => IsVisible(x) && !x.Slug!.Contains('/')).OrderBy(x => x.Order).ThenBy(x => x.Path).ToList()
Expand All @@ -31,12 +30,10 @@ public void LoadFrom(string fromDirectory)
{
Sidebars.Clear();
Pages.Clear();
var fs = AssertVirtualFiles();
var files = fs.GetDirectory(fromDirectory).GetAllFiles()
var files = VirtualFiles.GetDirectory(fromDirectory).GetAllFiles()
.OrderBy(x => x.VirtualPath)
.ToList();
var log = LogManager.GetLogger(GetType());
log.InfoFormat("Found {0} pages", files.Count);
log.LogInformation("Found {Count} pages", files.Count);

var pipeline = CreatePipeline();

Expand All @@ -50,7 +47,7 @@ public void LoadFrom(string fromDirectory)
if (doc == null)
continue;

var relativePath = file.VirtualPath.Substring(fromDirectory.Length + 1);
var relativePath = file.VirtualPath[(fromDirectory.Length + 1)..];
if (relativePath.IndexOf('/') >= 0)
{
doc.Slug = relativePath.LastLeftPart('/') + '/' + doc.Slug;
Expand All @@ -61,7 +58,7 @@ public void LoadFrom(string fromDirectory)
else if (file.Name == "sidebar.json")
{
var virtualPath = file.VirtualPath.Substring(fromDirectory.Length);
var folder = virtualPath.Substring(0, virtualPath.Length - "sidebar.json".Length).Trim('/');
var folder = virtualPath[..^"sidebar.json".Length].Trim('/');
var sidebarJson = file.ReadAllText();
var sidebar = sidebarJson.FromJson<List<MarkdownMenu>>();

Expand All @@ -76,12 +73,12 @@ public void LoadFrom(string fromDirectory)
}
catch (Exception e)
{
log.Error(e, "Couldn't load {0}: {1}", file.VirtualPath, e.Message);
log.LogError(e, "Couldn't load {VirtualPath}: {Message}", file.VirtualPath, e.Message);
}
}
if (Sidebars.Count > 0)
{
log.Info($"Loaded {Sidebars.Count} sidebars: {Sidebars.Keys.Join(", ")}");
log.LogInformation("Loaded {Count} sidebars: {Sidebars}", Sidebars.Count, Sidebars.Keys.Join(", "));
}
}

Expand All @@ -105,7 +102,7 @@ public virtual List<MarkdownMenu> GetSidebar(string folder, MarkdownMenu? defaul
if (group == null)
{
menuItem = defaultMenu ?? new MarkdownMenu {
Children = new(),
Children = [],
};
}
else
Expand All @@ -118,7 +115,7 @@ public virtual List<MarkdownMenu> GetSidebar(string folder, MarkdownMenu? defaul

foreach (var page in allPages.Where(x => x.Group == group).OrderBy(x => x.Order))
{
menuItem.Children ??= new();
menuItem.Children ??= [];
var link = page.Slug!;
if (link.EndsWith("/index"))
{
Expand Down
15 changes: 7 additions & 8 deletions MyApp/Markdown.Videos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,26 @@
// run node postinstall.js to update to latest version
using ServiceStack.IO;

namespace Ssg;
namespace MyApp;

public class MarkdownVideos : MarkdownPagesBase<MarkdownFileInfo>
public class MarkdownVideos(ILogger<MarkdownVideos> log, IWebHostEnvironment env, IVirtualFiles fs)
: MarkdownPagesBase<MarkdownFileInfo>(log, env, fs)
{
public override string Id => "videos";
public MarkdownVideos(ILogger<MarkdownVideos> log, IWebHostEnvironment env) : base(log,env) {}
public Dictionary<string, List<MarkdownFileInfo>> Groups { get; set; } = new();

public List<MarkdownFileInfo> GetVideos(string group)
{
return Groups.TryGetValue(group, out var docs)
? Fresh(docs.Where(IsVisible).OrderBy(x => x.Order).ThenBy(x => x.FileName).ToList())
: new List<MarkdownFileInfo>();
: [];
}

public void LoadFrom(string fromDirectory)
{
Groups.Clear();
var fs = AssertVirtualFiles();
var dirs = fs.GetDirectory(fromDirectory).GetDirectories().ToList();
Log.LogInformation("Found {0} video directories", dirs.Count);
var dirs = VirtualFiles.GetDirectory(fromDirectory).GetDirectories().ToList();
log.LogInformation("Found {Count} video directories", dirs.Count);

var pipeline = CreatePipeline();

Expand All @@ -44,7 +43,7 @@ public void LoadFrom(string fromDirectory)
}
catch (Exception e)
{
Log.LogError(e, "Couldn't load {0}: {1}", file.VirtualPath, e.Message);
log.LogError(e, "Couldn't load {VirtualPath}: {Message}", file.VirtualPath, e.Message);
}
}
}
Expand Down
19 changes: 9 additions & 10 deletions MyApp/Markdown.WhatsNew.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,26 @@
using System.Globalization;
using ServiceStack.IO;

namespace Ssg;
namespace MyApp;

public class MarkdownWhatsNew : MarkdownPagesBase<MarkdownFileInfo>
public class MarkdownWhatsNew(ILogger<MarkdownWhatsNew> log, IWebHostEnvironment env, IVirtualFiles fs)
: MarkdownPagesBase<MarkdownFileInfo>(log, env, fs)
{
public override string Id => "whatsnew";
public MarkdownWhatsNew(ILogger<MarkdownWhatsNew> log, IWebHostEnvironment env) : base(log,env) {}
public Dictionary<string, List<MarkdownFileInfo>> Features { get; set; } = new();

public List<MarkdownFileInfo> GetFeatures(string release)
{
return Features.TryGetValue(release, out var docs)
? Fresh(docs.Where(IsVisible).OrderBy(x => x.Order).ThenBy(x => x.FileName).ToList())
: new List<MarkdownFileInfo>();
: [];
}

public void LoadFrom(string fromDirectory)
{
Features.Clear();
var fs = AssertVirtualFiles();
var dirs = fs.GetDirectory(fromDirectory).GetDirectories().ToList();
Log.LogInformation("Found {0} whatsnew directories", dirs.Count);
var dirs = VirtualFiles.GetDirectory(fromDirectory).GetDirectories().ToList();
log.LogInformation("Found {Count} whatsnew directories", dirs.Count);

var pipeline = CreatePipeline();

Expand All @@ -32,7 +31,7 @@ public void LoadFrom(string fromDirectory)
if (!DateTime.TryParseExact(datePart, "yyyy-MM-dd", CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal, out var date))
{
Log.LogWarning("Could not parse date '{0}', ignoring...", datePart);
log.LogWarning("Could not parse date '{DatePart}', ignoring...", datePart);
continue;
}

Expand All @@ -50,12 +49,12 @@ public void LoadFrom(string fromDirectory)
doc.Date = releaseDate;
doc.Group = releaseVersion;

var releaseFeatures = Features.GetOrAdd(releaseVersion, v => new List<MarkdownFileInfo>());
var releaseFeatures = Features.GetOrAdd(dir.Name, v => new List<MarkdownFileInfo>());
releaseFeatures.Add(doc);
}
catch (Exception e)
{
Log.LogError(e, "Couldn't load {0}: {1}", file.VirtualPath, e.Message);
log.LogError(e, "Couldn't load {VirtualPath}: {Message}", file.VirtualPath, e.Message);
}
}
}
Expand Down
42 changes: 15 additions & 27 deletions MyApp/MarkdownPagesBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
using ServiceStack.IO;
using ServiceStack.Text;

namespace Ssg;
namespace MyApp;

public class MarkdigConfig
{
Expand Down Expand Up @@ -88,22 +88,14 @@ public virtual void Update(MarkdownFileBase newDoc)
public interface IMarkdownPages
{
string Id { get; }
IVirtualFiles VirtualFiles { get; set; }
List<MarkdownFileBase> GetAll();
}
public abstract class MarkdownPagesBase<T> : IMarkdownPages where T : MarkdownFileBase

public abstract class MarkdownPagesBase<T>(ILogger log, IWebHostEnvironment env, IVirtualFiles fs) : IMarkdownPages

Check warning on line 94 in MyApp/MarkdownPagesBase.cs

View workflow job for this annotation

GitHub Actions / build

Parameter 'log' is unread.
where T : MarkdownFileBase
{
public abstract string Id { get; }
protected ILogger Log { get; }
protected IWebHostEnvironment Environment { get; }

public MarkdownPagesBase(ILogger log, IWebHostEnvironment env)
{
this.Log = log;
this.Environment = env;
}

public IVirtualFiles VirtualFiles { get; set; } = default!;
public IVirtualFiles VirtualFiles => fs;

public virtual MarkdownPipeline CreatePipeline()
{
Expand Down Expand Up @@ -133,7 +125,7 @@ public virtual List<T> Fresh(List<T> docs)
public virtual T? Fresh(T? doc)
{
// Ignore reloading source .md if run in production or as AppTask
if (doc == null || !Environment.IsDevelopment() || AppTasks.IsRunAsAppTask())
if (doc == null || !env.IsDevelopment() || AppTasks.IsRunAsAppTask())
return doc;
var newDoc = Load(doc.Path);
doc.Update(newDoc);

Check warning on line 131 in MyApp/MarkdownPagesBase.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'newDoc' in 'void MarkdownFileBase.Update(MarkdownFileBase newDoc)'.
Expand Down Expand Up @@ -166,6 +158,7 @@ public virtual T CreateMarkdownFile(string content, TextWriter writer, MarkdownP
.ConvertTo<T>()
?? typeof(T).CreateInstance<T>();

doc.Tags = doc.Tags.Map(x => x.Trim());
doc.Content = content;
doc.DocumentMap = document.GetData(nameof(DocumentMap)) as DocumentMap;

Expand All @@ -174,7 +167,7 @@ public virtual T CreateMarkdownFile(string content, TextWriter writer, MarkdownP

public virtual T? Load(string path, MarkdownPipeline? pipeline = null)
{
var file = VirtualFiles.GetFile(path)
var file = fs.GetFile(path)
?? throw new FileNotFoundException(path.LastRightPart('/'));
var content = file.ReadAllText();

Expand All @@ -196,7 +189,7 @@ public virtual T CreateMarkdownFile(string content, TextWriter writer, MarkdownP
return doc;
}

public virtual bool IsVisible(T doc) => Environment.IsDevelopment() ||
public virtual bool IsVisible(T doc) => env.IsDevelopment() ||
!doc.Draft && (doc.Date == null || doc.Date.Value <= DateTime.UtcNow);

public int WordsPerMin { get; set; } = 225;
Expand All @@ -205,9 +198,6 @@ public virtual bool IsVisible(T doc) => Environment.IsDevelopment() ||
public virtual int LineCount(string str) => str.CountOccurrencesOf('\n');
public virtual int MinutesToRead(int? words) => (int)Math.Ceiling((words ?? 1) / (double)WordsPerMin);

protected IVirtualFiles AssertVirtualFiles() =>
VirtualFiles ?? throw new NullReferenceException($"{nameof(VirtualFiles)} is not populated");

public virtual List<MarkdownFileBase> GetAll() => new();

public virtual string? StripFrontmatter(string? content)
Expand Down Expand Up @@ -495,11 +485,10 @@ protected override void Write(HtmlRenderer renderer, CustomContainerInline obj)
}
}

public class CustomContainerRenderers : HtmlObjectRenderer<CustomContainer>
public class CustomContainerRenderers(ContainerExtensions extensions) : HtmlObjectRenderer<CustomContainer>
{
public CustomContainerRenderers(ContainerExtensions extensions) => Extensions = extensions;
public ContainerExtensions Extensions { get; }

public ContainerExtensions Extensions { get; } = extensions;

protected override void Write(HtmlRenderer renderer, CustomContainer obj)
{
var useRenderer = obj.Info != null && Extensions.BlockContainers.TryGetValue(obj.Info, out var customRenderer)
Expand All @@ -509,11 +498,10 @@ protected override void Write(HtmlRenderer renderer, CustomContainer obj)
}
}

public class CustomContainerInlineRenderers : HtmlObjectRenderer<CustomContainerInline>
public class CustomContainerInlineRenderers(ContainerExtensions extensions) : HtmlObjectRenderer<CustomContainerInline>
{
public CustomContainerInlineRenderers(ContainerExtensions extensions) => Extensions = extensions;
public ContainerExtensions Extensions { get; }

public ContainerExtensions Extensions { get; } = extensions;

protected override void Write(HtmlRenderer renderer, CustomContainerInline obj)
{
var firstWord = obj.FirstChild is LiteralInline literalInline
Expand Down
2 changes: 1 addition & 1 deletion MyApp/MarkdownTagHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace Ssg;
namespace MyApp;

[HtmlTargetElement("markdown", TagStructure = TagStructure.NormalOrSelfClosing)]
[HtmlTargetElement(Attributes = "markdown")]
Expand Down
3 changes: 1 addition & 2 deletions MyApp/MyApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
</PropertyGroup>
<ItemGroup>
<Using Include="Ssg" />
<Using Include="MyApp" />
<Using Include="ServiceStack" />
<Using Include="ServiceStack.Mvc" />
Expand All @@ -22,7 +21,7 @@
</Target>

<ItemGroup>
<PackageReference Include="Markdig" Version="0.30.*" />
<PackageReference Include="Markdig" Version="0.34.*" />
<PackageReference Include="ServiceStack" Version="8.*" />
<PackageReference Include="ServiceStack.Mvc" Version="8.*" />

Expand Down
1 change: 0 additions & 1 deletion MyApp/Pages/_ViewImports.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

@using ServiceStack
@using ServiceStack.Mvc
@using Ssg
@using MyApp
@namespace MyApp.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Expand Down
Loading

0 comments on commit 2a896ca

Please sign in to comment.