-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLUtility.cs
More file actions
341 lines (309 loc) · 10.6 KB
/
SQLUtility.cs
File metadata and controls
341 lines (309 loc) · 10.6 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
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Xml.Schema;
namespace CPUFramework
{
public class SQLUtility
{
private static string ConnectionString = "";
public static void SetConnectionString(string connstring, bool tryopen, string userid = "", string password = "")
{
ConnectionString = connstring;
if(userid != "")
{
SqlConnectionStringBuilder b = new();
b.ConnectionString = ConnectionString;
b.UserID = userid;
b.Password = password;
ConnectionString = b.ConnectionString;
}
if (tryopen)
{
using(SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
}
}
}
public static SqlCommand GetSQLCommand(string sprocname)
{
SqlCommand cmd;
using (SqlConnection conn = new SqlConnection(SQLUtility.ConnectionString))
{
cmd = new SqlCommand(sprocname, conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlCommandBuilder.DeriveParameters(cmd);
}
return cmd;
}
public static DataTable GetDataTable(SqlCommand cmd)
{
return DoExecuteSQL(cmd, true);
}
public static void SaveDataTable(DataTable dt, string sprocname)
{
var rows = dt.Select("", "", DataViewRowState.Added | DataViewRowState.ModifiedCurrent);
foreach(DataRow r in rows)
{
SaveDataRow(r, sprocname, false);
}
dt.AcceptChanges();
}
public static void SaveDataRow(DataRow row, string sprocname, bool acceptchanges = true)
{
SqlCommand cmd = GetSQLCommand(sprocname);
foreach(DataColumn col in row.Table.Columns)
{
string paramname = $"@{col.ColumnName}";
if (cmd.Parameters.Contains(paramname))
{
cmd.Parameters[paramname].Value = row[col.ColumnName];
}
}
DoExecuteSQL(cmd, false);
row.Table.AcceptChanges();
foreach(SqlParameter p in cmd.Parameters)
{
string colname = p.ParameterName.Substring(1);
if (row.Table.Columns.Contains(colname))
{
row[colname] = p.Value;
row.Table.AcceptChanges();
}
}
if (acceptchanges == true)
{
row.Table.AcceptChanges();
}
}
public static void SaveChildTable(DataTable dt, int parentid, string parentcolumnname, string sprocname)
{
foreach (DataRow r in dt.Select("", "", DataViewRowState.Added))
{
r[parentcolumnname] = parentid;
}
SaveDataTable(dt, sprocname);
}
public static void DeleteChildTable(int childtableid, string sprocname, string childtableparamname)
{
SqlCommand cmd = GetSQLCommand(sprocname);
cmd.Parameters[childtableparamname].Value = childtableid;
SQLUtility.ExecuteSQL(cmd);
}
private static DataTable DoExecuteSQL(SqlCommand cmd, bool loadtable)
{
Debug.Print("-----" +Environment.NewLine + cmd.CommandText);
DataTable dt = new();
using(SqlConnection conn = new SqlConnection(SQLUtility.ConnectionString))
{
conn.Open();
cmd.Connection = conn;
try
{
SqlDataReader dr = cmd.ExecuteReader();
CheckReturnValue(cmd);
if (loadtable == true)
{
dt.Load(dr);
}
}
catch(SqlException ex)
{
string msg = ParseConstraintMsg(ex.Message);
throw new Exception(msg);
}
catch(InvalidCastException ex)
{
throw new Exception(cmd.CommandText + ": " + ex.Message, ex);
}
}
SetAllColumnsProperties(dt);
return dt;
}
private static void CheckReturnValue(SqlCommand cmd)
{
int returnvalue = 0;
string msg = "";
if (cmd.CommandType == CommandType.StoredProcedure)
{
foreach (SqlParameter p in cmd.Parameters)
{
if (p.Direction == ParameterDirection.ReturnValue)
{
if (p.Value != null)
{
returnvalue = (int)p.Value;
}
}
else if (p.ParameterName.ToLower() == "@message")
{
if (p.Value != null)
{
msg = p.Value.ToString();
}
}
}
if (returnvalue == 1)
{
if (msg == "")
{
msg = $"{cmd.CommandText} did not do action that was requested";
}
throw new Exception(msg);
}
}
}
public static DataTable GetDataTable(string sqlstatement)
{
return DoExecuteSQL(new SqlCommand(sqlstatement), true);
}
public static void ExecuteSQL(SqlCommand cmd)
{
DoExecuteSQL(cmd, false);
}
public static void ExecuteSQL(string sqlstatement)
{
GetDataTable(sqlstatement);
}
public static void SetParamValue(SqlCommand cmd, string paramname, object value)
{
if(paramname.StartsWith("@") == false) { paramname = "@" + paramname; }
try
{
cmd.Parameters[paramname].Value = value;
}
catch(Exception ex)
{
throw new Exception(cmd.CommandText + ": " + ex.Message);
}
}
public static string ParseConstraintMsg(string msg)
{
//PartyId', table 'RecordKeeperDB.dbo.President'; column does not allow nulls. INSERT fails.
string origmsg = msg;
string prefix = "ck_";
string msgend = "";
string notnullprefix = "Cannot insert the value NULL into column '";
string msgstart = GetColumnFromConstraintName(msg);
if (msg.Contains(prefix) == false)
{
if (msg.Contains("u_"))
{
prefix = "u_";
msg = msgstart + " must be unique.";
}
else if (msg.Contains("f_"))
{
prefix = "f_";
}
else if (msg.Contains(notnullprefix))
{
prefix = notnullprefix;
msgend = " cannot be blank.";
}
}
if (msg.Contains(prefix))
{
msg = msg.Replace("\"", "'");
int pos = msg.IndexOf(prefix) + prefix.Length;
msg = msg.Substring(pos);
pos = msg.IndexOf("'");
if (pos == -1)
{
msg = origmsg;
}
else
{
msg = msg.Substring(0, pos);
msg = msg.Replace("_", " ");
msg = msg + msgend;
if(prefix == "f_")
{
var words = msg.Split(" ");
if(words.Length > 1)
{
msg = $"Cannot delete {words[0]} because it has a related {words[1]} record.";
}
}
}
}
return msg;
}
private static string GetColumnFromConstraintName(string constraintmsg)
{
int start = constraintmsg.IndexOf('\'');
int end = constraintmsg.IndexOf('\'', start + 1);
string constraintname = constraintmsg.Substring(start + 1, end - start - 1);
return constraintname.Split('_').Last();
}
public static int GetFirstColumnFirstRowValue(string sql)
{
int n = 0;
DataTable dt = GetDataTable(sql);
if(dt.Rows.Count > 0 && dt.Columns.Count > 0)
{
if (dt.Rows[0][0] != DBNull.Value)
{
int.TryParse(dt.Rows[0][0].ToString(), out n);
}
}
return n;
}
private static void SetAllColumnsProperties(DataTable dt)
{
foreach (DataColumn c in dt.Columns)
{
c.AllowDBNull = true;
c.AutoIncrement = false;
}
}
public static int GetValueFromFirstRowAsInt(DataTable dt, string columnname)
{
int value = 0;
if(dt.Rows.Count > 0)
{
DataRow r = dt.Rows[0];
if (r[columnname] != null && r[columnname] is int)
{
value = (int)r[columnname];
}
}
return value;
}
public static string GetValueFromFirstRowAsString(DataTable dt, string columnname)
{
string value = "";
if (dt.Rows.Count > 0)
{
DataRow r = dt.Rows[0];
if (r[columnname] != null && r[columnname] is string)
{
value = (string)r[columnname];
}
}
return value;
}
public static bool TableHasChanges(DataTable dt)
{
bool b = false;
if(dt.GetChanges() != null)
{
b = true;
}
return b;
}
public static void DebugPrintDataTable(DataTable dt)
{
foreach (DataRow r in dt.Rows)
{
foreach (DataColumn c in dt.Columns)
{
Debug.Print(c.ColumnName + " = " + r[c.ColumnName].ToString());
}
}
}
}
}