Skip to content

Commit

Permalink
Merge pull request #11 from NRG-Drink/feat/file-based
Browse files Browse the repository at this point in the history
Feat/file based
  • Loading branch information
NRG-Drink authored May 22, 2024
2 parents a94e6b6 + a89ad15 commit d055c16
Show file tree
Hide file tree
Showing 10 changed files with 182 additions and 51 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -399,4 +399,6 @@ FodyWeavers.xsd

# Custom
appsettings.json
calendar-finder-appsettings.json
calendar-finder-appsettings.json
mydata.json
launchSettings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using NRG.CalendarFinder.MsGraphFactories;

Expand Down
121 changes: 92 additions & 29 deletions NRG.CalendarFinder/NRG.CalendarFinder/CalendarFinderWorker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,83 @@ namespace NRG.CalendarFinder;
public class CalendarFinderWorker(
IHost host,
CalendarFinderService finder,
Options options
ProcessData processData
)
: BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
await Console.Out.WriteLineAsync($"Start Process with options: {processData.Options}");
var processed = new List<OutputData>();
foreach (var input in processData.Inputs)
{
await WriteObjectAsync("Query", options);

var user = await finder.FindUserAsyncOrThrow(options.UserIdentifier);
var calendars = await finder.FindCalendarsAsyncOrThrow(user);
var output = new OutputData() { Input = input };
try
{
var user = await finder.FindUserAsyncOrThrow(input.UserIdentifier);
var calendars = await finder.FindCalendarsAsyncOrThrow(user);

await WriteObjectAsync("Result", GetPrintObject(user, calendars));
}
catch (ODataError ex)
{
await Console.Out.WriteLineAsync($"Failed with {nameof(ODataError)}: {ex.Error?.Message}");
output = GetOutputObject(output, user, calendars);
}
catch (ODataError ex)
{
var message = $"Failed with {nameof(ODataError)}: {ex.Error?.Message}";
output = output with { Error = message };
}
catch (Exception ex)
{
var message = $"Failed with error: {ex.Message}";
output = output with { Error = message };
}
finally
{
processed.Add(output);
await Console.Out.WriteLineAsync($"Terminate search for: {input.UserIdentifier}");
}
}
catch (Exception ex)

var path = GetResultPath(processData.Options.FilePath);
await WriteToFile(path, processed);

if (processData.Options.OpenEditor == true)
{
await Console.Out.WriteLineAsync($"Failed with error: {ex.Message}");
OpenVsCode(path);
}
finally

await host.StopAsync(stoppingToken);
}

private static void OpenVsCode(string path)
{
var p = new System.Diagnostics.Process()
{
await host.StopAsync(stoppingToken);
}
StartInfo = new()
{
UseShellExecute = true,
FileName = "code",
Arguments = path
}
};
p.Start();
}

private static async Task WriteToFile(string path, List<OutputData> output)
{
var text = JsonSerializer.Serialize(output, options: new() { WriteIndented = true });
await File.WriteAllTextAsync(path, text);
await Console.Out.WriteLineAsync($"Wrote output data to file {path}.");
}

private static string GetResultPath(string inputPath)
{
var name = Path.GetFileNameWithoutExtension(inputPath);
var dir = Path.GetPathRoot(inputPath)
?? throw new ArgumentNullException(
$"No root directory for file {inputPath} found. " +
$"Output file could not be written."
);
var path = Path.Combine(dir, $"{name}.result.json");
return path;
}

private static Task WriteObjectAsync(string text, object? obj)
Expand All @@ -44,22 +94,35 @@ private static Task WriteObjectAsync(string text, object? obj)
return Console.Out.WriteLineAsync($"{text}:\n{json}");
}

