-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathDatabase.cs
More file actions
304 lines (257 loc) · 10.8 KB
/
Database.cs
File metadata and controls
304 lines (257 loc) · 10.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
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
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using Microsoft.Internal.Web.Utils;
using WebMatrix.Data.Resources;
namespace WebMatrix.Data
{
public class Database : IDisposable
{
internal const string SqlCeProviderName = "System.Data.SqlServerCe.4.0";
internal const string SqlServerProviderName = "System.Data.SqlClient";
private const string DefaultDataProviderAppSetting = "systemData:defaultProvider";
internal static string DataDirectory = (string)AppDomain.CurrentDomain.GetData("DataDirectory") ?? Directory.GetCurrentDirectory();
private static readonly IDictionary<string, IDbFileHandler> _databaseFileHandlers = new Dictionary<string, IDbFileHandler>(StringComparer.OrdinalIgnoreCase)
{
{ ".sdf", new SqlCeDbFileHandler() },
{ ".mdf", new SqlServerDbFileHandler() }
};
private static readonly IConfigurationManager _configurationManager = new ConfigurationManagerWrapper(_databaseFileHandlers);
private Func<DbConnection> _connectionFactory;
private DbConnection _connection;
internal Database(Func<DbConnection> connectionFactory)
{
_connectionFactory = connectionFactory;
}
public static event EventHandler<ConnectionEventArgs> ConnectionOpened
{
add { _connectionOpened += value; }
remove { _connectionOpened -= value; }
}
private static event EventHandler<ConnectionEventArgs> _connectionOpened;
public DbConnection Connection
{
get
{
if (_connection == null)
{
_connection = _connectionFactory();
}
return _connection;
}
}
public void Close()
{
Dispose();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_connection != null)
{
_connection.Close();
_connection = null;
}
}
}
public dynamic QuerySingle(string commandText, params object[] args)
{
if (String.IsNullOrEmpty(commandText))
{
throw ExceptionHelper.CreateArgumentNullOrEmptyException("commandText");
}
return QueryInternal(commandText, args).FirstOrDefault();
}
public IEnumerable<dynamic> Query(string commandText, params object[] parameters)
{
if (String.IsNullOrEmpty(commandText))
{
throw ExceptionHelper.CreateArgumentNullOrEmptyException("commandText");
}
// Return a readonly collection
return QueryInternal(commandText, parameters).ToList().AsReadOnly();
}
[SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "Users are responsible for ensuring the inputs to this method are SQL Injection sanitized")]
private IEnumerable<dynamic> QueryInternal(string commandText, params object[] parameters)
{
EnsureConnectionOpen();
DbCommand command = Connection.CreateCommand();
command.CommandText = commandText;
AddParameters(command, parameters);
using (command)
{
IEnumerable<string> columnNames = null;
using (DbDataReader reader = command.ExecuteReader())
{
foreach (DbDataRecord record in reader)
{
if (columnNames == null)
{
columnNames = GetColumnNames(record);
}
yield return new DynamicRecord(columnNames, record);
}
}
}
}
private static IEnumerable<string> GetColumnNames(DbDataRecord record)
{
// Get all of the column names for this query
for (int i = 0; i < record.FieldCount; i++)
{
yield return record.GetName(i);
}
}
[SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "Users are responsible for ensuring the inputs to this method are SQL Injection sanitized")]
public int Execute(string commandText, params object[] args)
{
if (String.IsNullOrEmpty(commandText))
{
throw ExceptionHelper.CreateArgumentNullOrEmptyException("commandText");
}
EnsureConnectionOpen();
DbCommand command = Connection.CreateCommand();
command.CommandText = commandText;
AddParameters(command, args);
using (command)
{
return command.ExecuteNonQuery();
}
}
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This makes a database request")]
public dynamic GetLastInsertId()
{
// This method only support sql ce and sql server for now
return QueryValue("SELECT @@Identity");
}
[SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "Users are responsible for ensuring the inputs to this method are SQL Injection sanitized")]
public dynamic QueryValue(string commandText, params object[] args)
{
if (String.IsNullOrEmpty(commandText))
{
throw ExceptionHelper.CreateArgumentNullOrEmptyException("commandText");
}
EnsureConnectionOpen();
DbCommand command = Connection.CreateCommand();
command.CommandText = commandText;
AddParameters(command, args);
using (command)
{
return command.ExecuteScalar();
}
}
private void EnsureConnectionOpen()
{
// If the connection isn't open then open it
if (Connection.State != ConnectionState.Open)
{
Connection.Open();
// Raise the connection opened event
OnConnectionOpened();
}
}
private void OnConnectionOpened()
{
if (_connectionOpened != null)
{
_connectionOpened(this, new ConnectionEventArgs(Connection));
}
}
private static void AddParameters(DbCommand command, object[] args)
{
if (args == null)
{
return;
}
// Create numbered parameters
IEnumerable<DbParameter> parameters = args.Select((o, index) =>
{
var parameter = command.CreateParameter();
parameter.ParameterName = index.ToString(CultureInfo.InvariantCulture);
parameter.Value = o ?? DBNull.Value;
return parameter;
});
foreach (var p in parameters)
{
command.Parameters.Add(p);
}
}
public static Database OpenConnectionString(string connectionString)
{
return OpenConnectionString(connectionString, providerName: null);
}
public static Database OpenConnectionString(string connectionString, string providerName)
{
if (String.IsNullOrEmpty(connectionString))
{
throw ExceptionHelper.CreateArgumentNullOrEmptyException("connectionString");
}
return OpenConnectionStringInternal(providerName, connectionString);
}
public static Database Open(string name)
{
if (String.IsNullOrEmpty(name))
{
throw ExceptionHelper.CreateArgumentNullOrEmptyException("name");
}
return OpenNamedConnection(name, _configurationManager);
}
internal static IConnectionConfiguration GetConnectionConfiguration(string fileName, IDictionary<string, IDbFileHandler> handlers)
{
string extension = Path.GetExtension(fileName);
IDbFileHandler handler;
if (handlers.TryGetValue(extension, out handler))
{
return handler.GetConnectionConfiguration(fileName);
}
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
DataResources.UnableToDetermineDatabase, fileName));
}
private static Database OpenConnectionStringInternal(string providerName, string connectionString)
{
return OpenConnectionStringInternal(new DbProviderFactoryWrapper(providerName), connectionString);
}
private static Database OpenConnectionInternal(IConnectionConfiguration connectionConfig)
{
return OpenConnectionStringInternal(connectionConfig.ProviderFactory, connectionConfig.ConnectionString);
}
internal static Database OpenConnectionStringInternal(IDbProviderFactory providerFactory, string connectionString)
{
return new Database(() => providerFactory.CreateConnection(connectionString));
}
internal static Database OpenNamedConnection(string name, IConfigurationManager configurationManager)
{
// Opens a connection using the connection string setting with the specified name
IConnectionConfiguration configuration = configurationManager.GetConnection(name);
if (configuration != null)
{
// We've found one in the connection string setting in config so use it
return OpenConnectionInternal(configuration);
}
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
DataResources.ConnectionStringNotFound, name));
}
internal static string GetDefaultProviderName()
{
string providerName;
// Get the default provider name from config if there is any
if (!_configurationManager.AppSettings.TryGetValue(DefaultDataProviderAppSetting, out providerName))
{
providerName = SqlCeProviderName;
}
return providerName;
}
}
}