Repository navigation
Expand file tree
/
Copy pathLogItem.cs
More file actions
55 lines (48 loc) · 2.07 KB
/
Copy pathLogItem.cs
File metadata and controls
55 lines (48 loc) · 2.07 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
using Common;
using Newtonsoft.Json;
namespace ProblemSource.Models
{
public class LogItem
{
public string className { get; set; } = "";
public long time { get; set; }
public string type { get; set; } = "";
public static string? GetEventClassName(object item)
{
// what the hell? Suddenly the deserialized items are JsonElement instead of dynamic object
if (item is System.Text.Json.JsonElement jEl)
return jEl.GetProperty("className").GetString();
else
return ExceptionTools.TryOrDefault(() => (string)((dynamic)item).className, null);
}
private static Dictionary<string, Type>? nameToType;
public static (LogItem? parsed, Exception? error) TryDeserialize(object item)
{
if (nameToType == null)
{
nameToType = typeof(LogItem).Assembly.GetTypes().Where(o => typeof(LogItem).IsAssignableFrom(o)).ToDictionary(o => o.Name, o => o);
}
// TODO: custom serializer
var className = GetEventClassName(item);
if (className == null)
return (null, new Exception("Couldn't get className"));
if (!nameToType.TryGetValue(className, out var type))
return (null, new Exception($"Non-existing type: '{className}'"));
try
{
var asJson = item is System.Text.Json.JsonElement jEl ? jEl.ToString() : JsonConvert.SerializeObject(item);
var typed = JsonConvert.DeserializeObject(asJson!, type);
if (typed == null)
return (null, new Exception($"Could not deserialize"));
if (typed is not LogItem li)
return (null, new Exception($"Not a {nameof(LogItem)}: '{typed.GetType().Name}'"));
return (li, null);
}
catch (Exception ex)
{
//unhandledItems.Add(new { Exception = ex, Item = item });
return (null, ex);
}
}
}
}