Skip to content

Commit

Permalink
Xml comments (#26)
Browse files Browse the repository at this point in the history
* fixed data parser

* added time and lifecycle manager

* improved docs

* added comments

* incremented version
  • Loading branch information
joshika39 committed Nov 6, 2023
1 parent 9438459 commit acd6393
Show file tree
Hide file tree
Showing 33 changed files with 669 additions and 131 deletions.
2 changes: 1 addition & 1 deletion Nuget/.projects.conf
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Modules:1.2.1
Modules:1.3.0
17 changes: 17 additions & 0 deletions _src/Implementation/Application/LifeCycleManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Threading;
using Infrastructure.Application;

namespace Implementation.Application
{
internal class LifeCycleManager : ILifeCycleManager
{
public CancellationTokenSource Source { get; }
public CancellationToken Token => Source.Token;

public LifeCycleManager(CancellationTokenSource source)
{
Source = source ?? throw new ArgumentNullException(nameof(source));
}
}
}
16 changes: 4 additions & 12 deletions _src/Implementation/IO/DefaultDataParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ public T TryParse<T>(string input, IDataParser.TryParseHandler<T> handler, out b
return result;
}

public IEnumerable<T> TryParse<T>(string input, IDataParser.TryParseHandler<T> handler, out bool isOkay, char separator, params char[] separators)
public IEnumerable<T> TryParse<T>(string input, IDataParser.TryParseHandler<T> handler, char separator, params char[] separators)
{
isOkay = false;
separators = new[]
{
separator
Expand All @@ -27,7 +26,7 @@ public IEnumerable<T> TryParse<T>(string input, IDataParser.TryParseHandler<T> h
var convertedLines = new List<T>();
foreach (var line in lines)
{
isOkay = handler(line, out var result);
var isOkay = handler(line, out var result);
if (isOkay)
{
convertedLines.Add(result);
Expand All @@ -37,18 +36,11 @@ public IEnumerable<T> TryParse<T>(string input, IDataParser.TryParseHandler<T> h
return convertedLines;
}

public IEnumerable<IEnumerable<T>> MultiTryParse<T>(string input, IDataParser.TryParseHandler<T> handler, out bool isOkay, char separator, params char[] separators)
public IEnumerable<IEnumerable<T>> MultiTryParse<T>(string input, IDataParser.TryParseHandler<T> handler, char separator, params char[] separators)
{
isOkay = false;
var convertedLines = new List<IEnumerable<T>>();
var lines = input.Split(Environment.NewLine);

foreach (var line in lines)
{
convertedLines.Add(TryParse(line, handler, out isOkay, separator, separators));
}

return convertedLines;
return lines.Select(line => TryParse(line, handler, separator, separators)).ToList();
}
}
}
23 changes: 4 additions & 19 deletions _src/Implementation/IO/Reader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ public Reader(ILogger logger, IWriter writer, IDataParser dataParser)
_dataParser = dataParser ?? throw new ArgumentNullException(nameof(dataParser));
}

public IEnumerable<T> ReadLine<T>(StreamReader streamReader, IDataParser.TryParseHandler<T> handler,
out bool isOkay, char separator, params char[] separators)
public IEnumerable<T> ReadLine<T>(StreamReader streamReader, IDataParser.TryParseHandler<T> handler, char separator, params char[] separators)
{
Console.SetIn(streamReader);

Expand All @@ -32,7 +31,7 @@ public Reader(ILogger logger, IWriter writer, IDataParser dataParser)
_logger.LogWrite($"{rawInput}\n");
}

return _dataParser.TryParse(rawInput, handler, out isOkay, separator, separators);
return _dataParser.TryParse(rawInput, handler, separator, separators);
}

public T? ReadLine<T>(StreamReader streamReader, IDataParser.TryParseHandler<T> handler, out bool isOkay)
Expand Down Expand Up @@ -63,8 +62,7 @@ public IEnumerable<T> ReadLine<T>(IDataParser.TryParseHandler<T> handler, string
var reader = new StreamReader(Console.OpenStandardInput());
var time = DateTime.Now.ToString("HH:mm:ss");
_writer.Write(Constants.EscapeColors.CYAN, $"[ INPUT: {time}] {prompt}");
var ans = ReadLine(reader, handler, out _, separator, separators);
return ans;
return ReadLine(reader, handler, separator, separators);
}

public string ReadLine(string prompt, string errorMsg)
Expand Down Expand Up @@ -98,14 +96,7 @@ public T ReadLine<T>(IDataParser.TryParseHandler<T> handler, string prompt, stri
{
var time = DateTime.Now.ToString("HH:mm:ss");
_writer.Write(Constants.EscapeColors.CYAN, $"[ INPUT: {time}] {prompt}");
var ans = ReadLine(reader, handler, out var isCorrect, separator, separators);

if (isCorrect)
{
return ans;
}

_writer.WriteLine(MessageSeverity.Error, $"{errorMsg} | (Invalid type: {typeof(T)})!");
return ReadLine(reader, handler, separator, separators);
}
}

Expand All @@ -121,12 +112,6 @@ public IEnumerable<T> ReadLine<T>(IDataParser.TryParseHandler<T> handler, char s
return ReadLine(reader, handler, separator, separators);
}

public IEnumerable<T> ReadLine<T>(StreamReader streamReader, IDataParser.TryParseHandler<T> handler,
char separator, params char[] separators)
{
return ReadLine(streamReader, handler, out _, separator, separators);
}

public string ReadAllLines(string prompt)
{
var streamReader = new StreamReader(Console.OpenStandardInput());
Expand Down
19 changes: 15 additions & 4 deletions _src/Implementation/Module/CoreModule.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,31 @@
using System;
using System.IO;
using System.Threading;
using GameFramework.Impl.Time;
using Implementation.Application;
using Implementation.Configuration.Factories;
using Implementation.IO;
using Implementation.Navigator.Factories;
using Implementation.Repositories.Factories;
using Implementation.Time.Factories;
using Infrastructure.Application;
using Infrastructure.Configuration.Factories;
using Infrastructure.IO;
using Infrastructure.Logger;
using Infrastructure.Module;
using Infrastructure.Navigator.Factories;
using Infrastructure.Repositories.Factories;
using Infrastructure.Time;
using Infrastructure.Time.Factories;
using Microsoft.Extensions.DependencyInjection;

namespace Implementation.Module
{
public class CoreModule : IGeneralModule
{
public void LoadModules(IServiceCollection collection, string projectNamespace)
public void RegisterServices(IServiceCollection collection, string projectNamespace)
{
var tokenSource = new CancellationTokenSource();
var mainFolder = Path.Join("joshika39", projectNamespace);
var userFolder = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), mainFolder);
collection.AddScoped<ILogger, Logger.Logger>(_ => new Logger.Logger(Guid.NewGuid()));
Expand All @@ -30,9 +36,14 @@ public void LoadModules(IServiceCollection collection, string projectNamespace)
collection.AddScoped<IReader, Reader>();
collection.AddScoped<IDataParser, DefaultDataParser>();
collection.AddTransient<IRepositoryFactory, RepositoryFactory>();
collection.AddTransient<IApplicationSettings, GeneralApplicationSettings>(provider =>
new GeneralApplicationSettings(userFolder, provider.GetRequiredService<IConfigurationQueryFactory>())
);

collection.AddScoped<ILifeCycleManager>(_ => new LifeCycleManager(tokenSource));
collection.AddSingleton<IStopWatchFactory, StopwatchFactory>();
collection.AddScoped<IStopwatch>(_ => new DefaultStopwatch(tokenSource.Token));

collection.AddTransient<IApplicationSettings, GeneralApplicationSettings>(provider =>
new GeneralApplicationSettings(userFolder, provider.GetRequiredService<IConfigurationQueryFactory>())
);
}
}
}
67 changes: 29 additions & 38 deletions _src/Implementation/Repositories/AJsonRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,94 +3,86 @@
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Implementation.Converters;
using Infrastructure.Application;
using Infrastructure.Repositories;
using Newtonsoft.Json;

namespace Implementation.Repositories
{
public abstract class AJsonRepository<TInterface, TClass> : IRepository<TInterface>
where TInterface : class, IEntity
where TClass : class, TInterface
/// <summary>
/// Abstract Json implementation of the <see cref="IRepository{T}"/>.
/// </summary>
/// <typeparam name="TClass"></typeparam>
public abstract class AJsonRepository<TClass> : IRepository<TClass> where TClass : class, IEntity
{
private readonly string _dataPath;
private readonly string _filePath;
private readonly IList<TInterface> _updatedEntities;
private readonly IList<TInterface> _addedEntities;
private readonly IList<TClass> _updatedEntities;
private readonly IList<TClass> _addedEntities;
private readonly IList<Guid> _removedEntities;
private bool _isLocked;
private readonly JsonSerializerSettings _settings;

protected AJsonRepository(IApplicationSettings applicationSettings, string repositoryKey)
{
applicationSettings = applicationSettings ?? throw new ArgumentNullException(nameof(applicationSettings));
repositoryKey = repositoryKey ?? throw new ArgumentNullException(nameof(repositoryKey));

_updatedEntities = new List<TInterface>();
_addedEntities = new List<TInterface>();
_updatedEntities = new List<TClass>();
_addedEntities = new List<TClass>();
_removedEntities = new List<Guid>();
_dataPath = applicationSettings.RepositoryPath!;
_filePath = Path.Join(_dataPath, $"{repositoryKey}.json");
_settings = new JsonSerializerSettings()
{
Converters = new List<JsonConverter>
{
new GenericJsonConverter<TInterface, TClass>()
}
};
}

public async Task<IEnumerable<TInterface>> GetAllEntitiesAsync()
public async Task<IEnumerable<TClass>> GetAllEntitiesAsync()
{
return await GetAllContentAsync();
}
public IEnumerable<TInterface> GetAllEntities()
public IEnumerable<TClass> GetAllEntities()
{
return GetAllContent();
}
public async Task<TInterface?> GetEntityAsync(Guid id)
public async Task<TClass?> GetEntityAsync(Guid id)
{
var allContent = await GetAllContentAsync();
return allContent.FirstOrDefault(e => e.Id.Equals(id));

}

public TInterface? GetEntity(Guid id)
public TClass? GetEntity(Guid id)
{
var allContent = GetAllContent();
return allContent.FirstOrDefault(e => e.Id.Equals(id));
}
public IRepository<TInterface> Create(TInterface entity)
public IRepository<TClass> Create(TClass entity)
{
_addedEntities.Add(entity);
return this;
}
public IRepository<TInterface> Delete(Guid id)
public IRepository<TClass> Delete(Guid id)
{
_removedEntities.Add(id);
return this;
}
public IRepository<TInterface> Update(TInterface entity)
public IRepository<TClass> Update(TClass entity)
{
_updatedEntities.Add(entity);
return this;
}

public IRepository<TInterface> SaveChanges()
public void SaveChanges()
{
if (_isLocked)
{
return this;
return;
}

CreateRepository();
_isLocked = true;

var newContent = JsonConvert.SerializeObject(PerformSave(GetAllContent().ToList()), _settings);
var newContent = JsonConvert.SerializeObject(PerformSave(GetAllContent().ToList()));
File.WriteAllText(_filePath, newContent);
_isLocked = false;
return this;
}

private async Task CreateRepositoryAsync()
Expand Down Expand Up @@ -121,38 +113,37 @@ private void CreateRepository()
}
}

private async Task<IEnumerable<TInterface>> GetAllContentAsync()
private async Task<IEnumerable<TClass>> GetAllContentAsync()
{
await SaveChangesAsync();
var allContent = await File.ReadAllTextAsync(_filePath);
var list = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<IEnumerable<TInterface>>(allContent, _settings));
return list ?? new List<TInterface>();
var list = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<IEnumerable<TClass>>(allContent));
return list ?? new List<TClass>();
}

