Skip to content

Commit

Permalink
Merge pull request #7 from Redacted-Team/sprint-4
Browse files Browse the repository at this point in the history
Sprint 4
  • Loading branch information
brewerkm1 authored Apr 9, 2024
2 parents 6adcbe0 + cfbed8a commit d431298
Show file tree
Hide file tree
Showing 13 changed files with 199 additions and 74 deletions.
2 changes: 1 addition & 1 deletion GameMicroServer.sln → APIGateway.sln
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34221.43
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameMicroServer", "GameMicroServer\GameMicroServer.csproj", "{C8787DE3-73A1-4FA9-BC23-865FCF0560AF}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "APIGateway", "APIGateway\APIGateway.csproj", "{C8787DE3-73A1-4FA9-BC23-865FCF0560AF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="6.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
Expand Down
85 changes: 85 additions & 0 deletions APIGateway/Controllers/GatewayController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Net.Http.Json;

namespace Gateway
{
/// <summary>
/// Controller responsible for handling requests and responses at the gateway.
/// </summary>
[ApiController]
[Route("[controller]")]
public class GatewayController : ControllerBase
{
private readonly HttpClient _httpClient; // Making readonly ensures thread safety
private readonly ILogger<GatewayController> _logger; // Making readonly ensures thread safety

public GatewayController(HttpClient httpClient, ILogger<GatewayController> logger)
{
_httpClient = httpClient;
_logger = logger;
}

/// <summary>
/// Handles GET requests to retrieve game information from the microservice.
/// </summary>
/// <returns>A collection of GameInfo objects.</returns>
[HttpGet]
public async Task<IEnumerable<GameInfo>> Get()
{
try
{
// Make a GET request to the microservice's endpoint
HttpResponseMessage response = await _httpClient.GetAsync("https://localhost:7223/Micro"); // URL might need to change for deployment

// Check if the request was successful
if (response.IsSuccessStatusCode)
{
// Deserialize the response content to a list of GameInfo objects
var gameInfoList = await response.Content.ReadAsAsync<List<GameInfo>>();
return gameInfoList;
}
else
{
_logger.LogError($"Failed to retrieve data from microservice. Status code: {response.StatusCode}");
// Return a placeholder list of GameInfo objects indicating failure
return GenerateFailureResponse();
}
}
catch (Exception ex)
{
_logger.LogError($"An error occurred while fetching data from microservice: {ex.Message}");
// Return a placeholder list of GameInfo objects indicating failure
return GenerateFailureResponse();
}
}

/// <summary>
/// Generates a placeholder list of GameInfo objects indicating failure to retrieve data.
/// </summary>
/// <returns>A collection of GameInfo objects indicating failure.</returns>
private IEnumerable<GameInfo> GenerateFailureResponse()
{
// Using IEnumerable allows flexibility in returning a placeholder response.
// It allows the method to return different types of collections (e.g., List, Array) if needed in the future.
// In this case, IEnumerable provides a simple way to return a list of failed responses.

// Generate a placeholder list of GameInfo objects indicating failure to retrieve data
return new List<GameInfo>
{
new GameInfo
{
Title = "Failed to retrieve from Microservice",
Author = "Failed to retrieve from Microservice",
Description = "Failed to retrieve from Microservice",
HowTo = "Failed to retrieve from Microservice",
LeaderBoardStack = new Stack<KeyValuePair<string, int>>() // Initializing an empty stack
}
};
}
}
}
File renamed without changes.
2 changes: 1 addition & 1 deletion GameMicroServer/GameInfo.cs → APIGateway/GameInfo.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Micro
namespace Gateway
{
public class GameInfo
{
Expand Down
41 changes: 41 additions & 0 deletions APIGateway/Logging/TimestampLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
namespace APIGateway
{
using Microsoft.Extensions.Logging;
using System;

// This class details the beginning steps of the logger with timestamps. It implements ILogger,
// which comes with a few methods to be fulfilled.

// This was written via ChatGPT 3.5.
public class TimestampLogger : ILogger
{
// This method is called when a new scope is requested for logging.
// Scopes are used to provide additional contextual information for log messages.
// In this implementation, it simply returns null because no specific scope is being managed.
public IDisposable BeginScope<TState>(TState state)
{
return null;
}

// This method is called to check if logging at the specified log level is enabled.
// It can be used to implement filtering based on log levels.
// In this implementation, it always returns true, indicating that logging at any level is enabled.
// You may modify this method to implement filtering based on log levels if needed.
public bool IsEnabled(LogLevel logLevel)
{
return true; // You may implement filtering based on log level
}

// This method is called to perform the actual logging of a message.
// It formats the log message with a timestamp in the format "yyyy-MM-dd HH:mm:ss",
// combines it with the formatted state and exception provided by the formatter function,
// and writes the resulting message to the console.
// You can replace Console.WriteLine(message) with your preferred logging mechanism.
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
string message = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} - {formatter(state, exception)}";

Console.WriteLine(message); // Change this to your preferred logging mechanism
}
}
}
27 changes: 27 additions & 0 deletions APIGateway/Logging/TimestampLoggerExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
namespace APIGateway
{
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using static IServiceCollection;

// This was written via ChatGPT 3.5.

public static class TimestampLoggerExtensions
{
// This extension method is used to extend the functionality of the ILoggingBuilder interface.
// It adds the capability to configure the logging system to include a timestamp in log messages.
// The method adds a timestamp logger to the logging builder.

public static ILoggingBuilder AddTimestampLogger(this ILoggingBuilder builder)
{
// Inside the method, it accesses the IServiceCollection provided by the logging builder (builder.Services).
// It registers the TimestampLoggerProvider as a singleton service for ILoggerProvider.
// This ensures that the TimestampLoggerProvider will be used to create logger instances.
builder.Services.AddSingleton<ILoggerProvider, TimestampLoggerProvider>();

// Finally, it returns the logging builder instance to support method chaining.
// This allows further configuration to be chained after adding the timestamp logger.
return builder;
}
}
}
28 changes: 28 additions & 0 deletions APIGateway/Logging/TimestampLoggerProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
namespace APIGateway
{
using Microsoft.Extensions.Logging;
using System;

// This was written via ChatGPT 3.5.

// This class creates the baseline for the LoggerProvider. It implements ILoggerProvider,
// which simply just needs to create a logger and return it, whilst disposing of any extras.
public class TimestampLoggerProvider : ILoggerProvider
{
// This method is called when a logger is requested for a specific category.
// It creates and returns a new instance of the TimestampLogger class.
// Each logger provider can be associated with one or more logger instances.
// In this case, it always returns a new instance of TimestampLogger for any requested category.

public ILogger CreateLogger(string categoryName)
{
// Creates and returns a new instance of TimestampLogger.
return new TimestampLogger();
}

// This method is called to release any resources used by the logger provider.
// Since this implementation does not hold any resources that need to be released explicitly,
// this method doesn't perform any action.
public void Dispose() { }
}
}
13 changes: 13 additions & 0 deletions GameMicroServer/Program.cs → APIGateway/Program.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using APIGateway;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
Expand All @@ -7,6 +9,17 @@
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Register HttpClient
builder.Services.AddHttpClient();

// This creates the services for the Logging files.
builder.Services.AddLogging(builder =>
{
builder.AddConsole();
builder.AddDebug();
builder.AddTimestampLogger(); // Add timestamp logger
});

var app = builder.Build();

// Configure the HTTP request pipeline.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"profiles": {
"GameMicroServer": {
"APIGateway": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7223;http://localhost:5130"
"applicationUrl": "https://localhost:4141"
},
"IIS Express": {
"commandName": "IISExpress",
Expand Down
File renamed without changes.
File renamed without changes.
70 changes: 0 additions & 70 deletions GameMicroServer/Controllers/microController.cs

This file was deleted.

0 comments on commit d431298

Please sign in to comment.