-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathSqlDataExecutor.cs
More file actions
230 lines (199 loc) · 7.8 KB
/
Copy pathSqlDataExecutor.cs
File metadata and controls
230 lines (199 loc) · 7.8 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
// Copyright (c) Geta Digital. All rights reserved.
// Licensed under Apache-2.0. See the LICENSE file in the project root for more information
using System;
using System.Data;
using System.Data.Common;
using System.Globalization;
using Geta.NotFoundHandler.Infrastructure.Configuration;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Geta.NotFoundHandler.Data
{
public class SqlDataExecutor : IDataExecutor
{
private readonly ILogger<SqlDataExecutor> _logger;
private readonly string _connectionString;
private readonly int _commandTimeout;
public SqlDataExecutor(
IOptions<NotFoundHandlerOptions> options,
ILogger<SqlDataExecutor> logger)
{
_connectionString = options.Value.ConnectionString;
_commandTimeout = options.Value.CommandTimeout;
_logger = logger;
}
public DataTable ExecuteQuery(string sqlCommand, params IDbDataParameter[] parameters)
{
var ds = new DataSet();
try
{
using var connection = new SqlConnection(_connectionString);
connection.Open();
using var command = CreateCommand(connection, sqlCommand, parameters);
using var da = new SqlDataAdapter(command);
da.Fill(ds);
}
catch (Exception ex)
{
_logger.LogError(ex,
"An error occurred in the ExecuteSQL method with the following sql: {SqlCommand}",
sqlCommand);
// Previously the exception was swallowed here and execution fell through to
// 'return ds.Tables[0]'. On a failed Fill the DataSet has no tables, so that line
// threw IndexOutOfRangeException ("Cannot find table 0"), masking the real cause
// (e.g. a command timeout). Rethrow so callers see the actual failure.
throw;
}
return ds.Tables[0];
}
public bool ExecuteNonQuery(string sqlCommand, params IDbDataParameter[] parameters)
{
var success = true;
try
{
using var connection = new SqlConnection(_connectionString);
connection.Open();
using var command = CreateCommand(connection, sqlCommand, parameters);
command.ExecuteNonQuery();
}
catch (Exception ex)
{
success = false;
_logger.LogError(ex,
"An error occurred in the ExecuteSQL method with the following sql: {SqlCommand}",
sqlCommand);
}
return success;
}
public int ExecuteScalar(string sqlCommand)
{
int result;
try
{
using var connection = new SqlConnection(_connectionString);
connection.Open();
using var command = CreateCommand(connection, sqlCommand);
var queryResult = command.ExecuteScalar();
if (queryResult == null) return 0;
result = (int)queryResult;
}
catch (Exception ex)
{
result = 0;
_logger.LogError(ex,
"An error occurred in the ExecuteScalar method with the following sql: {SqlCommand}",
sqlCommand);
}
return result;
}
public int ExecuteStoredProcedure(string sqlCommand, int defaultReturnValue = -1)
{
var value = defaultReturnValue;
try
{
using var connection = new SqlConnection(_connectionString);
connection.Open();
using var command = CreateCommand(connection, sqlCommand);
command.Parameters.Add(CreateReturnParameter());
command.CommandText = sqlCommand;
command.CommandType = CommandType.StoredProcedure;
command.ExecuteNonQuery();
value = Convert.ToInt32(GetReturnValue(command).ToString());
}
catch (SqlException)
{
_logger.LogInformation("Stored procedure not found");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while running stored procedure");
}
return value;
}
public DbParameter CreateParameter(string parameterName, DbType dbType)
{
var parameter = new SqlParameter
{
ParameterName = parameterName, DbType = dbType, Direction = ParameterDirection.Input
};
return parameter;
}
public DbParameter CreateParameter(string parameterName, DbType dbType, int size)
{
var parameter = new SqlParameter
{
ParameterName = parameterName,
DbType = dbType,
Direction = ParameterDirection.Input,
Size = size == 0 ? 1 : size
};
return parameter;
}
public static int GetReturnValue(DbCommand cmd)
{
var parameter = cmd.Parameters["@ReturnValue"];
return Convert.ToInt32(parameter.Value, CultureInfo.InvariantCulture);
}
public DbParameter CreateGuidParameter(string name, Guid value)
{
var parameter = CreateParameter(name, DbType.Guid);
parameter.Value = value;
return parameter;
}
public DbParameter CreateStringParameter(string name, string value, int size = 2000)
{
var parameter = CreateParameter(name, DbType.String, size);
parameter.Value = value;
return parameter;
}
public DbParameter CreateIntParameter(string name, int value)
{
var parameter = CreateParameter(name, DbType.Int32);
parameter.Value = value;
return parameter;
}
public DbParameter CreateBoolParameter(string name, bool value)
{
var parameter = CreateParameter(name, DbType.Boolean);
parameter.Value = value;
return parameter;
}
public DbParameter CreateDateTimeParameter(string name, DateTime value)
{
var parameter = CreateParameter(name, DbType.DateTime, 0);
parameter.Value = value;
return parameter;
}
public DbParameter CreateBinaryParameter(string name, byte[] value, int size = 8000)
{
var parameter = CreateParameter(name, DbType.Binary, size);
parameter.Value = value;
return parameter;
}
private static SqlParameter CreateReturnParameter()
{
var parameter = new SqlParameter
{
ParameterName = "@ReturnValue", DbType = DbType.Int32, Direction = ParameterDirection.ReturnValue,
};
return parameter;
}
private SqlCommand CreateCommand(SqlConnection connection, string sqlCommand, params IDbDataParameter[] parameters)
{
var command = connection.CreateCommand();
command.CommandText = sqlCommand;
command.CommandTimeout = _commandTimeout;
if (parameters != null)
{
foreach (var dbDataParameter in parameters)
{
var parameter = (SqlParameter)dbDataParameter;
command.Parameters.Add(parameter);
}
}
command.CommandType = CommandType.Text;
return command;
}
}
}