2022-07-17 10:56:06 +00:00
|
|
|
|
using DataModel.Database;
|
2022-07-16 20:40:06 +00:00
|
|
|
|
using DataModel.Database.Common;
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
|
|
|
|
|
namespace Processor;
|
|
|
|
|
|
|
|
|
|
public static class TextElementProcessor
|
|
|
|
|
{
|
|
|
|
|
public static Task<IAsyncEnumerable<TextElement>> GetTextElements(DataContext db, Section section)
|
|
|
|
|
{
|
|
|
|
|
return Task.FromResult(db.TextElements.Where(n => n.Section == section).AsAsyncEnumerable());
|
|
|
|
|
}
|
2022-07-17 10:56:06 +00:00
|
|
|
|
|
|
|
|
|
public static async Task<ProcessorResult<TextElement>> AddTextElement(DataContext db, string? currentSectionKey, string elementName)
|
|
|
|
|
{
|
|
|
|
|
if(string.IsNullOrWhiteSpace(currentSectionKey))
|
|
|
|
|
throw new ArgumentOutOfRangeException(nameof(currentSectionKey));
|
|
|
|
|
|
|
|
|
|
var currentSection = await db.Sections.FirstOrDefaultAsync(n => n.DataKey == currentSectionKey);
|
|
|
|
|
if (currentSection is null)
|
|
|
|
|
throw new ArgumentOutOfRangeException(nameof(currentSectionKey));
|
|
|
|
|
|
|
|
|
|
// Remove any whitespaces from the element name, regardless of how many e.g. spaces the user typed:
|
|
|
|
|
var code = string.Join('_', elementName.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)).ToUpperInvariant();
|
|
|
|
|
|
|
|
|
|
// Check, if this key already exists:
|
|
|
|
|
if (await db.TextElements.AnyAsync(n => n.Section == currentSection && n.Code == code))
|
|
|
|
|
{
|
|
|
|
|
var rng = new Random();
|
|
|
|
|
while (await db.TextElements.AnyAsync(n => n.Section == currentSection && n.Code == code))
|
|
|
|
|
{
|
|
|
|
|
// Add a random number to the end of the key:
|
|
|
|
|
code += $"_{rng.Next(1, 10_000)}";
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var textElement = new TextElement
|
|
|
|
|
{
|
|
|
|
|
Name = elementName,
|
|
|
|
|
Code = code,
|
|
|
|
|
Section = currentSection,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Add the new element to the database:
|
|
|
|
|
await db.TextElements.AddAsync(textElement);
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
// Save the changes:
|
|
|
|
|
await db.SaveChangesAsync();
|
|
|
|
|
return new ProcessorResult<TextElement>(textElement);
|
|
|
|
|
}
|
|
|
|
|
catch (DbUpdateException updateException)
|
|
|
|
|
{
|
|
|
|
|
return updateException.ToProcessorResult<TextElement>();
|
|
|
|
|
}
|
|
|
|
|
}
|
2022-07-16 20:40:06 +00:00
|
|
|
|
}
|