-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDistributedXmlRepository.cs
More file actions
66 lines (59 loc) · 1.78 KB
/
DistributedXmlRepository.cs
File metadata and controls
66 lines (59 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using Microsoft.Extensions.Caching.Distributed;
namespace net.vieapps.Components.Utility
{
/// <summary>
/// Distributed XML repository for working with data-protection
/// </summary>
public class DistributedXmlRepository : Microsoft.AspNetCore.DataProtection.Repositories.IXmlRepository
{
readonly IDistributedCache _cache;
readonly DistributedXmlRepositoryOptions _options;
public DistributedXmlRepository(IDistributedCache cache, DistributedXmlRepositoryOptions options)
{
this._cache = cache;
this._options = options;
}
protected XDocument GetXDocument()
{
try
{
var xml = this._cache.GetString(this._options.Key);
return string.IsNullOrWhiteSpace(xml) ? new XDocument() : XDocument.Parse(xml);
}
catch
{
return new XDocument();
}
}
public IReadOnlyCollection<XElement> GetAllElements()
=> this.GetXDocument().Elements().ToList().AsReadOnly();
public void StoreElement(XElement element, string friendlyName)
{
XDocument document;
try
{
document = this.GetXDocument();
document.Add(element);
}
catch
{
this._cache.Remove(this._options.Key);
document = new XDocument();
document.Add(element);
}
this._cache.SetString(this._options.Key, document.ToString(SaveOptions.DisableFormatting), this._options.CacheOptions);
}
}
/// <summary>
/// Distributed XML repository options for working with data-protection
/// </summary>
public class DistributedXmlRepositoryOptions
{
public DistributedCacheEntryOptions CacheOptions { get; set; } = new DistributedCacheEntryOptions { AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddDays(2)) };
public string Key { get; set; } = "DataProtection-Keys";
}
}