-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLUtility.cs
More file actions
415 lines (383 loc) · 13 KB
/
SQLUtility.cs
File metadata and controls
415 lines (383 loc) · 13 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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CPUFramework;
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 SqlConnectionStringBuilder();
b.ConnectionString = ConnectionString;
b.UserID = userid;
b.Password = password;
b.Encrypt = true;
b.TrustServerCertificate = true;
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);
foreach (SqlParameter p in cmd.Parameters)
{
if (p.Direction == ParameterDirection.InputOutput)
{
string colname = p.ParameterName.Substring(1);
if (row.Table.Columns.Contains(colname))
{
//5-27-2025
//JF: I added this in since the PK column was coming in as ReadOnly and therefore preventing the 'set'
//I overwrote it here, but should be looked into more if this is due to the new SQL package or something else.
//I did not review all the code so it may be due to something simple elsewhere, but I wanted her to be able to continue
if (row.Table.Columns[colname].ReadOnly)
{
row.Table.Columns[colname].ReadOnly = false;
}
row[colname] = p.Value;
}
}
}
if (acceptchanges == true)
{
row.Table.AcceptChanges();
}
}
private static DataTable DoExecuteSQL(SqlCommand cmd, bool loadtable)
{
DataTable dt = new();
using (SqlConnection conn = new SqlConnection(SQLUtility.ConnectionString))
{
conn.Open();
cmd.Connection = conn;
Debug.Print(GetSQL(cmd));
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);
}
}
SetAllColumnProperties(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) //- take a SQL statement and return a DataTable
{
return DoExecuteSQL(new SqlCommand(sqlstatement), true);
}
public static void ExecuteSQL(string sqlstatement)
{
GetDataTable(sqlstatement);
}
public static void ExecuteSQL(SqlCommand cmd)
{
DoExecuteSQL(cmd, false);
}
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, ex);
}
}
private static string ParseConstraintMsg(string msg)
{
string origmsg = msg;
string prefix = "ck_";
string msgend = "";
string notnullprefix = "Cannot insert the value NULL into column '";
if (msg.Contains(prefix) == false)
{
if (msg.Contains("u_"))
{
prefix = "u_";
msgend = " 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;
}
public static string GetFirstColumnFirstRowValueString(string sql)
{
string n = "";
DataTable dt = GetDataTable(sql);
if (dt.Rows.Count > 0 && dt.Columns.Count > 0)
{
if (dt.Rows[0][0] != DBNull.Value)
{
n = dt.Rows[0][0].ToString();
}
}
return n;
}
public static DateTime GetFirstColumnFirstRowValueDate(string sql)
{
DateTime n = DateTime.Now;
DataTable dt = GetDataTable(sql);
if (dt.Rows.Count > 0 && dt.Columns.Count > 0)
{
if (dt.Rows[0][0] != DBNull.Value)
{
DateTime.TryParse(dt.Rows[0][0].ToString(), out n);
}
}
return n;
}
public static int GetFirstColumnFirstRowValueInt(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 SetAllColumnProperties(DataTable dt1)
{
foreach (DataColumn c in dt1.Columns)
{
c.AllowDBNull = true;
c.AutoIncrement = false;
c.ReadOnly = 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 DateTime GetValueFromFirstRowAsDate(DataTable dt, string columnname)
{
DateTime value = new();
if (dt.Rows.Count > 0)
{
DataRow r = dt.Rows[0];
if (r[columnname] != null && r[columnname] is DateTime)
{
value = (DateTime)r[columnname];
}
}
return value;
}
public static bool TableHasChanges(DataTable dt)
{
bool b = false;
if (dt.GetChanges() != null)
{
b = true;
}
return b;
}
public static string GetSQL(SqlCommand cmd)
{
string val = "";
#if DEBUG
StringBuilder sb = new StringBuilder();
if (cmd.Connection != null)
{
sb.AppendLine($"--{cmd.Connection.DataSource}");
sb.AppendLine($"use {cmd.Connection.Database}");
sb.AppendLine("go");
}
if (cmd.CommandType == CommandType.StoredProcedure)
{
sb.AppendLine($"exec {cmd.CommandText}");
int paramcount = cmd.Parameters.Count - 1;
int paramnum = 0;
string comma = ",";
foreach (SqlParameter p in cmd.Parameters)
{
if (p.Direction != ParameterDirection.ReturnValue)
{
if (paramnum == paramcount)
{
comma = "";
}
sb.AppendLine($"{p.ParameterName} = {(p.Value == null ? "null" : p.Value.ToString())}{comma}");
}
paramnum++;
}
}
else
{
sb.AppendLine(cmd.CommandText);
}
val = sb.ToString();
#endif
return val;
}
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());
}
}
}
}
}
//