-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathMSSQLSerializer.cs
183 lines (145 loc) · 7.44 KB
/
MSSQLSerializer.cs
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
using System;
using System.Data;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
{
public class MssqlSerializer : IStateMachine
{
/// <summary>
/// Will initialize the state machine.
/// </summary>
/// <param name="file">Path of the file and name where to save the session details.</param>
/// <param name="fallbackStateForm">
/// Type of Form which will be saved instead of Form which has
/// <seealso cref="Attributes.IgnoreState" /> attribute declared. Needs to be subclass of
/// <seealso cref="Form.FormBase" />.
/// </param>
/// <param name="overwrite">Declares of the file could be overwritten.</param>
public MssqlSerializer(string connectionString, string tablePrefix = "tgb_", Type fallbackStateForm = null)
{
ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
TablePrefix = tablePrefix;
FallbackStateForm = fallbackStateForm;
if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase)))
{
throw new ArgumentException($"{nameof(FallbackStateForm)} is not a subclass of {nameof(FormBase)}");
}
}
public string ConnectionString { get; }
public string TablePrefix { get; set; }
public Type FallbackStateForm { get; set; }
public StateContainer LoadFormStates()
{
var sc = new StateContainer();
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "SELECT deviceId, deviceTitle, FormUri, QualifiedName FROM " + TablePrefix +
"devices_sessions";
var dataTable = new DataTable();
using (var dataAdapter = new SqlDataAdapter(command))
{
dataAdapter.Fill(dataTable);
foreach (DataRow r in dataTable.Rows)
{
var se = new StateEntry
{
DeviceId = (long)r["deviceId"],
ChatTitle = r["deviceTitle"].ToString(),
FormUri = r["FormUri"].ToString(),
QualifiedName = r["QualifiedName"].ToString()
};
sc.States.Add(se);
if (se.DeviceId > 0)
{
sc.ChatIds.Add(se.DeviceId);
}
else
{
sc.GroupIds.Add(se.DeviceId);
}
var command2 = connection.CreateCommand();
command2.CommandText = "SELECT [key], value, type FROM " + TablePrefix +
"devices_sessions_data WHERE deviceId = @deviceId";
command2.Parameters.Add(new SqlParameter("@deviceId", r["deviceId"]));
var dataTable2 = new DataTable();
using (var dataAdapter2 = new SqlDataAdapter(command2))
{
dataAdapter2.Fill(dataTable2);
foreach (DataRow r2 in dataTable2.Rows)
{
var key = r2["key"].ToString();
var type = Type.GetType(r2["type"].ToString());
var value = JsonConvert.DeserializeObject(r2["value"].ToString(), type);
se.Values.Add(key, value);
}
}
}
}
connection.Close();
}
return sc;
}
public void SaveFormStates(SaveStatesEventArgs e)
{
var container = e.States;
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
//Cleanup old Session data
var clearCommand = connection.CreateCommand();
clearCommand.CommandText = $"DELETE FROM {TablePrefix}devices_sessions_data";
clearCommand.ExecuteNonQuery();
clearCommand.CommandText = $"DELETE FROM {TablePrefix}devices_sessions";
clearCommand.ExecuteNonQuery();
//Prepare new session commands
var sessionCommand = connection.CreateCommand();
var dataCommand = connection.CreateCommand();
sessionCommand.CommandText = "INSERT INTO " + TablePrefix +
"devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)";
sessionCommand.Parameters.Add(new SqlParameter("@deviceId", ""));
sessionCommand.Parameters.Add(new SqlParameter("@deviceTitle", ""));
sessionCommand.Parameters.Add(new SqlParameter("@FormUri", ""));
sessionCommand.Parameters.Add(new SqlParameter("@QualifiedName", ""));
dataCommand.CommandText = "INSERT INTO " + TablePrefix +
"devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)";
dataCommand.Parameters.Add(new SqlParameter("@deviceId", ""));
dataCommand.Parameters.Add(new SqlParameter("@key", ""));
dataCommand.Parameters.Add(new SqlParameter("@value", ""));
dataCommand.Parameters.Add(new SqlParameter("@type", ""));
//Store session data in database
foreach (var state in container.States)
{
sessionCommand.Parameters["@deviceId"].Value = state.DeviceId;
sessionCommand.Parameters["@deviceTitle"].Value = state.ChatTitle ?? "";
sessionCommand.Parameters["@FormUri"].Value = state.FormUri;
sessionCommand.Parameters["@QualifiedName"].Value = state.QualifiedName;
sessionCommand.ExecuteNonQuery();
foreach (var data in state.Values)
{
dataCommand.Parameters["@deviceId"].Value = state.DeviceId;
dataCommand.Parameters["@key"].Value = data.Key;
var type = data.Value.GetType();
if (type.IsPrimitive || type.Equals(typeof(string)))
{
dataCommand.Parameters["@value"].Value = data.Value;
}
else
{
dataCommand.Parameters["@value"].Value = JsonConvert.SerializeObject(data.Value);
}
dataCommand.Parameters["@type"].Value = type.AssemblyQualifiedName;
dataCommand.ExecuteNonQuery();
}
}
connection.Close();
}
}
}
}