Repository navigation
Expand file tree
/
Copy pathContextStorageInFile.cs
More file actions
65 lines (57 loc) · 2.19 KB
/
Copy pathContextStorageInFile.cs
File metadata and controls
65 lines (57 loc) · 2.19 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
using BotSharp.Platform.Abstractions;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace BotSharp.Core.ContextStorage
{
public class ContextStorageInFile<T> : IContextStorage<T>
{
private static string storageDir;
public ContextStorageInFile()
{
IConfiguration config = (IConfiguration)AppDomain.CurrentDomain.GetData("Configuration");
var db = config.GetSection("Database:Default").Value;
storageDir = config.GetSection($"Database:ConnectionStrings:{db}").Value;
string contentDir = AppDomain.CurrentDomain.GetData("DataPath").ToString();
storageDir = storageDir.Replace("|DataDirectory|", contentDir + Path.DirectorySeparatorChar + "SessionStorage" + Path.DirectorySeparatorChar);
if (!Directory.Exists(storageDir))
{
Directory.CreateDirectory(storageDir);
}
}
public async Task<T[]> Fetch(string sessionId)
{
string dataPath = Path.Combine(storageDir, sessionId + ".json");
if (File.Exists(dataPath))
{
string json = File.ReadAllText(dataPath);
return JsonConvert.DeserializeObject<T[]>(json);
}
else
{
return new T[0];
}
}
public async Task<bool> Persist(string sessionId, T[] context)
{
var json = JsonConvert.SerializeObject(context, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter>
{
new Newtonsoft.Json.Converters.StringEnumConverter()
}
});
string dataPath = Path.Combine(storageDir, sessionId + ".json");
File.WriteAllText(dataPath, json);
return true;
}
}
}