111 lines
3.5 KiB
C#
111 lines
3.5 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Xml.Serialization;
|
|
|
|
namespace CadParamPluging.Common
|
|
{
|
|
public static class TemplateSchemaStore
|
|
{
|
|
private const string FolderName = "CadParamPluging";
|
|
private const string FileName = "template-schemas.xml";
|
|
|
|
public static string GetFilePath()
|
|
{
|
|
var dir = Path.Combine(
|
|
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
|
FolderName);
|
|
return Path.Combine(dir, FileName);
|
|
}
|
|
|
|
public static TemplateSchemas Load()
|
|
{
|
|
try
|
|
{
|
|
var defaults = TemplateSchemaDefaults.CreateDefault();
|
|
defaults.Normalize();
|
|
|
|
var path = GetFilePath();
|
|
if (!File.Exists(path))
|
|
{
|
|
return defaults;
|
|
}
|
|
|
|
using (var stream = File.OpenRead(path))
|
|
{
|
|
var serializer = new XmlSerializer(typeof(TemplateSchemas));
|
|
var obj = serializer.Deserialize(stream) as TemplateSchemas;
|
|
if (obj == null)
|
|
{
|
|
return defaults;
|
|
}
|
|
|
|
obj.Normalize();
|
|
|
|
// Merge: keep local modifications, but add any missing built-in defaults.
|
|
foreach (var def in defaults.Items ?? Enumerable.Empty<TemplateSchemaDefinition>())
|
|
{
|
|
if (def == null || string.IsNullOrWhiteSpace(def.TemplateKey))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var exists = (obj.Items ?? Enumerable.Empty<TemplateSchemaDefinition>())
|
|
.Any(x => x != null && string.Equals(x.TemplateKey, def.TemplateKey, StringComparison.OrdinalIgnoreCase));
|
|
if (!exists)
|
|
{
|
|
obj.Items.Add(def);
|
|
}
|
|
}
|
|
|
|
obj.Normalize();
|
|
if (obj.Items != null)
|
|
{
|
|
obj.Items = obj.Items
|
|
.Where(x => x != null && !string.IsNullOrWhiteSpace(x.TemplateKey))
|
|
.GroupBy(x => x.TemplateKey, StringComparer.OrdinalIgnoreCase)
|
|
.Select(g => g.First())
|
|
.ToList();
|
|
}
|
|
return obj;
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return TemplateSchemaDefaults.CreateDefault();
|
|
}
|
|
}
|
|
|
|
public static void Save(TemplateSchemas schemas)
|
|
{
|
|
if (schemas == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(schemas));
|
|
}
|
|
|
|
schemas.Normalize();
|
|
|
|
var path = GetFilePath();
|
|
var dir = Path.GetDirectoryName(path);
|
|
if (!string.IsNullOrEmpty(dir))
|
|
{
|
|
Directory.CreateDirectory(dir);
|
|
}
|
|
|
|
var tempPath = path + ".tmp";
|
|
var serializer = new XmlSerializer(typeof(TemplateSchemas));
|
|
using (var stream = File.Create(tempPath))
|
|
{
|
|
serializer.Serialize(stream, schemas);
|
|
}
|
|
|
|
if (File.Exists(path))
|
|
{
|
|
File.Delete(path);
|
|
}
|
|
|
|
File.Move(tempPath, path);
|
|
}
|
|
}
|
|
}
|