-
Notifications
You must be signed in to change notification settings - Fork 25
Convert LinqPad examples to .NET 8 console apps with basic auth middleware #66
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 5 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
b566d5b
minor.
Jaben 64119f3
Convert LinqPad examples to .NET 8 console applications
Jaben b898101
Added examples to solution (no build)
Jaben 96eda82
Add basic authentication support via reusable HTTP middleware
Jaben 3cc6fdb
Ignore the output files.
Jaben 65cd8cf
Merge develop into feature/convert-linqpad-to-console
Jaben 28bb8fd
Minor -- added solution items.
Jaben 54cda1d
Fix resource disposal and add CancellationToken.None to all CopyToAsy…
Jaben f4875f2
Add validation and null-forgiving operators to BasicAuth handler regi…
Jaben ce98331
Fix GitHub Actions build by adding example project build configurations
Jaben 096803d
Minor.
Jaben fde2acb
Nitpick addressed.
Jaben 4b93802
Fix for Footer/Header swap.
Jaben 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
Some comments aren't visible on the classic Files Changed page.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -288,3 +288,5 @@ __pycache__/ | |
*.odx.cs | ||
*.xsd.cs | ||
|
||
settings.local.json | ||
examples/**/output |
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
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,2 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
</Project> |
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,69 @@ | ||
using Gotenberg.Sharp.API.Client; | ||
using Gotenberg.Sharp.API.Client.Domain.Builders; | ||
using Gotenberg.Sharp.API.Client.Domain.Builders.Faceted; | ||
using Gotenberg.Sharp.API.Client.Domain.Requests; | ||
using Gotenberg.Sharp.API.Client.Domain.Settings; | ||
using Gotenberg.Sharp.API.Client.Extensions; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Logging; | ||
|
||
// Builds a simple DI container with logging enabled. | ||
// Client retrieved through the service provider is configured with options defined in appsettings.json | ||
// Watch the polly-retry policy in action: | ||
// Turn off gotenberg, run this script and let it fail/retry two or three times. | ||
// Turn gotenberg back on & the request will successfully complete. | ||
// Example builds a 1 page PDF from the specified TargetUrl | ||
|
||
const string TargetUrl = "https://www.cnn.com"; | ||
var saveToPath = args.Length > 0 ? args[0] : Path.Combine(Directory.GetCurrentDirectory(), "output"); | ||
Directory.CreateDirectory(saveToPath); | ||
|
||
var services = BuildServiceCollection(); | ||
var sp = services.BuildServiceProvider(); | ||
|
||
var sharpClient = sp.GetRequiredService<GotenbergSharpClient>(); | ||
var request = await CreateUrlRequest(); | ||
var response = await sharpClient.UrlToPdfAsync(request); | ||
|
||
var resultPath = Path.Combine(saveToPath, $"GotenbergFromUrl-{DateTime.Now:yyyyMMddHHmmss}.pdf"); | ||
|
||
using (var destinationStream = File.Create(resultPath)) | ||
{ | ||
await response.CopyToAsync(destinationStream); | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} | ||
|
||
Console.WriteLine($"PDF created: {resultPath}"); | ||
|
||
IServiceCollection BuildServiceCollection() | ||
{ | ||
var config = new ConfigurationBuilder() | ||
.SetBasePath(AppContext.BaseDirectory) | ||
.AddJsonFile("appsettings.json") | ||
.Build(); | ||
|
||
return new ServiceCollection() | ||
.AddOptions<GotenbergSharpClientOptions>() | ||
.Bind(config.GetSection(nameof(GotenbergSharpClient))).Services | ||
.AddGotenbergSharpClient() | ||
.Services.AddLogging(s => s.AddSimpleConsole(ops => | ||
{ | ||
ops.IncludeScopes = true; | ||
ops.SingleLine = false; | ||
ops.TimestampFormat = "hh:mm:ss "; | ||
})); | ||
} | ||
|
||
Task<UrlRequest> CreateUrlRequest() | ||
{ | ||
var builder = new UrlRequestBuilder() | ||
.SetUrl(TargetUrl) | ||
.ConfigureRequest(b => b.SetPageRanges("1-2")) | ||
.WithPageProperties(b => | ||
{ | ||
b.SetPaperSize(PaperSizes.A4) | ||
.SetMargins(Margins.None); | ||
}); | ||
|
||
return builder.BuildAsync(); | ||
} |
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,31 @@ | ||
<Project> | ||
<PropertyGroup> | ||
<OutputType>Exe</OutputType> | ||
<TargetFramework>net8.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\..\src\Gotenberg.Sharp.Api.Client\Gotenberg.Sharp.Api.Client.csproj" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" /> | ||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" /> | ||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" /> | ||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> | ||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" /> | ||
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.0" /> | ||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<None Include="..\appsettings.json" Link="appsettings.json"> | ||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> | ||
</None> | ||
<None Include="..\resources\**\*.*" Link="resources\%(RecursiveDir)%(Filename)%(Extension)"> | ||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> | ||
</None> | ||
</ItemGroup> | ||
</Project> |
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,2 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
</Project> |
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,70 @@ | ||
using Gotenberg.Sharp.API.Client; | ||
using Gotenberg.Sharp.API.Client.Domain.Builders; | ||
using Gotenberg.Sharp.API.Client.Domain.Builders.Faceted; | ||
using Gotenberg.Sharp.API.Client.Domain.Settings; | ||
using Gotenberg.Sharp.API.Client.Infrastructure.Pipeline; | ||
using Microsoft.Extensions.Configuration; | ||
|
||
var config = new ConfigurationBuilder() | ||
.SetBasePath(AppContext.BaseDirectory) | ||
.AddJsonFile("appsettings.json") | ||
.Build(); | ||
|
||
var options = new GotenbergSharpClientOptions(); | ||
config.GetSection(nameof(GotenbergSharpClient)).Bind(options); | ||
|
||
var destinationDirectory = args.Length > 0 ? args[0] : Path.Combine(Directory.GetCurrentDirectory(), "output"); | ||
Directory.CreateDirectory(destinationDirectory); | ||
|
||
var resourcePath = Path.Combine(AppContext.BaseDirectory, "resources", "Html", "ConvertExample"); | ||
var path = await CreateFromHtml(destinationDirectory, resourcePath, options); | ||
|
||
Console.WriteLine($"PDF created: {path}"); | ||
|
||
static async Task<string> CreateFromHtml(string destinationDirectory, string resourcePath, GotenbergSharpClientOptions options) | ||
{ | ||
var handler = new HttpClientHandler(); | ||
var httpClient = new HttpClient( | ||
!string.IsNullOrWhiteSpace(options.BasicAuthUsername) && !string.IsNullOrWhiteSpace(options.BasicAuthPassword) | ||
? new BasicAuthHandler(options.BasicAuthUsername, options.BasicAuthPassword) { InnerHandler = handler } | ||
: handler | ||
) | ||
{ BaseAddress = options.ServiceUrl }; | ||
|
||
var sharpClient = new GotenbergSharpClient(httpClient); | ||
|
||
var builder = new HtmlRequestBuilder() | ||
.AddAsyncDocument(async doc => | ||
doc.SetBody(await GetHtmlFile(resourcePath, "body.html")) | ||
.SetFooter(await GetHtmlFile(resourcePath, "footer.html")) | ||
).WithPageProperties(dims => dims.UseChromeDefaults()) | ||
.WithAsyncAssets(async assets => | ||
assets.AddItem("ear-on-beach.jpg", await GetImageBytes(resourcePath)) | ||
) | ||
.SetConversionBehaviors(b => | ||
b.AddAdditionalHeaders("hello", "from-earth") | ||
) | ||
.ConfigureRequest(b => b.SetPageRanges("1")); | ||
|
||
var request = await builder.BuildAsync(); | ||
|
||
var resultPath = Path.Combine(destinationDirectory, $"GotenbergFromHtml-{DateTime.Now:yyyyMMddHHmmss}.pdf"); | ||
var response = await sharpClient.HtmlToPdfAsync(request); | ||
|
||
using (var destinationStream = File.Create(resultPath)) | ||
{ | ||
await response.CopyToAsync(destinationStream); | ||
} | ||
|
||
return resultPath; | ||
} | ||
|
||
static Task<byte[]> GetImageBytes(string resourcePath) | ||
{ | ||
return File.ReadAllBytesAsync(Path.Combine(resourcePath, "ear-on-beach.jpg")); | ||
} | ||
|
||
static Task<byte[]> GetHtmlFile(string resourcePath, string fileName) | ||
{ | ||
return File.ReadAllBytesAsync(Path.Combine(resourcePath, fileName)); | ||
} |
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,2 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
</Project> |
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.