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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.BL.Entities;
namespace Tango.DataStore.EF
{
public static class EFDataStoreHelper
{
public static byte[] CreateBytes(DataType type, Object obj)
{
switch (type)
{
case DataType.Int32:
return BitConverter.GetBytes((int)obj);
case DataType.Float:
return BitConverter.GetBytes((float)obj);
case DataType.Double:
return BitConverter.GetBytes((double)obj);
case DataType.Boolean:
return BitConverter.GetBytes((bool)obj);
case DataType.String:
return Encoding.Default.GetBytes(obj.ToString());
case DataType.Bytes:
return (byte[])obj;
case DataType.Proto:
if (obj is DataStoreProtoObject protoMessage)
{
return protoMessage.ToBytes();
}
else
{
throw new NotSupportedException($"Data type is 'Proto' but object is not of type '{nameof(DataStoreProtoObject)}'.");
}
}
throw new NotSupportedException("The specified type is not supported.");
}
public static Object CreateObject(DataType type, byte[] bytes)
{
switch (type)
{
case DataType.Int32:
return BitConverter.ToInt32(bytes, 0);
case DataType.Float:
return BitConverter.ToSingle(bytes, 0);
case DataType.Double:
return BitConverter.ToDouble(bytes, 0);
case DataType.Boolean:
return BitConverter.ToBoolean(bytes, 0);
case DataType.String:
return Encoding.Default.GetString(bytes);
case DataType.Bytes:
return bytes;
case DataType.Proto:
return DataStoreProtoObject.FromBytes(bytes);
}
throw new NotSupportedException("The specified type is not supported.");
}
public static IDataStoreItem CreateDataStoreItem(DataStoreItem item)
{
return new EFDataStoreItem()
{
Guid = item.Guid,
Date = item.LastUpdated,
IsSynchronized = item.IsSynchronized,
Key = item.Key,
Type = (DataType)item.DataType,
Value = CreateObject((DataType)item.DataType, item.Value)
};
}
public static IDataStoreItem CreateDataStoreItem(GlobalDataStoreItem item)
{
return new EFDataStoreItem()
{
Guid = item.Guid,
Date = item.LastUpdated,
IsSynchronized = true,
Key = item.Key,
Type = (DataType)item.DataType,
Value = CreateObject((DataType)item.DataType, item.Value)
};
}
public static DataStoreItem CreateDbDataStoreItem(IDataStoreItem item)
{
return new DataStoreItem()
{
Guid = item.Guid,
LastUpdated = item.Date,
IsSynchronized = item.IsSynchronized,
Key = item.Key,
DataType = (int)item.Type,
Value = CreateBytes(item.Type, item.Value)
};
}
}
}
|