Skip to content

Commit

Permalink
Use new language features to clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
mitch-b committed Aug 4, 2024
1 parent d30a35e commit 329e049
Show file tree
Hide file tree
Showing 4 changed files with 91 additions and 117 deletions.
9 changes: 4 additions & 5 deletions ConsoleApp/Models/Configuration/ConsoleAppSettings.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
namespace ConsoleApp.Models.Configuration
namespace ConsoleApp.Models.Configuration;

public class ConsoleAppSettings
{
public class ConsoleAppSettings
{
public string? WelcomeMessage { get; set; }
}
public string? WelcomeMessage { get; set; }
}
72 changes: 32 additions & 40 deletions ConsoleApp/Services/ClientCredentialService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,54 +2,46 @@
using Microsoft.Extensions.Options;
using Microsoft.Identity.Client;

namespace ConsoleApp.Services
namespace ConsoleApp.Services;

internal interface IClientCredentialService
{
Task<AuthenticationResult> GetAuthenticationResult(IEnumerable<string>? scopes = null);
Task<string> GetAccessToken(IEnumerable<string>? scopes = null);
}

internal class ClientCredentialService(ILogger<ClientCredentialService> logger,
IOptions<ConfidentialClientApplicationOptions> confidentialClientApplicationOptions) : IClientCredentialService
{
internal interface IClientCredentialService
private readonly ILogger<ClientCredentialService> _logger = logger;
private readonly IConfidentialClientApplication _confidentialClientApplication =
ConfidentialClientApplicationBuilder
.CreateWithApplicationOptions(confidentialClientApplicationOptions.Value)
.Build();

public async Task<string> GetAccessToken(IEnumerable<string>? scopes = null)
{
Task<AuthenticationResult> GetAuthenticationResult(IEnumerable<string>? scopes = null);
Task<string> GetAccessToken(IEnumerable<string>? scopes = null);
var result = await GetAuthenticationResult(scopes);
return result.AccessToken;
}

internal class ClientCredentialService : IClientCredentialService
public async Task<AuthenticationResult> GetAuthenticationResult(IEnumerable<string>? scopes = null)
{
private readonly ILogger<ClientCredentialService> _logger;
private readonly IConfidentialClientApplication _confidentialClientApplication;

public ClientCredentialService(
ILogger<ClientCredentialService> logger,
IOptions<ConfidentialClientApplicationOptions> confidentialClientApplicationOptions)
AuthenticationResult? result = null;
scopes ??= new[] { ".default" };
try
{
_logger = logger;
_confidentialClientApplication = ConfidentialClientApplicationBuilder
.CreateWithApplicationOptions(confidentialClientApplicationOptions.Value)
.Build();
_logger.LogDebug($"Acquiring token with scopes: '{string.Join(" ", scopes)}'");
result = await _confidentialClientApplication
.AcquireTokenForClient(scopes)
.ExecuteAsync();
_logger.LogDebug("Acquired token");
}

public async Task<string> GetAccessToken(IEnumerable<string>? scopes = null)
catch (Exception e)
{
var result = await GetAuthenticationResult(scopes);
return result.AccessToken;
}

public async Task<AuthenticationResult> GetAuthenticationResult(IEnumerable<string>? scopes = null)
{
AuthenticationResult? result = null;
scopes ??= new[] { ".default" };
try
{
_logger.LogDebug($"Acquiring token with scopes: '{string.Join(" ", scopes)}'");
result = await _confidentialClientApplication
.AcquireTokenForClient(scopes)
.ExecuteAsync();
_logger.LogDebug("Acquired token");
}
catch (Exception e)
{
_logger.LogError(e, "Failed to acquire token");
throw;
}
return result;
_logger.LogError(e, "Failed to acquire token");
throw;
}
return result;
}
}

86 changes: 38 additions & 48 deletions ConsoleApp/Services/DemoService.cs
Original file line number Diff line number Diff line change
@@ -1,62 +1,52 @@
using System.Net.Http.Headers;
using System.Net.Http.Headers;
using System.Text.Json.Nodes;
using ConsoleApp.Models.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace ConsoleApp.Services
namespace ConsoleApp.Services;