private IEnumerable<TInterface> GetAllContent()
private IEnumerable<TClass> GetAllContent()
{
SaveChanges();
var allContent = File.ReadAllText(_filePath);
var list = JsonConvert.DeserializeObject<IEnumerable<TInterface>>(allContent, _settings);
return list ?? new List<TInterface>();
var list = JsonConvert.DeserializeObject<IEnumerable<TClass>>(allContent);
return list ?? new List<TClass>();
}

public async Task<IRepository<TInterface>> SaveChangesAsync()
public async Task SaveChangesAsync()
{
if (_isLocked)
{
return this;
return;
}
await CreateRepositoryAsync();
_isLocked = true;
var currentContent = PerformSave((await GetAllContentAsync()).ToList());
var newContent = await Task.Factory.StartNew(() => JsonConvert.SerializeObject(currentContent, _settings));
var newContent = await Task.Factory.StartNew(() => JsonConvert.SerializeObject(currentContent));
await File.WriteAllTextAsync(_filePath, newContent);
_isLocked = false;
return await Task.FromResult<IRepository<TInterface>>(this);
}

private ICollection<TInterface> PerformSave(ICollection<TInterface> currentContent)
private ICollection<TClass> PerformSave(ICollection<TClass> currentContent)
{
for (var index = 0; index < _addedEntities.Count; index++)
{
Expand Down
4 changes: 1 addition & 3 deletions _src/Implementation/Repositories/DefaultJsonRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@

namespace Implementation.Repositories
{
internal class DefaultJsonRepository<TInterface, TClass> : AJsonRepository<TInterface, TClass>
where TInterface: class, IEntity
where TClass: class, TInterface
internal class DefaultJsonRepository<T> : AJsonRepository<T> where T: class, IEntity
{
public DefaultJsonRepository(IApplicationSettings applicationSettings, string repositoryKey) : base(applicationSettings, repositoryKey)
{ }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,9 @@ public RepositoryFactory(IApplicationSettings applicationSettings)
_applicationSettings = applicationSettings ?? throw new ArgumentNullException(nameof(applicationSettings));
}

public IRepository<TInterface> CreateJsonRepository<TInterface, T>(string repositoryName)
where TInterface : class, IEntity
where T : class, TInterface
public IRepository<T> CreateRepository<T>(string repositoryName) where T : class, IEntity
{
return new DefaultJsonRepository<TInterface, T>(_applicationSettings, repositoryName);
return new DefaultJsonRepository<T>(_applicationSettings, repositoryName);
}
}
}
Loading

0 comments on commit acd6393

Please sign in to comment.