Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 400 lines (396 sloc) 19.307 kB
bdfd2a2 @subsonic Added async methods (thanks to Damien Edwards) and Rails ActiveRecord…
subsonic authored
1 using System;
2 using System.Collections.Generic;
3 using System.Collections.Specialized;
4 using System.Configuration;
5 using System.Data;
6 using System.Data.Common;
7 using System.Dynamic;
8 using System.Linq;
9 using System.Text;
10 using System.Threading.Tasks;
11 using System.Data.SqlClient;
12
13 namespace Massive {
14 public static class ObjectExtensions {
15 /// <summary>
16 /// Extension method for adding in a bunch of parameters
17 /// </summary>
18 public static void AddParams(this DbCommand cmd, params object[] args) {
19 foreach (var item in args) {
20 AddParam(cmd, item);
21 }
22 }
23 /// <summary>
24 /// Extension for adding single parameter
25 /// </summary>
26 public static void AddParam(this DbCommand cmd, object item) {
27 var p = cmd.CreateParameter();
28 p.ParameterName = string.Format("@{0}", cmd.Parameters.Count);
29 if (item == null) {
30 p.Value = DBNull.Value;
31 } else {
32 if (item.GetType() == typeof(Guid)) {
33 p.Value = item.ToString();
34 p.DbType = DbType.String;
35 p.Size = 4000;
36 } else if (item.GetType() == typeof(ExpandoObject)) {
37 var d = (IDictionary<string, object>)item;
38 p.Value = d.Values.FirstOrDefault();
39 } else {
40 p.Value = item;
41 }
42 if (item.GetType() == typeof(string))
43 p.Size = ((string)item).Length > 4000 ? -1 : 4000;
44 }
45 cmd.Parameters.Add(p);
46 }
47 /// <summary>
48 /// Turns an IDataReader to a Dynamic list of things
49 /// </summary>
50 public static List<dynamic> ToExpandoList(this IDataReader rdr) {
51 var result = new List<dynamic>();
52 while (rdr.Read()) {
53 result.Add(rdr.RecordToExpando());
54 }
55 return result;
56 }
57 public static dynamic RecordToExpando(this IDataReader rdr) {
58 dynamic e = new ExpandoObject();
59 var d = e as IDictionary<string, object>;
007d200 When returning data from a Query, convert DBNull values to null so ca…
David Clarke authored
60 for (int i = 0; i < rdr.FieldCount; i++)
bdfd2a2 @subsonic Added async methods (thanks to Damien Edwards) and Rails ActiveRecord…
subsonic authored
61 d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]);
62 return e;
63 }
64 /// <summary>
65 /// Turns the object into an ExpandoObject
66 /// </summary>
67 public static dynamic ToExpando(this object o) {
68 var result = new ExpandoObject();
69 var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
70 if (o.GetType() == typeof(ExpandoObject)) return o; //shouldn't have to... but just in case
71 if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection))) {
72 var nv = (NameValueCollection)o;
73 nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i));
74 } else {
75 var props = o.GetType().GetProperties();
76 foreach (var item in props) {
77 d.Add(item.Name, item.GetValue(o, null));
78 }
79 }
80 return result;
81 }
82 /// <summary>
83 /// Turns the object into a Dictionary
84 /// </summary>
85 public static IDictionary<string, object> ToDictionary(this object thingy) {
86 return (IDictionary<string, object>)thingy.ToExpando();
87 }
88 }
89 /// <summary>
90 /// A class that wraps your database table in Dynamic Funtime
91 /// </summary>
47c98a8 @subsonic Cleaned up a bit of stuff
subsonic authored
92 public class DynamicModel : DynamicObject {
bdfd2a2 @subsonic Added async methods (thanks to Damien Edwards) and Rails ActiveRecord…
subsonic authored
93 DbProviderFactory _factory;
94 string _connectionString;
95
47c98a8 @subsonic Cleaned up a bit of stuff
subsonic authored
96 public DynamicModel(string connectionStringName,string tableName = "", string primaryKeyField = "") {
bdfd2a2 @subsonic Added async methods (thanks to Damien Edwards) and Rails ActiveRecord…
subsonic authored
97 TableName = tableName == "" ? this.GetType().Name : tableName;
98 PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField;
99 var _providerName = "System.Data.SqlClient";
100 _factory = DbProviderFactories.GetFactory(_providerName);
101 _connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
102 }
103 /// <summary>
104 /// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert
105 /// </summary>
106 public virtual IEnumerable<dynamic> Query(string sql, params object[] args) {
107 using (var conn = OpenConnection()) {
108 var rdr = CreateCommand(sql, conn, args).ExecuteReader();
109 while (rdr.Read()) {
110 yield return rdr.RecordToExpando(); ;
111 }
112 }
113 }
114 /// <summary>
6424009 updates to async API
unknown authored
115 /// Executes the reader using SQL async API - thanks to Damian Edwards
bdfd2a2 @subsonic Added async methods (thanks to Damien Edwards) and Rails ActiveRecord…
subsonic authored
116 /// </summary>
117 public void QueryAsync(string sql, Action<List<dynamic>> callback, params object[] args) {
6424009 updates to async API
unknown authored
118 using (var conn = new SqlConnection(_connectionString)) {
119 var cmd = new SqlCommand(sql, new SqlConnection(_connectionString));
bdfd2a2 @subsonic Added async methods (thanks to Damien Edwards) and Rails ActiveRecord…
subsonic authored
120 cmd.AddParams(args);
47c98a8 @subsonic Cleaned up a bit of stuff
subsonic authored
121 cmd.Connection.Open();
bdfd2a2 @subsonic Added async methods (thanks to Damien Edwards) and Rails ActiveRecord…
subsonic authored
122 var task = Task.Factory.FromAsync<IDataReader>(cmd.BeginExecuteReader, cmd.EndExecuteReader, null);
123 task.ContinueWith(x => callback.Invoke(x.Result.ToExpandoList()));
124 }
125 }
126 public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, params object[] args) {
127 using (var rdr = CreateCommand(sql, connection, args).ExecuteReader()) {
128 while (rdr.Read()) {
129 yield return rdr.RecordToExpando(); ;
130 }
131 }
132 }
133 /// <summary>
134 /// Returns a single result
135 /// </summary>
136 public virtual object Scalar(string sql, params object[] args) {
137 object result = null;
138 using (var conn = OpenConnection()) {
139 result = CreateCommand(sql, conn, args).ExecuteScalar();
140 }
141 return result;
142 }
143 /// <summary>
144 /// Creates a DBCommand that you can use for loving your database.
145 /// </summary>
146 DbCommand CreateCommand(string sql, DbConnection conn, params object[] args) {
147 var result = _factory.CreateCommand();
148 result.Connection = conn;
149 result.CommandText = sql;
150 if (args.Length > 0)
151 result.AddParams(args);
152 return result;
153 }
154 /// <summary>
155 /// Returns and OpenConnection
156 /// </summary>
157 public virtual DbConnection OpenConnection() {
158 var result = _factory.CreateConnection();
159 result.ConnectionString = _connectionString;
160 result.Open();
161 return result;
162 }
163 /// <summary>
164 /// Builds a set of Insert and Update commands based on the passed-on objects.
165 /// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
166 /// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
167 /// </summary>
168 public virtual List<DbCommand> BuildCommands(params object[] things) {
169 var commands = new List<DbCommand>();
170 foreach (var item in things) {
171 if (HasPrimaryKey(item)) {
172 commands.Add(CreateUpdateCommand(item, GetPrimaryKey(item)));
173 } else {
174 commands.Add(CreateInsertCommand(item));
175 }
176 }
177 return commands;
178 }
179 /// <summary>
180 /// Executes a set of objects as Insert or Update commands based on their property settings, within a transaction.
181 /// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
182 /// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
183 /// </summary>
184 public virtual int Save(params object[] things) {
185 var commands = BuildCommands(things);
186 return Execute(commands);
187 }
188 public virtual int Execute(DbCommand command) {
189 return Execute(new DbCommand[] { command });
190 }
191 /// <summary>
192 /// Executes a series of DBCommands in a transaction
193 /// </summary>
194 public virtual int Execute(IEnumerable<DbCommand> commands) {
195 var result = 0;
196 using (var conn = OpenConnection()) {
197 using (var tx = conn.BeginTransaction()) {
198 foreach (var cmd in commands) {
199 cmd.Connection = conn;
200 cmd.Transaction = tx;
201 result += cmd.ExecuteNonQuery();
202 }
203 tx.Commit();
204 }
205 }
206 return result;
207 }
208 public virtual string PrimaryKeyField { get; set; }
209 /// <summary>
210 /// Conventionally introspects the object passed in for a field that
211 /// looks like a PK. If you've named your PrimaryKeyField, this becomes easy
212 /// </summary>
213 public virtual bool HasPrimaryKey(object o) {
214 return o.ToDictionary().ContainsKey(PrimaryKeyField);
215 }
216 /// <summary>
217 /// If the object passed in has a property with the same name as your PrimaryKeyField
218 /// it is returned here.
219 /// </summary>
220 public virtual object GetPrimaryKey(object o) {
221 object result = null;
222 o.ToDictionary().TryGetValue(PrimaryKeyField, out result);
223 return result;
224 }
225 public virtual string TableName { get; set; }
226 /// <summary>
227 /// Creates a command for use with transactions - internal stuff mostly, but here for you to play with
228 /// </summary>
229 public virtual DbCommand CreateInsertCommand(object o) {
230 DbCommand result = null;
231 var expando = o.ToExpando();
232 var settings = (IDictionary<string, object>)expando;
233 var sbKeys = new StringBuilder();
234 var sbVals = new StringBuilder();
235 var stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})";
236 result = CreateCommand(stub, null);
237 int counter = 0;
238 foreach (var item in settings) {
239 sbKeys.AppendFormat("{0},", item.Key);
240 sbVals.AppendFormat("@{0},", counter.ToString());
241 result.AddParam(item.Value);
242 counter++;
243 }
244 if (counter > 0) {
245 var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 1);
246 var vals = sbVals.ToString().Substring(0, sbVals.Length - 1);
247 var sql = string.Format(stub, TableName, keys, vals);
248 result.CommandText = sql;
249 } else throw new InvalidOperationException("Can't parse this object to the database - there are no properties set");
250 return result;
251 }
252 /// <summary>
253 /// Creates a command for use with transactions - internal stuff mostly, but here for you to play with
254 /// </summary>
255 public virtual DbCommand CreateUpdateCommand(object o, object key) {
256 var expando = o.ToExpando();
257 var settings = (IDictionary<string, object>)expando;
258 var sbKeys = new StringBuilder();
259 var stub = "UPDATE {0} SET {1} WHERE {2} = @{3}";
260 var args = new List<object>();
261 var result = CreateCommand(stub, null);
262 int counter = 0;
263 foreach (var item in settings) {
264 var val = item.Value;
265 if (!item.Key.Equals(PrimaryKeyField, StringComparison.CurrentCultureIgnoreCase) && item.Value != null) {
266 result.AddParam(val);
267 sbKeys.AppendFormat("{0} = @{1}, \r\n", item.Key, counter.ToString());
268 counter++;
269 }
270 }
271 if (counter > 0) {
272 //add the key
273 result.AddParam(key);
274 //strip the last commas
275 var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 4);
276 result.CommandText = string.Format(stub, TableName, keys, PrimaryKeyField, counter);
277 } else throw new InvalidOperationException("No parsable object was sent in - could not divine any name/value pairs");
278 return result;
279 }
280 /// <summary>
281 /// Removes one or more records from the DB according to the passed-in WHERE
282 /// </summary>
283 public virtual DbCommand CreateDeleteCommand(string where = "", object key = null, params object[] args) {
284 var sql = string.Format("DELETE FROM {0} ", TableName);
285 if (key != null) {
286 sql += string.Format("WHERE {0}=@0", PrimaryKeyField);
287 args = new object[] { key };
288 } else if (!string.IsNullOrEmpty(where)) {
289 sql += where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase) ? where : "WHERE " + where;
290 }
291 return CreateCommand(sql, null, args);
292 }
293 /// <summary>
294 /// Adds a record to the database. You can pass in an Anonymous object, an ExpandoObject,
295 /// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString
296 /// </summary>
297 public virtual object Insert(object o) {
298 dynamic result = 0;
299 using (var conn = OpenConnection()) {
300 var cmd = CreateInsertCommand(o);
301 cmd.Connection = conn;
302 cmd.ExecuteNonQuery();
303 cmd.CommandText = "SELECT @@IDENTITY as newID";
304 result = cmd.ExecuteScalar();
305 }
306 return result;
307 }
308 /// <summary>
309 /// Updates a record in the database. You can pass in an Anonymous object, an ExpandoObject,
310 /// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString
311 /// </summary>
312 public virtual int Update(object o, object key) {
313 return Execute(CreateUpdateCommand(o, key));
314 }
315 /// <summary>
316 /// Removes one or more records from the DB according to the passed-in WHERE
317 /// </summary>
318 public int Delete(object key = null, string where = "", params object[] args) {
319 return Execute(CreateDeleteCommand(where: where, key: key, args: args));
320 }
321 /// <summary>
322 /// Returns all records complying with the passed-in WHERE clause and arguments,
323 /// ordered as specified, limited (TOP) by limit.
324 /// </summary>
325 public virtual IEnumerable<dynamic> All(string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args) {
326 string sql = BuildSelect(where, orderBy, limit);
327 return Query(string.Format(sql, columns, TableName), args);
328 }
329 private static string BuildSelect(string where, string orderBy, int limit) {
330 string sql = limit > 0 ? "SELECT TOP " + limit + " {0} FROM {1} " : "SELECT {0} FROM {1} ";
331 if (!string.IsNullOrEmpty(where))
332 sql += where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase) ? where : "WHERE " + where;
333 if (!String.IsNullOrEmpty(orderBy))
334 sql += orderBy.Trim().StartsWith("order by", StringComparison.CurrentCultureIgnoreCase) ? orderBy : " ORDER BY " + orderBy;
335 return sql;
336 }
337 /// <summary>
338 /// Returns all records complying with the passed-in WHERE clause and arguments,
339 /// ordered as specified, limited (TOP) by limit.
340 /// </summary>
47c98a8 @subsonic Cleaned up a bit of stuff
subsonic authored
341 public virtual void AllAsync(Action<List<dynamic>> callback, string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args) {
bdfd2a2 @subsonic Added async methods (thanks to Damien Edwards) and Rails ActiveRecord…
subsonic authored
342 string sql = BuildSelect(where, orderBy, limit);
47c98a8 @subsonic Cleaned up a bit of stuff
subsonic authored
343 QueryAsync(string.Format(sql, columns, TableName), callback, args);
bdfd2a2 @subsonic Added async methods (thanks to Damien Edwards) and Rails ActiveRecord…
subsonic authored
344 }
345 /// <summary>
346 /// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords.
347 /// </summary>
348 public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) {
349 dynamic result = new ExpandoObject();
350 var countSQL = string.Format("SELECT COUNT({0}) FROM {1}", PrimaryKeyField, TableName);
351 if (String.IsNullOrEmpty(orderBy))
352 orderBy = PrimaryKeyField;
353
354 if (!string.IsNullOrEmpty(where)) {
355 if (!where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase)) {
356 where = "WHERE " + where;
357 }
358 }
359 var sql = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ", columns, pageSize, orderBy, TableName, where);
360 var pageStart = (currentPage - 1) * pageSize;
361 sql += string.Format(" WHERE Row > {0} AND Row <={1}", pageStart, (pageStart + pageSize));
362 countSQL += where;
363 result.TotalRecords = Scalar(countSQL, args);
364 result.TotalPages = result.TotalRecords / pageSize;
365 if (result.TotalRecords % pageSize > 0)
366 result.TotalPages += 1;
367 result.Items = Query(string.Format(sql, columns, TableName), args);
368 return result;
369 }
370 /// <summary>
371 /// Returns a single row from the database
372 /// </summary>
373 public virtual dynamic Single(object key, string columns = "*") {
374 var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns, TableName, PrimaryKeyField);
375 var items = Query(sql, key).ToList();
376 return items.FirstOrDefault();
377 }
378 /// <summary>
379 /// A little Rails-y love for ya
380 /// </summary>
381 public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {
382 //parse the method
383 var stems = binder.Name.Split('_');
384 var sb = new List<string>();
385
386 //first should be "FindBy or whatever"
387 var op = stems[0];
388 var counter = 0;
389 for (int i = 1; i < stems.Length; i++) {
390 if (stems[i].Trim().ToLower() != "and") {
391 sb.Add(stems[i] + "=@" + counter);
392 counter++;
393 }
394 }
395 var sql = "SELECT * FROM " + TableName + " WHERE " + string.Join(" AND ", sb.ToArray());
396 result = Query(sql, args);
397 return true;
398 }
399 }
b03bf61 @davecowart light refactoring; 500 lines
davecowart authored
400 }
Something went wrong with that request. Please try again.