-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLHelper.cs
More file actions
532 lines (478 loc) · 23.1 KB
/
SQLHelper.cs
File metadata and controls
532 lines (478 loc) · 23.1 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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//===============================================================================
// This file is based on the Microsoft Data Access Application Block for .NET
// For more information please go to
// http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
//===============================================================================
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Security;
using System.Web.Caching;
using System.Collections.Specialized;
using System.Linq;
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.SqlAzure;
// only include security rules stuff if in 4.0
#if _NET_L_T_4_0
#else
[assembly: SecurityRules(SecurityRuleSet.Level1)]
#endif
namespace MsSqlDBUtility
{
public abstract class SqlHelper
{
static RetryPolicy RetryPolicy;
//Database connection strings
public static readonly string ConnStringMain = ConfigurationManager.ConnectionStrings["MsSqlConnectionString"].ConnectionString;
public static readonly string ConnStringMainCustom = ConfigurationManager.ConnectionStrings["MsSqlConnectionStringCustom"].ConnectionString;
// Hashtable to store cached parameters
private static readonly Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
public SqlHelper()
{
//This means, 3 retries, first error, wait 0.5 secs and the next errors, increment 1 second the waiting
// Incremental RetryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1));
// You can use one of the built-in detection strategies for
//SQL Azure, Windows Azure Storage, Windows Azure Caching, or the Windows Azure Service Bus.
//You can also define detection strategies for any other services that your application uses.
//RetryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(RetryStrategy);
// RetryPolicy = RetryPolicyFactory.GetRetryPolicy<HolSqlTransientErrorDetectionStrategy>("HOL Strategy");
RetryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(3, TimeSpan.FromSeconds(15));
}
public static string PrepareIntListForParameter(List<int> list)
{
string categoryIds = string.Empty;
if (list != null)
foreach (int cat in list)
categoryIds += cat + " ";
return categoryIds;
}
public static SqlParameter GetNullable(string name, object value)
{
if (value == null)
return new SqlParameter(name, DBNull.Value);
else if (value.GetType() == typeof(System.Net.IPAddress))
return new SqlParameter(name, value.ToString());
else if (value.GetType() == typeof(string) && string.IsNullOrEmpty((string)value))
return new SqlParameter(name, DBNull.Value);
else if (value.GetType() == typeof(bool?) && !((bool?)value).HasValue)
return new SqlParameter(name, DBNull.Value);
else
return new SqlParameter(name, value);
}
public static SqlParameter GetNullableSortFieldParameter(string value)
{
return (value != null && value.Length > 1) ? new SqlParameter("@sortByColumn", value) : new SqlParameter("@sortByColumn", DBNull.Value);
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connString">a valid connection string for a SqlConnection</param>
/// <param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="cmdText">the stored procedure name or T-SQL command</param>
/// <param name="cmdParms">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
{
using (var conn = new SqlConnection(connString))
{
using (var cmd = new SqlCommand())
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
int val = cmd.ExecuteNonQueryWithRetry(RetryPolicy);
cmd.Parameters.Clear();
return val;
}
}
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset) against an existing database connection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="conn">an existing database connection</param>
/// <param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="cmdText">the stored procedure name or T-SQL command</param>
/// <param name="cmdParms">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection conn, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
{
using (var cmd = new SqlCommand())
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
int val = cmd.ExecuteNonQueryWithRetry(RetryPolicy);
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="trans">an existing sql transaction</param>
/// <param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="cmdText">the stored procedure name or T-SQL command</param>
/// <param name="cmdParms">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
{
using (var cmd = new SqlCommand())
{
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);
int val = cmd.ExecuteNonQueryWithRetry(RetryPolicy);
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// Execute a SqlCommand that returns a resultset against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connString">an existing database connection</param>
/// <param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="cmdText">the stored procedure name or T-SQL command</param>
/// <param name="cmdParms">an array of SqlParamters used to execute the command</param>
/// <returns>A SqlDataReader containing the results</returns>
public static IDataReader ExecuteReader(string connString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
// we use a try/catch here because if the method throws an exception we want to
// close the connection throw code, because no datareader will exist, hence the
// commandBehaviour.CloseConnection will not work
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
SqlDataReader rdr = cmd.ExecuteReaderWithRetry(CommandBehavior.CloseConnection, RetryPolicy);
cmd.Parameters.Clear();
return rdr;
}
catch
{
conn.Close();
throw;
}
}
/// <summary>
/// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connString">an existing database connection</param>
/// <param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="cmdText">the stored procedure name or T-SQL command</param>
/// <param name="cmdParms">an array of SqlParamters used to execute the command</param>
/// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
public static object ExecuteScalar(string connString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
{
using (var conn = new SqlConnection(connString))
{
using (var cmd = new SqlCommand())
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
object val = cmd.ExecuteScalarWithRetry(RetryPolicy);
cmd.Parameters.Clear();
return val;
}
}
}
/// <summary>
/// Execute a SqlCommand that returns the first column of the first record against an existing database connection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="conn">an existing database connection</param>
/// <param name="cmdType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="cmdText">the stored procedure name or T-SQL command</param>
/// <param name="cmdParms">an array of SqlParamters used to execute the command</param>
/// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
public static object ExecuteScalar(SqlConnection conn, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
{
using (var cmd = new SqlCommand())
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
object val = cmd.ExecuteScalarWithRetry(RetryPolicy);
cmd.Parameters.Clear();
return val;
}
}
public static object ExecuteScalar(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
{
using (var cmd = new SqlCommand())
{
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);
object val = cmd.ExecuteScalarWithRetry(RetryPolicy);
cmd.Parameters.Clear();
return val;
}
}
public static DataSet ExecuteDataset(string connString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
using (var conn = new SqlConnection(connString))
{
using (var cmd = new SqlCommand())
{
PrepareCommand(cmd, conn, null, commandType, commandText, commandParameters);
using (var da = new SqlDataAdapter(cmd))
{
var ds = new DataSet();
da.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
}
}
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">A valid SqlConnection</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (connection == null) throw new ArgumentNullException("connection");
using (var cmd = new SqlCommand())
{
PrepareCommand(cmd, connection, null, commandType, commandText, commandParameters);
using (var da = new SqlDataAdapter(cmd))
{
var ds = new DataSet();
da.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
}
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">A valid SqlTransaction</param>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// Create a command and prepare it for execution
using (var cmd = new SqlCommand())
{
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
using (var da = new SqlDataAdapter(cmd))
{
var ds = new DataSet();
da.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
}
}
/// <summary>
/// add parameter array to the cache
/// </summary>
/// <param name="cacheKey">Key to the parameter cache</param>
/// <param name="cmdParms">an array of SqlParamters to be cached</param>
public static void CacheParameters(string cacheKey, params SqlParameter[] cmdParms)
{
parmCache[cacheKey] = cmdParms;
}
/// <summary>
/// Retrieve cached parameters
/// </summary>
/// <param name="cacheKey">key used to lookup parameters</param>
/// <returns>Cached SqlParamters array</returns>
public static SqlParameter[] GetCachedParameters(string cacheKey)
{
SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
if (cachedParms == null)
return null;
SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
for (int i = 0, j = cachedParms.Length; i < j; i++)
clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
return clonedParms;
}
/// <summary>
/// Prepare a command for execution
/// </summary>
/// <param name="cmd">SqlCommand object</param>
/// <param name="conn">SqlConnection object</param>
/// <param name="trans">SqlTransaction object</param>
/// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
/// <param name="cmdText">Command text, e.g. Select * from Products</param>
/// <param name="cmdParms">SqlParameters to use in the command</param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.OpenWithRetry(RetryPolicy);
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = cmdType;
if (cmdParms != null) {
cmd.Parameters.Clear();
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
public static void RunScript(string connString, string sql)
{
string[] commands = sql.Split(new string[] { "GO\r\n", "GO ", "GO\t" }, StringSplitOptions.RemoveEmptyEntries);
var count = 0;
foreach (string c in commands)
{
try
{
count++;
ExecuteNonQuery(connString, CommandType.Text, c);
}
catch (SqlException ex)
{
throw new Exception(ex.Message + "; " + c, ex);
}
}
}
public static string BuildConnectionString(string serverName, string dbName, string dbUsername, string dbPassword)
{
var connBuilder = new SqlConnectionStringBuilder();
connBuilder.UserID = dbUsername;
connBuilder.Password = dbPassword;
connBuilder.DataSource = serverName;
connBuilder.InitialCatalog = dbName;
connBuilder.Pooling = true;
return connBuilder.ConnectionString;
}
public enum DbConnectivityResult { NotEmpty, Empty, DoesnExist, CantConnect };
public static DbConnectivityResult CheckDbConnectivity(string connString)
{
var connBuilder = new SqlConnectionStringBuilder(connString);
var database = connBuilder.InitialCatalog;
connBuilder.InitialCatalog = "";
try
{
var sql = @"SELECT COUNT(name) FROM [sys].[databases] WHERE name = @database";
var databaseExists = ((int)SqlHelper.ExecuteScalar(connBuilder.ConnectionString, CommandType.Text, sql, new SqlParameter("@database", database)) > 0);
if (!string.IsNullOrWhiteSpace(database) && databaseExists)
{
sql = "SELECT COUNT(*) FROM [sysobjects] WHERE [type] IN ('U', 'V', 'P')";
var isEmpty = ((int)SqlHelper.ExecuteScalar(connString, CommandType.Text, sql) == 0);
return isEmpty ? DbConnectivityResult.Empty : DbConnectivityResult.NotEmpty;
}
return DbConnectivityResult.DoesnExist;
}
catch
{
}
return DbConnectivityResult.CantConnect;
}
public static List<string> ListDatabases(string connString)
{
List<string> list = new List<string>();
var sql = @"SELECT name
FROM [sys].[databases]
WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')";
using (var reader = SqlHelper.ExecuteReader(connString, CommandType.Text, sql))
{
while (reader.Read())
{
list.Add((string)reader["name"]);
}
}
return list;
}
public static Type GetDbType(int dbTypeId)
{
switch (dbTypeId)
{
case -5:
return typeof(long);
case -1: // text
return typeof(string);
case -7: // bit
return typeof(bool);
case -6: // tinyint
return typeof(byte);
case 3: // decimal
return typeof(decimal);
case 6:
return typeof(double);
case 4: // int
return typeof(int);
case -9:
return typeof(DateTime);
case 11:
return typeof(DateTime);
case -10:
return typeof(string); // ntext
default:
return typeof(string);
}
}
public static string GetTableQualifier(string tableIdentifier)
{
if (string.IsNullOrEmpty(tableIdentifier))
return tableIdentifier;
var temp = tableIdentifier.Split('.');
if (temp.Count() > 1)
{
return temp[1].Trim(new[] { '[', ']' });
}
else if (temp.Count() == 1)
{
return temp[0].Trim(new[] { '[', ']' });
}
return "";
}
public static SqlParameter[] PreparePrimaryKeyParameters(IOrderedDictionary dataKeys, ref string sqlPart)
{
int primaryKeyOrdinal = 0;
var parameters = new SqlParameter[dataKeys.Keys.Count];
foreach (var partOfPrimaryKey in dataKeys.Keys)
{
sqlPart += " AND " + partOfPrimaryKey + "=@PK" + primaryKeyOrdinal;
parameters[primaryKeyOrdinal] = new SqlParameter("@PK" + primaryKeyOrdinal, dataKeys[partOfPrimaryKey]);
primaryKeyOrdinal++;
}
return parameters;
}
}
}