forked from schotime/massive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Massive.cs
1158 lines (1066 loc) · 42.2 KB
/
Massive.cs
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
/*
* Massive: a lightweight Data Access tool written by Rob Conery
* http://wekeroad.com/helpy-stuff/and-i-shall-call-it-massive
* http://theothersideofcode.com/lightweight-data-access-in-dot-net-massive
* https://github.com/robconery/massive
*
*/
namespace PAMP.Utils
{
/// <summary>
/// case-insensitive ExpandoObject
/// </summary>
public class MassiveExpando : DynamicObject, IDictionary<string, object>
{
// internal dictionary, which is case insensitive
private IDictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase);
#region extend DynamicObject
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (dictionary.ContainsKey(binder.Name))
{
result = dictionary[binder.Name];
return true;
}
return base.TryGetMember(binder, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (!dictionary.ContainsKey(binder.Name))
dictionary.Add(binder.Name, value);
else
dictionary[binder.Name] = value;
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
if (dictionary.ContainsKey(binder.Name) && dictionary[binder.Name] is Delegate)
{
Delegate del = dictionary[binder.Name] as Delegate;
result = del.DynamicInvoke(args);
return true;
}
return base.TryInvokeMember(binder, args, out result);
}
public override bool TryDeleteMember(DeleteMemberBinder binder)
{
if (dictionary.ContainsKey(binder.Name))
{
dictionary.Remove(binder.Name);
return true;
}
return base.TryDeleteMember(binder);
}
#endregion
#region implements interface IDictionary<string, object>
#region IDictionary<string,object> Members
public void Add(string key, object value)
{
dictionary.Add(key, value);
}
public bool ContainsKey(string key)
{
return dictionary.ContainsKey(key);
}
public ICollection<string> Keys
{
get
{
return dictionary.Keys;
}
}
public bool Remove(string key)
{
return dictionary.Remove(key);
}
public bool TryGetValue(string key, out object value)
{
return dictionary.TryGetValue(key, out value);
}
public ICollection<object> Values
{
get
{
return dictionary.Values;
}
}
public object this[string key]
{
get
{
return dictionary[key];
}
set
{
dictionary[key] = value;
}
}
#endregion
#region ICollection<KeyValuePair<string,object>> Members
public void Add(KeyValuePair<string, object> item)
{
dictionary.Add(item);
}
public void Clear()
{
dictionary.Clear();
}
public bool Contains(KeyValuePair<string, object> item)
{
return dictionary.Contains(item);
}
public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
dictionary.CopyTo(array, arrayIndex);
}
public int Count
{
get
{
return dictionary.Keys.Count;
}
}
public bool IsReadOnly
{
get
{
return dictionary.IsReadOnly;
}
}
public bool Remove(KeyValuePair<string, object> item)
{
return dictionary.Remove(item);
}
#endregion
#region IEnumerable<KeyValuePair<string,object>> Members
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return dictionary.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#endregion
}
public static class ObjectExtensions
{
/// <summary>
/// Extension method for adding in a bunch of parameters
/// </summary>
public static void AddParams(this DbCommand cmd, params object[] args)
{
foreach (var item in args)
{
AddParam(cmd, item);
}
}
/// <summary>
/// Extension for adding single parameter
/// </summary>
public static void AddParam(this DbCommand cmd, object item)
{
var p = cmd.CreateParameter();
p.ParameterName = string.Format("@{0}", cmd.Parameters.Count);
if (item == null)
{
p.Value = DBNull.Value;
}
else
{
if (item.GetType() == typeof(Guid))
{
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
}
else if (item.GetType() == typeof(MassiveExpando) || item.GetType() == typeof(ExpandoObject))
{
var d = (IDictionary<string, object>)item;
p.Value = d.Values.FirstOrDefault();
}
else
{
p.Value = item;
}
if (item.GetType() == typeof(string))
p.Size = ((string)item).Length > 4000 ? -1 : 4000;
}
cmd.Parameters.Add(p);
}
/// <summary>
/// Turns an IDataReader to a Dynamic list of things
/// </summary>
public static List<dynamic> ToExpandoList(this IDataReader rdr)
{
var result = new List<dynamic>();
while (rdr.Read())
{
result.Add(rdr.RecordToExpando());
}
return result;
}
public static dynamic RecordToExpando(this IDataReader rdr)
{
dynamic e = new MassiveExpando();
var d = e as IDictionary<string, object>;
for (int i = 0; i < rdr.FieldCount; i++)
d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]);
return e;
}
/// <summary>
/// Turns the object into a case-insensitive MassiveExpando dynamic object
/// </summary>
public static dynamic ToExpando(this object o)
{
var result = new MassiveExpando();
var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
if (o.GetType() == typeof(MassiveExpando)) //shouldn't have to... but just in case
return o;
if (o.GetType() == typeof(ExpandoObject))
{
var dd = o as IDictionary<string, object>;
foreach (var key in dd.Keys)
{
d[key] = dd[key];
}
}
if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection)))
{
var nv = (NameValueCollection)o;
nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i));
}
else if (o is System.Collections.IDictionary)
{
var dd = o as IDictionary;
foreach (var key in dd.Keys)
{
var value = dd[key];
d.Add(key as string, value);
}
}
else
{
var props = o.GetType().GetProperties();
foreach (var item in props)
{
d.Add(item.Name, item.GetValue(o, null));
}
}
return result;
}
/// <summary>
/// Turns the object into a Dictionary
/// </summary>
public static IDictionary<string, object> ToDictionary(this object thingy)
{
return (IDictionary<string, object>)thingy.ToExpando();
}
}
/// <summary>
/// Convenience class for opening/executing data
/// </summary>
public static class DB
{
public static DynamicModel Current
{
get
{
if (ConfigurationManager.ConnectionStrings.Count > 1)
{
return new DynamicModel(ConfigurationManager.ConnectionStrings[0].Name);
}
throw new InvalidOperationException("Need a connection string name - can't determine what it is");
}
}
}
/// <summary>
/// A class that wraps your database table in Dynamic Funtime
/// </summary>
public class DynamicModel : DynamicObject
{
DbProviderFactory _factory;
string ConnectionString;
public static DynamicModel Open(string connectionStringName)
{
dynamic dm = new DynamicModel(connectionStringName);
return dm;
}
public DynamicModel(string connectionStringName = "", string tableName = "",
string primaryKeyField = "", string descriptorField = "", bool isPrimaryKeyIdentity = true)
{
TableName = tableName == "" ? this.GetType().Name : tableName;
PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField;
IsPrimaryKeyIdentity = isPrimaryKeyIdentity;
var _providerName = "System.Data.SqlClient";
_factory = DbProviderFactories.GetFactory(_providerName);
if (connectionStringName == "")
connectionStringName = ConfigurationManager.ConnectionStrings[0].Name;
ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
/// <summary>
/// Creates a new Expando from a Form POST - white listed against the columns in the DB
/// </summary>
public dynamic CreateFrom(NameValueCollection coll)
{
dynamic result = new MassiveExpando();
var dc = (IDictionary<string, object>)result;
var schema = Schema;
//loop the collection, setting only what's in the Schema
foreach (var item in coll.Keys)
{
var exists = schema.Any(x => x.COLUMN_NAME.ToLower() == item.ToString().ToLower());
if (exists)
{
var key = item.ToString();
var val = coll[key];
dc.Add(key, val);
}
}
return result;
}
/// <summary>
/// Creates a new Expando from a dictionary - white listed against the columns in the DB
/// </summary>
/// <param name="dict"></param>
/// <returns></returns>
public dynamic CreateFrom(IDictionary<string, object> dict)
{
dynamic result = new MassiveExpando();
var dc = (IDictionary<string, object>)result;
var schema = Schema;
// loop the dict, setting only what's in the Schema
foreach (var key in dict.Keys)
{
var exists = schema.Any(x => x.COLUMN_NAME.ToLower() == key.ToLower());
if (exists)
{
var val = dict[key];
dc.Add(key, val);
}
}
return result;
}
/// <summary>
/// Gets a default value for the column
/// </summary>
public dynamic DefaultValue(dynamic column)
{
dynamic result = null;
string def = column.COLUMN_DEFAULT;
if (String.IsNullOrEmpty(def))
{
result = null;
}
else if (def == "getdate()" || def == "(getdate())")
{
result = DateTime.Now.ToShortDateString();
}
else if (def == "newid()")
{
result = Guid.NewGuid().ToString();
}
else
{
result = def.Replace("(", "").Replace(")", "");
}
return result;
}
/// <summary>
/// Creates an empty Expando set with defaults from the DB
/// </summary>
public dynamic Prototype
{
get
{
dynamic result = new MassiveExpando();
var schema = Schema;
foreach (dynamic column in schema)
{
var dc = (IDictionary<string, object>)result;
dc.Add(column.COLUMN_NAME, DefaultValue(column));
}
result._Table = this;
return result;
}
}
private string _descriptorField = null;
public string DescriptorField
{
get
{
return _descriptorField;
}
}
/// <summary>
/// List out all the schema bits for use with ... whatever
/// </summary>
IEnumerable<dynamic> _schema;
public IEnumerable<dynamic> Schema
{
get
{
if (_schema == null)
_schema = Query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @0", TableName);
return _schema;
}
}
/// <summary>
/// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert
/// </summary>
public virtual IEnumerable<dynamic> Query(string sql, params object[] args)
{
using (var conn = OpenConnection())
{
var rdr = CreateCommand(sql, conn, args).ExecuteReader();
while (rdr.Read())
{
yield return rdr.RecordToExpando(); ;
}
}
}
public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, params object[] args)
{
using (var rdr = CreateCommand(sql, connection, args).ExecuteReader())
{
while (rdr.Read())
{
yield return rdr.RecordToExpando(); ;
}
}
}
/// <summary>
/// Runs a query against the database, similar to Query(), but returns the result list instead of a IEnumerable
/// </summary>
/// <param name="sql"></param>
/// <param name="args"></param>
/// <returns></returns>
public virtual IList<dynamic> Fetch(string sql, params object[] args)
{
return this.Query(sql, args).ToList();
}
/// <summary>
/// Returns a single result
/// </summary>
public virtual object Scalar(string sql, params object[] args)
{
object result = null;
using (var conn = OpenConnection())
{
result = CreateCommand(sql, conn, args).ExecuteScalar();
}
return result;
}
/// <summary>
/// Creates a DBCommand that you can use for loving your database.
/// </summary>
DbCommand CreateCommand(string sql, DbConnection conn, params object[] args)
{
var result = _factory.CreateCommand();
result.Connection = conn;
result.CommandText = sql;
if (args.Length > 0)
result.AddParams(args);
return result;
}
/// <summary>
/// Returns and OpenConnection
/// </summary>
public virtual DbConnection OpenConnection()
{
var result = _factory.CreateConnection();
result.ConnectionString = ConnectionString;
result.Open();
return result;
}
/// <summary>
/// Builds a set of Insert and Update commands based on the passed-on objects.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual List<DbCommand> BuildCommands(params object[] things)
{
var commands = new List<DbCommand>();
foreach (var item in things)
{
if (HasPrimaryKey(item))
{
commands.Add(CreateUpdateCommand(item.ToExpando(), GetPrimaryKey(item)));
}
else
{
commands.Add(CreateInsertCommand(item.ToExpando()));
}
}
return commands;
}
public virtual int Execute(DbCommand command)
{
return Execute(new DbCommand[] { command });
}
public virtual int Execute(string sql, params object[] args)
{
return Execute(CreateCommand(sql, null, args));
}
/// <summary>
/// Executes a series of DBCommands in a transaction
/// </summary>
public virtual int Execute(IEnumerable<DbCommand> commands)
{
var result = 0;
using (var conn = OpenConnection())
{
using (var tx = conn.BeginTransaction())
{
foreach (var cmd in commands)
{
cmd.Connection = conn;
cmd.Transaction = tx;
result += cmd.ExecuteNonQuery();
}
tx.Commit();
}
}
return result;
}
public virtual bool IsPrimaryKeyIdentity { get; set; } // Pink add this
public virtual string PrimaryKeyField { get; set; }
/// <summary>
/// Conventionally introspects the object passed in for a field that
/// looks like a PK. If you've named your PrimaryKeyField, this becomes easy
/// </summary>
public virtual bool HasPrimaryKey(object o)
{
return o.ToDictionary().ContainsKey(PrimaryKeyField);
}
/// <summary>
/// If the object passed in has a property with the same name as your PrimaryKeyField
/// it is returned here.
/// </summary>
public virtual object GetPrimaryKey(object o)
{
object result = null;
o.ToDictionary().TryGetValue(PrimaryKeyField, out result);
return result;
}
public virtual string TableName { get; set; }
/// <summary>
/// Returns all records complying with the passed-in WHERE clause and arguments,
/// ordered as specified, limited (TOP) by limit.
/// </summary>
public virtual IEnumerable<dynamic> All(string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args)
{
string sql = BuildSelect(where, orderBy, limit);
return Query(string.Format(sql, columns, TableName), args);
}
private static string BuildSelect(string where, string orderBy, int limit)
{
string sql = limit > 0 ? "SELECT TOP " + limit + " {0} FROM {1} " : "SELECT {0} FROM {1} ";
if (!string.IsNullOrEmpty(where))
sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where;
if (!String.IsNullOrEmpty(orderBy))
sql += orderBy.Trim().StartsWith("order by", StringComparison.OrdinalIgnoreCase) ? orderBy : " ORDER BY " + orderBy;
return sql;
}
/// <summary>
/// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords.
/// </summary>
public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args)
{
dynamic result = new MassiveExpando();
var countSQL = string.Format("SELECT COUNT(1) FROM {0} ", TableName);
if (String.IsNullOrEmpty(orderBy))
orderBy = "newid()";
if (!string.IsNullOrEmpty(where))
{
if (!where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase))
{
where = "WHERE " + where;
}
}
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);
var pageStart = (currentPage - 1) * pageSize;
sql += string.Format(" WHERE Row > {0} AND Row <={1}", pageStart, (pageStart + pageSize));
countSQL += where;
result.TotalRecords = Scalar(countSQL, args);
result.TotalPages = result.TotalRecords / pageSize;
if (result.TotalRecords % pageSize > 0)
result.TotalPages += 1;
result.Items = Query(string.Format(sql, columns, TableName), args);
return result;
}
/// <summary>
/// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords.
/// </summary>
public virtual dynamic Paged(string viewSql, string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args)
{
dynamic result = new MassiveExpando();
string tablename = this.TableName;
if (!string.IsNullOrEmpty(viewSql))
{
tablename = string.Format("({0}) t0", viewSql);
}
var countSQL = string.Format("SELECT COUNT(1) FROM {0} ", tablename);
if (String.IsNullOrEmpty(orderBy))
orderBy = "newid()";
if (!string.IsNullOrEmpty(where))
{
if (!where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase))
{
where = "WHERE " + where;
}
}
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);
var pageStart = (currentPage - 1) * pageSize;
sql += string.Format(" WHERE Row > {0} AND Row <={1}", pageStart, (pageStart + pageSize));
countSQL += where;
result.TotalRecords = Scalar(countSQL, args);
result.TotalPages = result.TotalRecords / pageSize;
if (result.TotalRecords % pageSize > 0)
result.TotalPages += 1;
result.Items = Query(string.Format(sql, columns, tablename), args);
return result;
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(string where, string columns = "*", params object[] args)
{
string wheresql = where.IsNullOrEmpty() ? "" : (where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where);
var sql = string.Format("SELECT {2} FROM {0} {1}", TableName, wheresql, columns);
return Query(sql, args).FirstOrDefault();
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(object key, string columns = "*")
{
if (key == null)
return null;
var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns, TableName, PrimaryKeyField);
return Query(sql, key).FirstOrDefault();
}
/// <summary>
/// This will return a string/object dictionary for dropdowns etc
/// </summary>
public virtual IDictionary<string, object> KeyValues(string orderBy = "")
{
if (String.IsNullOrEmpty(DescriptorField))
throw new InvalidOperationException("There's no DescriptorField set - do this in your constructor to describe the text value you want to see");
var sql = string.Format("SELECT {0},{1} FROM {2} ", PrimaryKeyField, DescriptorField, TableName);
if (!String.IsNullOrEmpty(orderBy))
sql += "ORDER BY " + orderBy;
return (IDictionary<string, object>)Query(sql);
}
/// <summary>
/// This will return an Expando as a Dictionary
/// </summary>
public virtual IDictionary<string, object> ItemAsDictionary(ExpandoObject item)
{
return (IDictionary<string, object>)item;
}
/// <summary>
/// This will return an MassiveExpando as a Dictionary
/// </summary>
public virtual IDictionary<string, object> ItemAsDictionary(MassiveExpando item)
{
return (IDictionary<string, object>)item;
}
//Checks to see if a key is present based on the passed-in value
public virtual bool ItemContainsKey(string key, ExpandoObject item)
{
var dc = ItemAsDictionary(item);
return dc.ContainsKey(key);
}
//Checks to see if a key is present based on the passed-in value
public virtual bool ItemContainsKey(string key, MassiveExpando item)
{
var dc = ItemAsDictionary(item);
return dc.ContainsKey(key);
}
/// <summary>
/// Executes a set of objects as Insert or Update commands based on their property settings, within a transaction.
/// These objects can be POCOs, Anonymous, NameValueCollections, Dictionary or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual int Save(params object[] things)
{
foreach (var item in things)
{
if (!IsValid(item.ToExpando()))
{
throw new InvalidOperationException("Can't save this item: " + String.Join("; ", Errors.ToArray()));
}
}
var commands = BuildCommands(things);
return Execute(commands);
}
public virtual DbCommand CreateInsertCommand(dynamic expando)
{
DbCommand result = null;
var settings = (IDictionary<string, object>)expando;
var sbKeys = new StringBuilder();
var sbVals = new StringBuilder();
var stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})";
result = CreateCommand(stub, null);
int counter = 0;
bool containsKey = HasPrimaryKey(expando);
if (!containsKey || !IsPrimaryKeyIdentity)
{
foreach (var item in settings)
{
sbKeys.AppendFormat("{0},", item.Key);
sbVals.AppendFormat("@{0},", counter.ToString());
result.AddParam(item.Value);
counter++;
}
}
else
{
foreach (var item in settings)
{
if (item.Key != PrimaryKeyField)
{
sbKeys.AppendFormat("{0},", item.Key);
sbVals.AppendFormat("@{0},", counter.ToString());
result.AddParam(item.Value);
counter++;
}
}
}
if (counter > 0)
{
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 1);
var vals = sbVals.ToString().Substring(0, sbVals.Length - 1);
var sql = string.Format(stub, TableName, keys, vals);
result.CommandText = sql;
}
else throw new InvalidOperationException("Can't parse this object to the database - there are no properties set");
return result;
}
/// <summary>
/// Creates a command for use with transactions - internal stuff mostly, but here for you to play with
/// </summary>
public virtual DbCommand CreateUpdateCommand(dynamic expando, object key)
{
var settings = (IDictionary<string, object>)expando;
var sbKeys = new StringBuilder();
var stub = "UPDATE {0} SET {1} WHERE {2} = @{3}";
var args = new List<object>();
var result = CreateCommand(stub, null);
int counter = 0;
foreach (var item in settings)
{
var val = item.Value;
if (!item.Key.Equals(PrimaryKeyField, StringComparison.OrdinalIgnoreCase) && item.Value != null)
{
result.AddParam(val);
sbKeys.AppendFormat("{0} = @{1}, \r\n", item.Key, counter.ToString());
counter++;
}
}
if (counter > 0)
{
//add the key
result.AddParam(key);
//strip the last commas
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 4);
result.CommandText = string.Format(stub, TableName, keys, PrimaryKeyField, counter);
}
else throw new InvalidOperationException("No parsable object was sent in - could not divine any name/value pairs");
return result;
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public virtual DbCommand CreateDeleteCommand(string where = "", object key = null, params object[] args)
{
var sql = string.Format("DELETE FROM {0} ", TableName);
if (key != null)
{
sql += string.Format("WHERE {0}=@0", PrimaryKeyField);
args = new object[] { key };
}
else if (!string.IsNullOrEmpty(where))
{
sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where;
}
return CreateCommand(sql, null, args);
}
public bool IsValid(dynamic item)
{
Errors.Clear();
Validate(item);
return Errors.Count == 0;
}
//Temporary holder for error messages
public IList<string> Errors = new List<string>();
/// <summary>
/// Adds a record to the database. You can pass in an Anonymous object, an MassiveExpando, an IDictionary<string, object>,
/// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString
/// </summary>
public virtual dynamic Insert(object o)
{
var ex = o.ToExpando();
if (!IsValid(ex))
{
throw new InvalidOperationException("Can't insert: " + String.Join("; ", Errors.ToArray()));
}
if (BeforeSave(ex))
{
using (dynamic conn = OpenConnection())
{
var cmd = CreateInsertCommand(ex);
cmd.Connection = conn;
//cmd.ExecuteNonQuery();
cmd.CommandText += ";SELECT SCOPE_IDENTITY() as newID";
ex.ID = cmd.ExecuteScalar();
Inserted(ex);
}
return ex;
}
else
{
return null;
}
}
/// <summary>
/// Updates a record in the database. You can pass in an Anonymous object, an MassiveExpando, an IDictionary<string, object>,
/// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString
/// </summary>
public virtual int Update(object o, object key)
{
var ex = o.ToExpando();
if (!IsValid(ex))
{
throw new InvalidOperationException("Can't Update: " + String.Join("; ", Errors.ToArray()));
}
var result = 0;
if (BeforeSave(ex))
{
result = Execute(CreateUpdateCommand(ex, key));
Updated(ex);
}
return result;
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public int Delete(object key = null, string where = "", params object[] args)
{
var deleted = this.Single(key);
var result = 0;
if (BeforeDelete(deleted))
{
result = Execute(CreateDeleteCommand(where: where, key: key, args: args));
Deleted(deleted);
}
return result;
}
public void DefaultTo(string key, object value, dynamic item)
{
if (!ItemContainsKey(key, item))
{
var dc = (IDictionary<string, object>)item;
dc[key] = value;
}
}
/// <summary>
/// insert(when key not exist in table) or update(when key exsits in table) a record in database. remember: the db table shall contain one Non-Identity PK field, and the passed-in object's PK field shall have value. You can pass in an Anonymous object, an MassiveExpando, an IDictionary<string, object>,
/// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public bool InsertOrUpdate(object o)
{
bool containsPK = HasPrimaryKey(o);
if (!containsPK)
{
throw new InvalidOperationException("the object passed-in does not include a primary key");
}
bool isIdentity = this.IsPrimaryKeyIdentity;
if (isIdentity)
{
throw new InvalidOperationException("the primary key should not be an Identity");
}
object key = GetPrimaryKey(o);
var single = this.Single(key);
if (single == null)
{
var inserted = this.Insert(o);
return true;
}
else
{
this.Update(o, key);
return true;
}
}
//Hooks
public virtual void Validate(dynamic item) { }
public virtual void Inserted(dynamic item) { }
public virtual void Updated(dynamic item) { }
public virtual void Deleted(dynamic item) { }
public virtual bool BeforeDelete(dynamic item) { return true; }
public virtual bool BeforeSave(dynamic item) { return true; }