kreta/Framework/Caching/StringResourcesCache.cs
2024-03-13 00:33:46 +01:00

80 lines
2.5 KiB
C#

using System;
using System.Collections.Concurrent;
using System.IO;
using System.Xml.Linq;
namespace Kreta.Framework.Caching
{
public sealed class StringResourcesCache : Cache
{
private const int DefaultLcid = 1038; // magyar
private const string StringResourcesFileName = "StringResources.kres";
private ConcurrentDictionary<string, string> cache;
public StringResourcesCache(CacheManager cacheManager) : base(cacheManager)
{
cache = new ConcurrentDictionary<string, string>();
LoadCache();
}
private string GetStringResourcesKey(int id, int lcid)
{
return $"{id}¤{lcid}";
}
private void LoadCache()
{
string[] stringResourcesFilePath = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, StringResourcesFileName, SearchOption.AllDirectories);
if (stringResourcesFilePath.Length == 0)
{
throw new Exception($"Not found {StringResourcesFileName} file!");
}
var root = XElement.Load(stringResourcesFilePath[0]);
foreach (XElement text in root.Elements())
{
foreach (XElement language in text.Elements())
{
string stringResourcesKey = GetStringResourcesKey(Convert.ToInt32(text.Attribute("ID").Value), Convert.ToInt32(language.Attribute("LCID").Value));
string value = language.Value.Replace("\n", "<br/>");
cache.AddOrUpdate(stringResourcesKey, key => value, (k, v) => value);
}
}
}
private static string GetDefaultText(int id, int lcid)
{
return $"Nincs fordítása -> ID:{id} - LCID:{lcid}!";
}
public string Get(int id, int lcid)
{
return Get(id, lcid, GetDefaultText(id, lcid));
}
public string Get(int id, int lcid, string defaultText)
{
var result = cache.GetOrAdd(GetStringResourcesKey(id, lcid), key => GetDefaultText(id, lcid));
if (result == null && lcid != DefaultLcid)
{
result = cache.GetOrAdd(GetStringResourcesKey(id, DefaultLcid), key => GetDefaultText(id, DefaultLcid));
}
if (result == null)
{
result = defaultText;
}
return result;
}
public override void Reset()
{
cache.Clear();
}
}
}