private static object GetPrintObject(User user, List<Calendar> calendars)
=> new
private static OutputData GetOutputObject(OutputData output, User user, List<Calendar> calendars)
=> output with
{
User = new
User = new()
{
user.DisplayName,
user.Id,
user.Mail,
user.UserPrincipalName
DisplayName = user.DisplayName,
UserId = user.Id,
Mail = user.Mail,
PrincipalName = user.UserPrincipalName,
CalendarId = GetDefaultCalendarId(calendars)
},
Calendars = calendars.Select(e => new
{
e.Id,
e.Name,
Owner = e.Owner?.Address,
e.IsDefaultCalendar
Calendars = calendars
.Select(e => new MyCalendar()
{
Id = e.Id,
Name = e.Name,
Owner = e.Owner?.Address,
IsDefault = e.IsDefaultCalendar
})
.ToArray()
};

private static string? GetDefaultCalendarId(List<Calendar> calendars)
{
if (calendars.Count == 1)
{
return calendars.Single().Id;
}

return calendars.FirstOrDefault(e => e.IsDefaultCalendar == true)?.Id;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NRG.CalendarFinder.Models;

namespace NRG.CalendarFinder.Extensions;

public static class IHostBuilderExtensionsProcessData
{
public static IHostBuilder AddProcessDataFromJson(this IHostBuilder builder, Options options)
{
builder.ConfigureServices((context, services) =>
{
var inputData = context.Configuration
.GetSection(nameof(InputData.UserIdentifier))
.GetChildren()
.Select(e => e.Value)
.OfType<string>()
.Select(e => new InputData() { UserIdentifier = e })
.ToArray();

var data = new ProcessData()
{
Options = options,
Inputs = inputData
};

services.AddSingleton(data);
});

return builder;
}
}
8 changes: 4 additions & 4 deletions NRG.CalendarFinder/NRG.CalendarFinder/Models/Options.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ namespace NRG.CalendarFinder.Models;

public record Options
{
[Option('u', "user", Required = true, HelpText = "Can be a Guid or the user-principal-name (mail-address)")]
public required string UserIdentifier { get; set; }
[Option('a', "appsettings", Required = false, HelpText = "Path and filename of appsettings.json")]
public string AppSettingsPath { get; set; } = "calendar-finder-appsettings.json";
[Option('f', "file", Required = true, HelpText = "Name or path to the file. (e.g. mydata.json)")]
public required string FilePath { get; init; }
[Option('e', "open-editor", Required = false, HelpText = "Open the editor after finish.")]
public bool? OpenEditor { get; init; } = true;
}
42 changes: 42 additions & 0 deletions NRG.CalendarFinder/NRG.CalendarFinder/Models/ProcessData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Text.Json.Serialization;

namespace NRG.CalendarFinder.Models;

public record ProcessData
{
public required Options Options { get; init; }
public InputData[] Inputs { get; init; } = [];
}

public record InputData
{
public required string UserIdentifier { get; init; }
}

public record OutputData
{
public required InputData Input { get; init; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? Error { get; init; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public MyUser? User { get; init; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public MyCalendar[]? Calendars { get; init; }
}

public record MyUser
{
public string? DisplayName { get; init; }
public string? PrincipalName { get; init; }
public string? Mail { get; init; }
public string? UserId { get; init; }
public string? CalendarId { get; init; }
}

public record MyCalendar
{
public string? Id { get; init; }
public string? Name { get; init; }
public string? Owner { get; init; }
public bool? IsDefault { get; init; }
}
12 changes: 0 additions & 12 deletions NRG.CalendarFinder/NRG.CalendarFinder/NRG.CalendarFinder.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,4 @@
<PackageReference Include="Microsoft.Graph" Version="5.52.0" />
</ItemGroup>

<ItemGroup>
<None Update="calendar-finder-appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="calendar-finder-appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="calendar-finder-appsettings.template.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
5 changes: 3 additions & 2 deletions NRG.CalendarFinder/NRG.CalendarFinder/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NRG.CalendarFinder.Exteinsions;
using NRG.CalendarFinder.Extensions;
using NRG.CalendarFinder.Models;

namespace NRG.CalendarFinder;
Expand All @@ -25,17 +26,17 @@ private static async Task RunHost(Options options)
var host = Host.CreateDefaultBuilder()
.ConfigureAppConfiguration(builder =>
{
builder.AddJsonFile(options.AppSettingsPath);
builder.AddJsonFile(options.FilePath);
})
.ConfigureServices((context, services) =>
{
// Services
services.AddSingleton(options);
services.AddSingleton<CalendarFinderService>();

// Workers
services.AddHostedService<CalendarFinderWorker>();
})
.AddProcessDataFromJson(options)
.AddGraphClientsFromJson()
.UseConsoleLifetime()
.ConfigureLogging(e => e.SetMinimumLevel(LogLevel.None))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"profiles": {
"NRG.CalendarFinder": {
"commandName": "Project",
"commandLineArgs": "-u mail@provider.com"
"commandLineArgs": "-f mydata.json"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@
"Thumbprint": "my_thumbprint",
"Scopes": null
}
],
"UserIdentifier": [
"myUserPrincipalName",
"myUserId"
]
}

0 comments on commit d055c16

Please sign in to comment.