internal interface IDemoService
{
internal interface IDemoService
{
void WriteWelcomeMessage();
Task<string> MakeGraphApiCall();
}
void WriteWelcomeMessage();
Task<string> MakeGraphApiCall();
}

internal class DemoService : IDemoService
internal class DemoService(ILogger<DemoService> logger,
IClientCredentialService clientCredentialService,
IOptions<ConsoleAppSettings> consoleAppSettings,
IHttpClientFactory httpClientFactory) : IDemoService
{
private readonly ILogger<DemoService> _logger = logger;
private readonly IClientCredentialService _clientCredentialService = clientCredentialService;
private readonly IOptions<ConsoleAppSettings> _consoleAppSettings = consoleAppSettings;
private readonly IHttpClientFactory _httpClientFactory = httpClientFactory;

public async Task<string> MakeGraphApiCall()
{
private readonly ILogger<DemoService> _logger;
private readonly IClientCredentialService _clientCredentialService;
private readonly IOptions<ConsoleAppSettings> _consoleAppSettings;
private readonly IHttpClientFactory _httpClientFactory;

public DemoService(ILogger<DemoService> logger,
IClientCredentialService clientCredentialService,
IOptions<ConsoleAppSettings> consoleAppSettings,
IHttpClientFactory httpClientFactory)
{
_logger = logger;
_clientCredentialService = clientCredentialService;
_consoleAppSettings = consoleAppSettings;
_httpClientFactory = httpClientFactory;
}
var accessToken = await _clientCredentialService.GetAccessToken(
["https://graph.microsoft.com/.default"]);

public async Task<string> MakeGraphApiCall()
{
var accessToken = await _clientCredentialService.GetAccessToken(
new[] { "https://graph.microsoft.com/.default" });

var httpClient = _httpClientFactory.CreateClient("GraphApi");
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);

var response = await httpClient.GetAsync("/v1.0/users");

JsonNode? result = null;
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
result = JsonNode.Parse(json);
}
return result is null
? ""
: result.ToJsonString();
}
var httpClient = _httpClientFactory.CreateClient("GraphApi");
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);

public void WriteWelcomeMessage()
var response = await httpClient.GetAsync("/v1.0/users");

JsonNode? result = null;
if (response.IsSuccessStatusCode)
{
_logger.LogInformation("Saying hello");
Console.WriteLine(_consoleAppSettings.Value?.WelcomeMessage);
var json = await response.Content.ReadAsStringAsync();
result = JsonNode.Parse(json);
}
return result is null
? ""
: result.ToJsonString();
}
}

public void WriteWelcomeMessage()
{
_logger.LogInformation("Saying hello");
Console.WriteLine(_consoleAppSettings.Value?.WelcomeMessage);
}
}
41 changes: 17 additions & 24 deletions ConsoleApp/WorkerService.cs
Original file line number Diff line number Diff line change
@@ -1,34 +1,27 @@
using ConsoleApp.Services;
using Microsoft.Extensions.Hosting;

namespace ConsoleApp
{
internal class WorkerService : IHostedService
{
private readonly IDemoService _demoService;
namespace ConsoleApp;

public WorkerService(IDemoService demoService)
{
_demoService = demoService;
}
internal class WorkerService(IDemoService demoService) : IHostedService
{
private readonly IDemoService _demoService = demoService;

public async Task StartAsync(CancellationToken cancellationToken)
public async Task StartAsync(CancellationToken cancellationToken)
{
var response = await _demoService.MakeGraphApiCall();
if (!string.IsNullOrWhiteSpace(response))
{
var response = await _demoService.MakeGraphApiCall();
if (!string.IsNullOrWhiteSpace(response))
{
Console.WriteLine(response);
}

while (true)
{
_demoService.WriteWelcomeMessage();
await Task.Delay(3000);
}
Console.WriteLine(response);
}

public Task StopAsync(CancellationToken cancellationToken)
=> Task.CompletedTask;
while (true)
{
_demoService.WriteWelcomeMessage();
await Task.Delay(3000);
}
}
}

public Task StopAsync(CancellationToken cancellationToken)
=> Task.CompletedTask;
}

0 comments on commit 329e049

Please sign in to comment.