diff --git a/AmalgamationTool/DynamORM.Amalgamation.cs b/AmalgamationTool/DynamORM.Amalgamation.cs index 2da2823..88f5e32 100644 --- a/AmalgamationTool/DynamORM.Amalgamation.cs +++ b/AmalgamationTool/DynamORM.Amalgamation.cs @@ -44,7 +44,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.Collections; -using System.ComponentModel; using System.Data.Common; using System.Data; using System.Dynamic; @@ -3876,7 +3875,7 @@ namespace DynamORM { typeof(Guid?), DbType.Guid }, { typeof(DateTime?), DbType.DateTime }, { typeof(TimeSpan?), DbType.Time }, - { typeof(DateTimeOffset?), DbType.DateTimeOffset } + { typeof(DateTimeOffset?), DbType.DateTimeOffset }, }; #endregion Type column map @@ -4072,9 +4071,9 @@ namespace DynamORM p.DbType = TypeMap.TryGetNullable(type) ?? DbType.String; if (type == typeof(DynamicExpando) || type == typeof(ExpandoObject)) - p.Value = ((IDictionary)item).Values.FirstOrDefault(); + p.Value = CorrectValue(p.DbType, ((IDictionary)item).Values.FirstOrDefault()); else - p.Value = item; + p.Value = CorrectValue(p.DbType, item); if (p.DbType == DbType.String) p.Size = item.ToString().Length > 4000 ? -1 : 4000; @@ -4114,7 +4113,7 @@ namespace DynamORM p.Scale = 4; } - p.Value = value == null ? DBNull.Value : value; + p.Value = CorrectValue(p.DbType, value); } else if (value == null || value == DBNull.Value) p.Value = DBNull.Value; @@ -4127,7 +4126,7 @@ namespace DynamORM else if (p.DbType == DbType.String) p.Size = value.ToString().Length > 4000 ? -1 : 4000; - p.Value = value; + p.Value = CorrectValue(p.DbType, value); } cmd.Parameters.Add(p); @@ -4135,6 +4134,24 @@ namespace DynamORM return cmd; } + private static object CorrectValue(DbType type, object value) + { + if (value == null || value == DBNull.Value) + return DBNull.Value; + + if ((type == DbType.String || type == DbType.AnsiString || type == DbType.StringFixedLength || type == DbType.AnsiStringFixedLength) && + !(value is string)) + return value.ToString(); + else if (type == DbType.Guid && value is string) + return Guid.Parse(value.ToString()); + else if (type == DbType.Guid && value is byte[] && ((byte[])value).Length == 16) + return new Guid((byte[])value); + else if (type == DbType.DateTime && value is TimeSpan) // HACK: This is specific for SQL Server, to be verified with other databases + return DateTime.Today.Add((TimeSpan)value); + + return value; + } + /// Extension for adding single parameter determining only type of object. /// Command to handle. /// Query builder containing schema. @@ -4167,7 +4184,7 @@ namespace DynamORM p.Scale = 4; } - p.Value = item.Value == null ? DBNull.Value : item.Value; + p.Value = item.Value == null ? DBNull.Value : CorrectValue(p.DbType, item.Value); } else if (item.Value == null || item.Value == DBNull.Value) p.Value = DBNull.Value; @@ -4180,7 +4197,7 @@ namespace DynamORM else if (p.DbType == DbType.String) p.Size = item.Value.ToString().Length > 4000 ? -1 : 4000; - p.Value = item.Value; + p.Value = CorrectValue(p.DbType, item.Value); } cmd.Parameters.Add(p); @@ -4207,7 +4224,7 @@ namespace DynamORM param.Size = size; param.Precision = precision; param.Scale = scale; - param.Value = value; + param.Value = CorrectValue(param.DbType, value); command.Parameters.Add(param); return command; @@ -4253,7 +4270,7 @@ namespace DynamORM param.DbType = databaseType; param.Precision = precision; param.Scale = scale; - param.Value = value; + param.Value = CorrectValue(param.DbType, value); command.Parameters.Add(param); return command; @@ -4274,7 +4291,7 @@ namespace DynamORM param.DbType = databaseType; param.Precision = precision; param.Scale = scale; - param.Value = value; + param.Value = CorrectValue(param.DbType, value); command.Parameters.Add(param); return command; @@ -4314,7 +4331,7 @@ namespace DynamORM param.Direction = parameterDirection; param.DbType = databaseType; param.Size = size; - param.Value = value ?? DBNull.Value; + param.Value = CorrectValue(param.DbType, value ?? DBNull.Value); command.Parameters.Add(param); return command; @@ -4333,7 +4350,7 @@ namespace DynamORM param.ParameterName = parameterName; param.DbType = databaseType; param.Size = size; - param.Value = value ?? DBNull.Value; + param.Value = CorrectValue(param.DbType, value ?? DBNull.Value); command.Parameters.Add(param); return command; @@ -4350,7 +4367,7 @@ namespace DynamORM IDbDataParameter param = command.CreateParameter(); param.ParameterName = parameterName; param.DbType = databaseType; - param.Value = value ?? DBNull.Value; + param.Value = CorrectValue(param.DbType, value ?? DBNull.Value); command.Parameters.Add(param); return command; @@ -4401,7 +4418,8 @@ namespace DynamORM { try { - ((IDbDataParameter)command.Parameters[parameterName]).Value = value; + var p = ((IDbDataParameter)command.Parameters[parameterName]); + p.Value = CorrectValue(p.DbType, value); } catch (Exception ex) { @@ -4420,7 +4438,8 @@ namespace DynamORM { try { - ((IDbDataParameter)command.Parameters[index]).Value = value; + var p = ((IDbDataParameter)command.Parameters[index]); + p.Value = CorrectValue(p.DbType, value); } catch (Exception ex) { @@ -4507,7 +4526,7 @@ namespace DynamORM }); if (method != null) - ret = o.ToString().TryParseDefault(defaultValue, delegate(string v, out T r) + ret = o.ToString().TryParseDefault(defaultValue, delegate (string v, out T r) { r = defaultValue; return (bool)method.Invoke(null, new object[] { v, r }); @@ -4566,7 +4585,7 @@ namespace DynamORM else if (typeof(T) == typeof(object)) ret = (T)o; else if (method != null) - ret = o.ToString().TryParseDefault(defaultValue, delegate(string v, out T r) + ret = o.ToString().TryParseDefault(defaultValue, delegate (string v, out T r) { r = defaultValue; return (bool)method.Invoke(null, new object[] { v, r }); @@ -4627,7 +4646,7 @@ namespace DynamORM param.Scale, param.Precision, param.Scale, - param.Value is byte[] ? ConvertByteArrayToHexString((byte[])param.Value) : param.Value ?? "NULL", + param.Value is byte[]? ConvertByteArrayToHexString((byte[])param.Value) : param.Value ?? "NULL", param.Value != null ? param.Value.GetType().Name : "DBNull"); } @@ -4806,7 +4825,7 @@ namespace DynamORM public static List ToList(this IDataReader r) { List result = new List(); - + while (r.Read()) result.Add(r.RowToDynamic()); @@ -7134,7 +7153,7 @@ namespace DynamORM } namespace Builders - { + { /// Dynamic delete query builder interface. /// This interface it publicly available. Implementation should be hidden. public interface IDynamicDeleteQueryBuilder : IDynamicQueryBuilder @@ -7142,7 +7161,7 @@ namespace DynamORM /// Execute this builder. /// Result of an execution.. int Execute(); - + /// /// Adds to the 'Where' clause the contents obtained from parsing the dynamic lambda expression given. The condition /// is parsed to the appropriate syntax, where the specific customs virtual methods supported by the parser are used @@ -7154,25 +7173,25 @@ namespace DynamORM /// The specification. /// This instance to permit chaining. IDynamicDeleteQueryBuilder Where(Func func); - + /// Add where condition. /// Condition column with operator and value. /// Builder instance. IDynamicDeleteQueryBuilder Where(DynamicColumn column); - + /// Add where condition. /// Condition column. /// Condition operator. /// Condition value. /// Builder instance. IDynamicDeleteQueryBuilder Where(string column, DynamicColumn.CompareOperator op, object value); - + /// Add where condition. /// Condition column. /// Condition value. /// Builder instance. IDynamicDeleteQueryBuilder Where(string column, object value); - + /// Add where condition. /// Set conditions as properties and values of an object. /// If true use schema to determine key columns and ignore those which @@ -7180,7 +7199,7 @@ namespace DynamORM /// Builder instance. IDynamicDeleteQueryBuilder Where(object conditions, bool schema = false); } - + /// Dynamic insert query builder interface. /// This interface it publicly available. Implementation should be hidden. public interface IDynamicInsertQueryBuilder : IDynamicQueryBuilder @@ -7188,7 +7207,7 @@ namespace DynamORM /// Execute this builder. /// Result of an execution.. int Execute(); - + /// /// Specifies the columns to insert using the dynamic lambda expressions given. Each expression correspond to one /// column, and can: @@ -7199,59 +7218,59 @@ namespace DynamORM /// The specifications. /// This instance to permit chaining. IDynamicInsertQueryBuilder Values(Func fn, params Func[] func); - + /// Add insert fields. /// Insert column. /// Insert value. /// Builder instance. IDynamicInsertQueryBuilder Insert(string column, object value); - + /// Add insert fields. /// Set insert value as properties and values of an object. /// Builder instance. IDynamicInsertQueryBuilder Insert(object o); } - + /// Dynamic query builder base interface. /// This interface it publicly available. Implementation should be hidden. public interface IDynamicQueryBuilder : IExtendedDisposable { /// Gets instance. DynamicDatabase Database { get; } - + /// Gets tables information. IList Tables { get; } - + /// Gets the tables used in this builder. IDictionary Parameters { get; } - + /// Gets or sets a value indicating whether add virtual parameters. bool VirtualMode { get; set; } - + /// Gets a value indicating whether database supports standard schema. bool SupportSchema { get; } - + /// Fill command with query. /// Command to fill. /// Filled instance of . IDbCommand FillCommand(IDbCommand command); - + /// /// Generates the text this command will execute against the underlying database. /// /// The text to execute against the underlying database. /// This method must be override by derived classes. string CommandText(); - + /// Gets or sets the on create temporary parameter actions. /// This is exposed to allow setting schema of column. List> OnCreateTemporaryParameter { get; set; } - + /// Gets or sets the on create real parameter actions. /// This is exposed to allow modification of parameter. List> OnCreateParameter { get; set; } } - + /// Dynamic select query builder interface. /// This interface it publicly available. Implementation should be hidden. public interface IDynamicSelectQueryBuilder : IDynamicQueryBuilder ////, IEnumerable @@ -7259,32 +7278,32 @@ namespace DynamORM /// Execute this builder. /// Enumerator of objects expanded from query. IEnumerable Execute(); - + /// Execute this builder and map to given type. /// Type of object to map on. /// Enumerator of objects expanded from query. IEnumerable Execute() where T : class; - + /// Execute this builder as a data reader. /// Action containing reader. void ExecuteDataReader(Action reader); - + /// Returns a single result. /// Result of a query. object Scalar(); - - #if !DYNAMORM_OMMIT_GENERICEXECUTION && !DYNAMORM_OMMIT_TRYPARSE - + +#if !DYNAMORM_OMMIT_GENERICEXECUTION && !DYNAMORM_OMMIT_TRYPARSE + /// Returns a single result. /// Type to parse to. /// Default value. /// Result of a query. T ScalarAs(T defaultValue = default(T)); - - #endif - + +#endif + #region From/Join - + /// /// Adds to the 'From' clause the contents obtained by parsing the dynamic lambda expressions given. The supported /// formats are: @@ -7297,7 +7316,7 @@ namespace DynamORM /// The specification. /// This instance to permit chaining. IDynamicSelectQueryBuilder From(Func fn, params Func[] func); - + /// /// Adds to the 'Join' clause the contents obtained by parsing the dynamic lambda expressions given. The supported /// formats are: @@ -7315,11 +7334,11 @@ namespace DynamORM /// The specification. /// This instance to permit chaining. IDynamicSelectQueryBuilder Join(params Func[] func); - + #endregion From/Join - + #region Where - + /// /// Adds to the 'Where' clause the contents obtained from parsing the dynamic lambda expression given. The condition /// is parsed to the appropriate syntax, where the specific customs virtual methods supported by the parser are used @@ -7331,36 +7350,36 @@ namespace DynamORM /// The specification. /// This instance to permit chaining. IDynamicSelectQueryBuilder Where(Func func); - + /// Add where condition. /// Condition column with operator and value. /// Builder instance. IDynamicSelectQueryBuilder Where(DynamicColumn column); - + /// Add where condition. /// Condition column. /// Condition operator. /// Condition value. /// Builder instance. IDynamicSelectQueryBuilder Where(string column, DynamicColumn.CompareOperator op, object value); - + /// Add where condition. /// Condition column. /// Condition value. /// Builder instance. IDynamicSelectQueryBuilder Where(string column, object value); - + /// Add where condition. /// Set conditions as properties and values of an object. /// If true use schema to determine key columns and ignore those which /// aren't keys. /// Builder instance. IDynamicSelectQueryBuilder Where(object conditions, bool schema = false); - + #endregion Where - + #region Select - + /// /// Adds to the 'Select' clause the contents obtained by parsing the dynamic lambda expressions given. The supported /// formats are: @@ -7374,23 +7393,23 @@ namespace DynamORM /// The specification. /// This instance to permit chaining. IDynamicSelectQueryBuilder Select(Func fn, params Func[] func); - + /// Add select columns. /// Columns to add to object. /// Builder instance. IDynamicSelectQueryBuilder SelectColumn(params DynamicColumn[] columns); - + /// Add select columns. /// Columns to add to object. /// Column format consist of Column Name, Alias and /// Aggregate function in this order separated by ':'. /// Builder instance. IDynamicSelectQueryBuilder SelectColumn(params string[] columns); - + #endregion Select - + #region GroupBy - + /// /// Adds to the 'Group By' clause the contents obtained from from parsing the dynamic lambda expression given. /// @@ -7398,23 +7417,23 @@ namespace DynamORM /// The specification. /// This instance to permit chaining. IDynamicSelectQueryBuilder GroupBy(Func fn, params Func[] func); - + /// Add select columns. /// Columns to group by. /// Builder instance. IDynamicSelectQueryBuilder GroupByColumn(params DynamicColumn[] columns); - + /// Add select columns. /// Columns to group by. /// Column format consist of Column Name and /// Alias in this order separated by ':'. /// Builder instance. IDynamicSelectQueryBuilder GroupByColumn(params string[] columns); - + #endregion GroupBy - + #region Having - + /// /// Adds to the 'Having' clause the contents obtained from parsing the dynamic lambda expression given. The condition /// is parsed to the appropriate syntax, Having the specific customs virtual methods supported by the parser are used @@ -7426,36 +7445,36 @@ namespace DynamORM /// The specification. /// This instance to permit chaining. IDynamicSelectQueryBuilder Having(Func func); - + /// Add Having condition. /// Condition column with operator and value. /// Builder instance. IDynamicSelectQueryBuilder Having(DynamicColumn column); - + /// Add Having condition. /// Condition column. /// Condition operator. /// Condition value. /// Builder instance. IDynamicSelectQueryBuilder Having(string column, DynamicColumn.CompareOperator op, object value); - + /// Add Having condition. /// Condition column. /// Condition value. /// Builder instance. IDynamicSelectQueryBuilder Having(string column, object value); - + /// Add Having condition. /// Set conditions as properties and values of an object. /// If true use schema to determine key columns and ignore those which /// aren't keys. /// Builder instance. IDynamicSelectQueryBuilder Having(object conditions, bool schema = false); - + #endregion Having - + #region OrderBy - + /// /// Adds to the 'Order By' clause the contents obtained from from parsing the dynamic lambda expression given. It /// accepts a multipart column specification followed by an optional Ascending() or Descending() virtual methods @@ -7466,46 +7485,46 @@ namespace DynamORM /// The specification. /// This instance to permit chaining. IDynamicSelectQueryBuilder OrderBy(Func fn, params Func[] func); - + /// Add select columns. /// Columns to order by. /// Builder instance. IDynamicSelectQueryBuilder OrderByColumn(params DynamicColumn[] columns); - + /// Add select columns. /// Columns to order by. /// Column format consist of Column Name and /// Alias in this order separated by ':'. /// Builder instance. IDynamicSelectQueryBuilder OrderByColumn(params string[] columns); - + #endregion OrderBy - + #region Top/Limit/Offset/Distinct - + /// Set top if database support it. /// How many objects select. /// Builder instance. IDynamicSelectQueryBuilder Top(int? top); - + /// Set top if database support it. /// How many objects select. /// Builder instance. IDynamicSelectQueryBuilder Limit(int? limit); - + /// Set top if database support it. /// How many objects skip selecting. /// Builder instance. IDynamicSelectQueryBuilder Offset(int? offset); - + /// Set distinct mode. /// Distinct mode. /// Builder instance. IDynamicSelectQueryBuilder Distinct(bool distinct = true); - + #endregion Top/Limit/Offset/Distinct } - + /// Dynamic update query builder interface. /// This interface it publicly available. Implementation should be hidden. public interface IDynamicUpdateQueryBuilder : IDynamicQueryBuilder @@ -7513,24 +7532,24 @@ namespace DynamORM /// Execute this builder. /// Result of an execution.. int Execute(); - + #region Update - + /// Add update value or where condition using schema. /// Update or where column name. /// Column value. /// Builder instance. IDynamicUpdateQueryBuilder Update(string column, object value); - + /// Add update values and where condition columns using schema. /// Set values or conditions as properties and values of an object. /// Builder instance. IDynamicUpdateQueryBuilder Update(object conditions); - + #endregion Update - + #region Values - + /// /// Specifies the columns to update using the dynamic lambda expressions given. Each expression correspond to one /// column, and can: @@ -7540,22 +7559,22 @@ namespace DynamORM /// The specifications. /// This instance to permit chaining. IDynamicUpdateQueryBuilder Set(params Func[] func); - + /// Add insert fields. /// Insert column. /// Insert value. /// Builder instance. IDynamicUpdateQueryBuilder Values(string column, object value); - + /// Add insert fields. /// Set insert value as properties and values of an object. /// Builder instance. IDynamicUpdateQueryBuilder Values(object o); - + #endregion Values - + #region Where - + /// /// Adds to the 'Where' clause the contents obtained from parsing the dynamic lambda expression given. The condition /// is parsed to the appropriate syntax, where the specific customs virtual methods supported by the parser are used @@ -7567,102 +7586,102 @@ namespace DynamORM /// The specification. /// This instance to permit chaining. IDynamicUpdateQueryBuilder Where(Func func); - + /// Add where condition. /// Condition column with operator and value. /// Builder instance. IDynamicUpdateQueryBuilder Where(DynamicColumn column); - + /// Add where condition. /// Condition column. /// Condition operator. /// Condition value. /// Builder instance. IDynamicUpdateQueryBuilder Where(string column, DynamicColumn.CompareOperator op, object value); - + /// Add where condition. /// Condition column. /// Condition value. /// Builder instance. IDynamicUpdateQueryBuilder Where(string column, object value); - + /// Add where condition. /// Set conditions as properties and values of an object. /// If true use schema to determine key columns and ignore those which /// aren't keys. /// Builder instance. IDynamicUpdateQueryBuilder Where(object conditions, bool schema = false); - + #endregion Where } - + /// Interface describing parameter info. public interface IParameter : IExtendedDisposable { /// Gets the parameter position in command. /// Available after filling the command. int Ordinal { get; } - + /// Gets the parameter temporary name. string Name { get; } - + /// Gets or sets the parameter value. object Value { get; set; } - + /// Gets or sets a value indicating whether name of temporary parameter is well known. bool WellKnown { get; set; } - + /// Gets or sets a value indicating whether this is virtual. bool Virtual { get; set; } - + /// Gets or sets the parameter schema information. DynamicSchemaColumn? Schema { get; set; } } - + /// Interface describing table information. public interface ITableInfo : IExtendedDisposable { /// Gets table owner name. string Owner { get; } - + /// Gets table name. string Name { get; } - + /// Gets table alias. string Alias { get; } - + /// Gets table no lock status. bool NoLock { get; } - + /// Gets table schema. Dictionary Schema { get; } } namespace Extensions - { + { internal static class DynamicHavingQueryExtensions { #region Where - + internal static T InternalHaving(this T builder, Func func) where T : DynamicQueryBuilder, DynamicQueryBuilder.IQueryWithHaving { return builder.InternalHaving(false, false, func); } - + internal static T InternalHaving(this T builder, bool addBeginBrace, bool addEndBrace, Func func) where T : DynamicQueryBuilder, DynamicQueryBuilder.IQueryWithHaving { if (func == null) throw new ArgumentNullException("Array of functions cannot be null."); - + using (DynamicParser parser = DynamicParser.Parse(func)) { string condition = null; bool and = true; - + object result = parser.Result; if (result is string) { condition = (string)result; - + if (condition.ToUpper().IndexOf("OR") == 0) { and = false; @@ -7685,19 +7704,19 @@ namespace DynamORM object[] args = ((DynamicParser.Node.Method)node).Arguments; if (args == null) throw new ArgumentNullException("arg", string.Format("{0} is not a parameterless method.", name)); if (args.Length != 1) throw new ArgumentException(string.Format("{0} requires one and only one parameter: {1}.", name, args.Sketch())); - + and = name == "AND" ? true : false; result = args[0]; } } - + // Just parsing the contents now... condition = builder.Parse(result, pars: builder.Parameters).Validated("Where condition"); } - + if (addBeginBrace) builder.HavingOpenBracketsCount++; if (addEndBrace) builder.HavingOpenBracketsCount--; - + if (builder.HavingCondition == null) builder.HavingCondition = string.Format("{0}{1}{2}", addBeginBrace ? "(" : string.Empty, condition, addEndBrace ? ")" : string.Empty); @@ -7705,27 +7724,27 @@ namespace DynamORM builder.HavingCondition = string.Format("{0} {1} {2}{3}{4}", builder.HavingCondition, and ? "AND" : "OR", addBeginBrace ? "(" : string.Empty, condition, addEndBrace ? ")" : string.Empty); } - + return builder; } - + internal static T InternalHaving(this T builder, DynamicColumn column) where T : DynamicQueryBuilder, DynamicQueryBuilder.IQueryWithHaving { bool virt = builder.VirtualMode; if (column.VirtualColumn.HasValue) builder.VirtualMode = column.VirtualColumn.Value; - + Action modParam = (p) => { if (column.Schema.HasValue) p.Schema = column.Schema; - + if (!p.Schema.HasValue) p.Schema = column.Schema ?? builder.GetColumnFromSchema(column.ColumnName); }; - + builder.CreateTemporaryParameterAction(modParam); - + // It's kind of uglu, but... well it works. if (column.Or) switch (column.Operator) @@ -7757,32 +7776,32 @@ namespace DynamORM case DynamicColumn.CompareOperator.Gte: builder.InternalHaving(column.BeginBlock, column.EndBlock, x => x(builder.FixObjectName(column.ColumnName)) >= column.Value); break; case DynamicColumn.CompareOperator.Between: builder.InternalHaving(column.BeginBlock, column.EndBlock, x => x(builder.FixObjectName(column.ColumnName)).Between(column.Value)); break; } - + builder.OnCreateTemporaryParameter.Remove(modParam); builder.VirtualMode = virt; - + return builder; } - + internal static T InternalHaving(this T builder, string column, DynamicColumn.CompareOperator op, object value) where T : DynamicQueryBuilder, DynamicQueryBuilder.IQueryWithHaving { if (value is DynamicColumn) { DynamicColumn v = (DynamicColumn)value; - + if (string.IsNullOrEmpty(v.ColumnName)) v.ColumnName = column; - + return builder.InternalHaving(v); } else if (value is IEnumerable) { foreach (DynamicColumn v in (IEnumerable)value) builder.InternalHaving(v); - + return builder; } - + return builder.InternalHaving(new DynamicColumn { ColumnName = column, @@ -7790,12 +7809,12 @@ namespace DynamORM Value = value }); } - + internal static T InternalHaving(this T builder, string column, object value) where T : DynamicQueryBuilder, DynamicQueryBuilder.IQueryWithHaving { return builder.InternalHaving(column, DynamicColumn.CompareOperator.Eq, value); } - + internal static T InternalHaving(this T builder, object conditions, bool schema = false) where T : DynamicQueryBuilder, DynamicQueryBuilder.IQueryWithHaving { if (conditions is DynamicColumn) @@ -7804,58 +7823,58 @@ namespace DynamORM { foreach (DynamicColumn v in (IEnumerable)conditions) builder.InternalHaving(v); - + return builder; } - + IDictionary dict = conditions.ToDictionary(); DynamicTypeMap mapper = DynamicMapperCache.GetMapper(conditions.GetType()); string table = dict.TryGetValue("_table").NullOr(x => x.ToString(), string.Empty); - + foreach (KeyValuePair condition in dict) { if (mapper.Ignored.Contains(condition.Key) || condition.Key == "_table") continue; - + string colName = mapper != null ? mapper.PropertyMap.TryGetValue(condition.Key) ?? condition.Key : condition.Key; - + DynamicSchemaColumn? col = null; - + // This should be used on typed queries or update/delete steatements, which usualy operate on a single table. if (schema) { col = builder.GetColumnFromSchema(colName, mapper, table); - + if ((!col.HasValue || !col.Value.IsKey) && (mapper == null || mapper.ColumnsMap.TryGetValue(colName).NullOr(m => m.Ignore || m.Column.NullOr(c => !c.IsKey, true), true))) continue; - + colName = col.HasValue ? col.Value.Name : colName; } - + if (!string.IsNullOrEmpty(table)) builder.InternalHaving(x => x(builder.FixObjectName(string.Format("{0}.{1}", table, colName))) == condition.Value); else builder.InternalHaving(x => x(builder.FixObjectName(colName)) == condition.Value); } - + return builder; } - + #endregion Where } - + internal static class DynamicModifyBuilderExtensions { internal static T Table(this T builder, Func func) where T : DynamicModifyBuilder { if (func == null) throw new ArgumentNullException("Function cannot be null."); - + using (DynamicParser parser = DynamicParser.Parse(func)) { object result = parser.Result; - + // If the expression result is string. if (result is string) return builder.Table((string)result); @@ -7865,38 +7884,38 @@ namespace DynamORM { // Or if it resolves to a dynamic node DynamicParser.Node node = (DynamicParser.Node)result; - + string owner = null; string main = null; - + while (true) { // Deny support for the AS() virtual method... if (node is DynamicParser.Node.Method && ((DynamicParser.Node.Method)node).Name.ToUpper() == "AS") throw new ArgumentException(string.Format("Alias is not supported on modification builders. (Parsing: {0})", result)); - + // Support for table specifications... if (node is DynamicParser.Node.GetMember) { if (owner != null) throw new ArgumentException(string.Format("Owner '{0}.{1}' is already set when parsing '{2}'.", owner, main, result)); - + if (main != null) owner = ((DynamicParser.Node.GetMember)node).Name; else main = ((DynamicParser.Node.GetMember)node).Name; - + node = node.Host; continue; } - + // Support for generic sources... if (node is DynamicParser.Node.Invoke) { if (owner == null && main == null) { DynamicParser.Node.Invoke invoke = (DynamicParser.Node.Invoke)node; - + if (invoke.Arguments.Length == 1 && invoke.Arguments[0] is Type) return builder.Table((Type)invoke.Arguments[0]); else if (invoke.Arguments.Length == 1 && invoke.Arguments[0] is String) @@ -7909,51 +7928,51 @@ namespace DynamORM else if (main != null) throw new ArgumentException(string.Format("Main '{0}' is already set when parsing '{1}'.", main, result)); } - + if (!string.IsNullOrEmpty(main)) return builder.Table(string.Format("{0}{1}", string.IsNullOrEmpty(owner) ? string.Empty : string.Format("{0}.", owner), main)); } } - + throw new ArgumentException(string.Format("Unable to set table parsing '{0}'", result)); } } - + internal static T Table(this T builder, string tableName, Dictionary schema = null) where T : DynamicModifyBuilder { Tuple tuple = tableName.Validated("Table Name").SplitSomethingAndAlias(); - + if (!string.IsNullOrEmpty(tuple.Item2)) throw new ArgumentException(string.Format("Can not use aliases in INSERT steatement. ({0})", tableName), "tableName"); - + string[] parts = tuple.Item1.Split('.'); - + if (parts.Length > 2) throw new ArgumentException(string.Format("Table name can consist only from name or owner and name. ({0})", tableName), "tableName"); - + builder.Tables.Clear(); builder.Tables.Add(new DynamicQueryBuilder.TableInfo(builder.Database, builder.Database.StripName(parts.Last()).Validated("Table"), null, parts.Length == 2 ? builder.Database.StripName(parts.First()).Validated("Owner", canbeNull: true) : null)); - + if (schema != null) (builder.Tables[0] as DynamicQueryBuilder.TableInfo).Schema = schema; - + return builder; } - + internal static T Table(this T builder, Type type) where T : DynamicQueryBuilder { if (type.IsAnonymous()) throw new InvalidOperationException(string.Format("Cant assign anonymous type as a table ({0}).", type.FullName)); - + DynamicTypeMap mapper = DynamicMapperCache.GetMapper(type); - + if (mapper == null) throw new InvalidOperationException("Cant assign unmapable type as a table."); - + if (builder is DynamicModifyBuilder) { builder.Tables.Clear(); @@ -7961,34 +7980,34 @@ namespace DynamORM } else if (builder is DynamicSelectQueryBuilder) (builder as DynamicSelectQueryBuilder).From(x => x(type)); - + return builder; } } - + internal static class DynamicWhereQueryExtensions { #region Where - + internal static T InternalWhere(this T builder, Func func) where T : DynamicQueryBuilder, DynamicQueryBuilder.IQueryWithWhere { return builder.InternalWhere(false, false, func); } - + internal static T InternalWhere(this T builder, bool addBeginBrace, bool addEndBrace, Func func) where T : DynamicQueryBuilder, DynamicQueryBuilder.IQueryWithWhere { if (func == null) throw new ArgumentNullException("Array of functions cannot be null."); - + using (DynamicParser parser = DynamicParser.Parse(func)) { string condition = null; bool and = true; - + object result = parser.Result; if (result is string) { condition = (string)result; - + if (condition.ToUpper().IndexOf("OR") == 0) { and = false; @@ -8011,19 +8030,19 @@ namespace DynamORM object[] args = ((DynamicParser.Node.Method)node).Arguments; if (args == null) throw new ArgumentNullException("arg", string.Format("{0} is not a parameterless method.", name)); if (args.Length != 1) throw new ArgumentException(string.Format("{0} requires one and only one parameter: {1}.", name, args.Sketch())); - + and = name == "AND" ? true : false; result = args[0]; } } - + // Just parsing the contents now... condition = builder.Parse(result, pars: builder.Parameters).Validated("Where condition"); } - + if (addBeginBrace) builder.WhereOpenBracketsCount++; if (addEndBrace) builder.WhereOpenBracketsCount--; - + if (builder.WhereCondition == null) builder.WhereCondition = string.Format("{0}{1}{2}", addBeginBrace ? "(" : string.Empty, condition, addEndBrace ? ")" : string.Empty); @@ -8031,27 +8050,27 @@ namespace DynamORM builder.WhereCondition = string.Format("{0} {1} {2}{3}{4}", builder.WhereCondition, and ? "AND" : "OR", addBeginBrace ? "(" : string.Empty, condition, addEndBrace ? ")" : string.Empty); } - + return builder; } - + internal static T InternalWhere(this T builder, DynamicColumn column) where T : DynamicQueryBuilder, DynamicQueryBuilder.IQueryWithWhere { bool virt = builder.VirtualMode; if (column.VirtualColumn.HasValue) builder.VirtualMode = column.VirtualColumn.Value; - + Action modParam = (p) => { if (column.Schema.HasValue) p.Schema = column.Schema; - + if (!p.Schema.HasValue) p.Schema = column.Schema ?? builder.GetColumnFromSchema(column.ColumnName); }; - + builder.CreateTemporaryParameterAction(modParam); - + // It's kind of uglu, but... well it works. if (column.Or) switch (column.Operator) @@ -8083,32 +8102,32 @@ namespace DynamORM case DynamicColumn.CompareOperator.Gte: builder.InternalWhere(column.BeginBlock, column.EndBlock, x => x(builder.FixObjectName(column.ColumnName)) >= column.Value); break; case DynamicColumn.CompareOperator.Between: builder.InternalWhere(column.BeginBlock, column.EndBlock, x => x(builder.FixObjectName(column.ColumnName)).Between(column.Value)); break; } - + builder.OnCreateTemporaryParameter.Remove(modParam); builder.VirtualMode = virt; - + return builder; } - + internal static T InternalWhere(this T builder, string column, DynamicColumn.CompareOperator op, object value) where T : DynamicQueryBuilder, DynamicQueryBuilder.IQueryWithWhere { if (value is DynamicColumn) { DynamicColumn v = (DynamicColumn)value; - + if (string.IsNullOrEmpty(v.ColumnName)) v.ColumnName = column; - + return builder.InternalWhere(v); } else if (value is IEnumerable) { foreach (DynamicColumn v in (IEnumerable)value) builder.InternalWhere(v); - + return builder; } - + return builder.InternalWhere(new DynamicColumn { ColumnName = column, @@ -8116,12 +8135,12 @@ namespace DynamORM Value = value }); } - + internal static T InternalWhere(this T builder, string column, object value) where T : DynamicQueryBuilder, DynamicQueryBuilder.IQueryWithWhere { return builder.InternalWhere(column, DynamicColumn.CompareOperator.Eq, value); } - + internal static T InternalWhere(this T builder, object conditions, bool schema = false) where T : DynamicQueryBuilder, DynamicQueryBuilder.IQueryWithWhere { if (conditions is DynamicColumn) @@ -8130,50 +8149,50 @@ namespace DynamORM { foreach (DynamicColumn v in (IEnumerable)conditions) builder.InternalWhere(v); - + return builder; } - + IDictionary dict = conditions.ToDictionary(); DynamicTypeMap mapper = DynamicMapperCache.GetMapper(conditions.GetType()); string table = dict.TryGetValue("_table").NullOr(x => x.ToString(), string.Empty); - + foreach (KeyValuePair condition in dict) { if (mapper.Ignored.Contains(condition.Key) || condition.Key == "_table") continue; - + string colName = mapper != null ? mapper.PropertyMap.TryGetValue(condition.Key) ?? condition.Key : condition.Key; - + DynamicSchemaColumn? col = null; - + // This should be used on typed queries or update/delete steatements, which usualy operate on a single table. if (schema) { col = builder.GetColumnFromSchema(colName, mapper, table); - + if ((!col.HasValue || !col.Value.IsKey) && (mapper == null || mapper.ColumnsMap.TryGetValue(colName).NullOr(m => m.Ignore || m.Column.NullOr(c => !c.IsKey, true), true))) continue; - + colName = col.HasValue ? col.Value.Name : colName; } - + if (!string.IsNullOrEmpty(table)) builder.InternalWhere(x => x(builder.FixObjectName(string.Format("{0}.{1}", table, colName))) == condition.Value); else builder.InternalWhere(x => x(builder.FixObjectName(colName)) == condition.Value); } - + return builder; } - + #endregion Where } } namespace Implementation - { + { /// Implementation of dynamic delete query builder. internal class DynamicDeleteQueryBuilder : DynamicModifyBuilder, IDynamicDeleteQueryBuilder, DynamicQueryBuilder.IQueryWithWhere { @@ -8185,7 +8204,7 @@ namespace DynamORM : base(db) { } - + /// /// Initializes a new instance of the class. /// @@ -8195,7 +8214,7 @@ namespace DynamORM : base(db, tableName) { } - + /// Generates the text this command will execute against the underlying database. /// The text to execute against the underlying database. /// This method must be override by derived classes. @@ -8208,9 +8227,9 @@ namespace DynamORM string.IsNullOrEmpty(WhereCondition) ? string.Empty : " WHERE ", WhereCondition); } - + #region Where - + /// /// Adds to the 'Where' clause the contents obtained from parsing the dynamic lambda expression given. The condition /// is parsed to the appropriate syntax, where the specific customs virtual methods supported by the parser are used @@ -8225,7 +8244,7 @@ namespace DynamORM { return this.InternalWhere(func); } - + /// Add where condition. /// Condition column with operator and value. /// Builder instance. @@ -8233,7 +8252,7 @@ namespace DynamORM { return this.InternalWhere(column); } - + /// Add where condition. /// Condition column. /// Condition operator. @@ -8243,7 +8262,7 @@ namespace DynamORM { return this.InternalWhere(column, op, value); } - + /// Add where condition. /// Condition column. /// Condition value. @@ -8252,7 +8271,7 @@ namespace DynamORM { return this.InternalWhere(column, value); } - + /// Add where condition. /// Set conditions as properties and values of an object. /// If true use schema to determine key columns and ignore those which @@ -8262,16 +8281,16 @@ namespace DynamORM { return this.InternalWhere(conditions, schema); } - + #endregion Where } - + /// Implementation of dynamic insert query builder. internal class DynamicInsertQueryBuilder : DynamicModifyBuilder, IDynamicInsertQueryBuilder { private string _columns; private string _values; - + /// /// Initializes a new instance of the class. /// @@ -8280,7 +8299,7 @@ namespace DynamORM : base(db) { } - + /// /// Initializes a new instance of the class. /// @@ -8290,7 +8309,7 @@ namespace DynamORM : base(db, tableName) { } - + /// Generates the text this command will execute against the underlying database. /// The text to execute against the underlying database. /// This method must be override by derived classes. @@ -8301,9 +8320,9 @@ namespace DynamORM string.IsNullOrEmpty(info.Owner) ? string.Empty : string.Format("{0}.", Database.DecorateName(info.Owner)), Database.DecorateName(info.Name), _columns, _values); } - + #region Insert - + /// /// Specifies the columns to insert using the dynamic lambda expressions given. Each expression correspond to one /// column, and can: @@ -8317,42 +8336,42 @@ namespace DynamORM { if (fn == null) throw new ArgumentNullException("Array of specifications cannot be null."); - + int index = InsertFunc(-1, fn); - + if (func != null) foreach (Func f in func) index = InsertFunc(index, f); - + return this; } - + private int InsertFunc(int index, Func f) { index++; - + if (f == null) throw new ArgumentNullException(string.Format("Specification #{0} cannot be null.", index)); - + using (DynamicParser parser = DynamicParser.Parse(f)) { object result = parser.Result; if (result == null) throw new ArgumentException(string.Format("Specification #{0} resolves to null.", index)); - + string main = null; string value = null; string str = null; - + // When 'x => x.Table.Column = value' or 'x => x.Column = value'... if (result is DynamicParser.Node.SetMember) { DynamicParser.Node.SetMember node = (DynamicParser.Node.SetMember)result; - + DynamicSchemaColumn? col = GetColumnFromSchema(node.Name); main = Database.DecorateName(node.Name); value = Parse(node.Value, ref col, pars: Parameters, nulls: true); - + _columns = _columns == null ? main : string.Format("{0}, {1}", _columns, main); _values = _values == null ? value : string.Format("{0}, {1}", _values, value); return index; @@ -8362,7 +8381,7 @@ namespace DynamORM Insert(result); return index; } - + // Other specifications are considered invalid... string err = string.Format("Specification '{0}' is invalid.", result); str = Parse(result); @@ -8370,7 +8389,7 @@ namespace DynamORM throw new ArgumentException(err); } } - + /// Add insert fields. /// Insert column. /// Insert value. @@ -8380,20 +8399,20 @@ namespace DynamORM if (value is DynamicColumn) { DynamicColumn v = (DynamicColumn)value; - + if (string.IsNullOrEmpty(v.ColumnName)) v.ColumnName = column; - + return Insert(v); } - + return Insert(new DynamicColumn { ColumnName = column, Value = value, }); } - + /// Add insert fields. /// Set insert value as properties and values of an object. /// Builder instance. @@ -8403,19 +8422,19 @@ namespace DynamORM { DynamicColumn column = (DynamicColumn)o; DynamicSchemaColumn? col = column.Schema ?? GetColumnFromSchema(column.ColumnName); - + string main = FixObjectName(column.ColumnName, onlyColumn: true); string value = Parse(column.Value, ref col, pars: Parameters, nulls: true); - + _columns = _columns == null ? main : string.Format("{0}, {1}", _columns, main); _values = _values == null ? value : string.Format("{0}, {1}", _values, value); - + return this; } - + IDictionary dict = o.ToDictionary(); DynamicTypeMap mapper = DynamicMapperCache.GetMapper(o.GetType()); - + if (mapper != null) { foreach (KeyValuePair con in dict) @@ -8423,34 +8442,34 @@ namespace DynamORM { string colName = mapper.PropertyMap.TryGetValue(con.Key) ?? con.Key; DynamicPropertyInvoker propMap = mapper.ColumnsMap.TryGetValue(colName.ToLower()); - + if (propMap == null || propMap.Column == null || !propMap.Column.IsNoInsert) - Insert(colName, con.Value); + Insert(colName, con.Value); // TODO: This probably should get value from mapper } } else foreach (KeyValuePair con in dict) Insert(con.Key, con.Value); - + return this; } - + #endregion Insert - + #region IExtendedDisposable - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. public override void Dispose() { base.Dispose(); - + _columns = _values = null; } - + #endregion IExtendedDisposable } - + /// Base query builder for insert/update/delete statements. internal abstract class DynamicModifyBuilder : DynamicQueryBuilder { @@ -8463,7 +8482,7 @@ namespace DynamORM { VirtualMode = false; } - + /// /// Initializes a new instance of the class. /// @@ -8475,7 +8494,7 @@ namespace DynamORM VirtualMode = false; this.Table(tableName); } - + /// Execute this builder. /// Result of an execution.. public virtual int Execute() @@ -8489,7 +8508,7 @@ namespace DynamORM } } } - + /// Implementation of dynamic query builder base interface. internal abstract class DynamicQueryBuilder : IDynamicQueryBuilder { @@ -8498,25 +8517,25 @@ namespace DynamORM { /// Gets or sets the where condition. string WhereCondition { get; set; } - + /// Gets or sets the amount of not closed brackets in where statement. int WhereOpenBracketsCount { get; set; } } - + /// Empty interface to allow having query builder implementation use universal approach. internal interface IQueryWithHaving { /// Gets or sets the having condition. string HavingCondition { get; set; } - + /// Gets or sets the amount of not closed brackets in having statement. int HavingOpenBracketsCount { get; set; } } - + private DynamicQueryBuilder _parent = null; - + #region TableInfo - + /// Table information. internal class TableInfo : ITableInfo { @@ -8527,7 +8546,7 @@ namespace DynamORM { IsDisposed = false; } - + /// /// Initializes a new instance of the class. /// @@ -8543,11 +8562,11 @@ namespace DynamORM Alias = alias; Owner = owner; NoLock = nolock; - + if (!name.ContainsAny(StringExtensions.InvalidMemberChars)) Schema = db.GetSchema(name, owner: owner); } - + /// /// Initializes a new instance of the class. /// @@ -8560,49 +8579,49 @@ namespace DynamORM : this() { DynamicTypeMap mapper = DynamicMapperCache.GetMapper(type); - + Name = mapper.Table == null || string.IsNullOrEmpty(mapper.Table.Name) ? mapper.Type.Name : mapper.Table.Name; - + Owner = (mapper.Table != null) ? mapper.Table.Owner : owner; Alias = alias; NoLock = nolock; - + Schema = db.GetSchema(type); } - + /// Gets or sets table owner name. public string Owner { get; internal set; } - + /// Gets or sets table name. public string Name { get; internal set; } - + /// Gets or sets table alias. public string Alias { get; internal set; } - + /// Gets or sets table alias. public bool NoLock { get; internal set; } - + /// Gets or sets table schema. public Dictionary Schema { get; internal set; } - + /// Gets a value indicating whether this instance is disposed. public bool IsDisposed { get; private set; } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. public virtual void Dispose() { IsDisposed = true; - + ////if (Schema != null) //// Schema.Clear(); - + Owner = Name = Alias = null; Schema = null; } } - + /// Generic based table information. /// Type of class that is represented in database. internal class TableInfo : TableInfo @@ -8618,11 +8637,11 @@ namespace DynamORM { } } - + #endregion TableInfo - + #region Parameter - + /// Interface describing parameter info. internal class Parameter : IParameter { @@ -8632,44 +8651,44 @@ namespace DynamORM { IsDisposed = false; } - + /// Gets or sets the parameter position in command. /// Available after filling the command. public int Ordinal { get; internal set; } - + /// Gets or sets the parameter temporary name. public string Name { get; internal set; } - + /// Gets or sets the parameter value. public object Value { get; set; } - + /// Gets or sets a value indicating whether name of temporary parameter is well known. public bool WellKnown { get; set; } - + /// Gets or sets a value indicating whether this is virtual. public bool Virtual { get; set; } - + /// Gets or sets the parameter schema information. public DynamicSchemaColumn? Schema { get; set; } - + /// Gets a value indicating whether this instance is disposed. public bool IsDisposed { get; private set; } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. public virtual void Dispose() { IsDisposed = true; - + Name = null; Schema = null; } } - + #endregion Parameter - + #region Constructor - + /// /// Initializes a new instance of the class. /// @@ -8682,18 +8701,18 @@ namespace DynamORM Parameters = new Dictionary(); OnCreateTemporaryParameter = new List>(); OnCreateParameter = new List>(); - + WhereCondition = null; WhereOpenBracketsCount = 0; - + Database = db; if (Database != null) Database.AddToCache(this); - + SupportSchema = (db.Options & DynamicDatabaseOptions.SupportSchema) == DynamicDatabaseOptions.SupportSchema; SupportNoLock = (db.Options & DynamicDatabaseOptions.SupportNoLock) == DynamicDatabaseOptions.SupportNoLock; } - + /// Initializes a new instance of the class. /// The database. /// The parent query. @@ -8702,54 +8721,54 @@ namespace DynamORM { _parent = parent; } - + #endregion Constructor - + #region IQueryWithWhere - + /// Gets or sets the where condition. public string WhereCondition { get; set; } - + /// Gets or sets the amount of not closed brackets in where statement. public int WhereOpenBracketsCount { get; set; } - + #endregion IQueryWithWhere - + #region IDynamicQueryBuilder - + /// Gets instance. public DynamicDatabase Database { get; private set; } - + /// Gets the tables used in this builder. public IList Tables { get; private set; } - + /// Gets the tables used in this builder. public IDictionary Parameters { get; private set; } - + /// Gets or sets a value indicating whether add virtual parameters. public bool VirtualMode { get; set; } - + /// Gets or sets the on create temporary parameter actions. /// This is exposed to allow setting schema of column. public List> OnCreateTemporaryParameter { get; set; } - + /// Gets or sets the on create real parameter actions. /// This is exposed to allow modification of parameter. public List> OnCreateParameter { get; set; } - + /// Gets a value indicating whether database supports standard schema. public bool SupportSchema { get; private set; } - + /// Gets a value indicating whether database supports with no lock syntax. public bool SupportNoLock { get; private set; } - + /// /// Generates the text this command will execute against the underlying database. /// /// The text to execute against the underlying database. /// This method must be override by derived classes. public abstract string CommandText(); - + /// Fill command with query. /// Command to fill. /// Filled instance of . @@ -8764,19 +8783,19 @@ namespace DynamORM WhereOpenBracketsCount--; } } - + // End not ended having statement if (this is IQueryWithHaving) { IQueryWithHaving h = this as IQueryWithHaving; - + while (h.HavingOpenBracketsCount > 0) { h.HavingCondition += ")"; h.HavingOpenBracketsCount--; } } - + return command.SetCommand(CommandText() .FillStringWithVariables(s => { @@ -8785,21 +8804,21 @@ namespace DynamORM IDbDataParameter param = (IDbDataParameter)command .AddParameter(this, p.Schema, p.Value) .Parameters[command.Parameters.Count - 1]; - + (p as Parameter).Ordinal = command.Parameters.Count - 1; - + if (OnCreateParameter != null) OnCreateParameter.ForEach(x => x(p, param)); - + return param.ParameterName; }, s); })); } - + #endregion IDynamicQueryBuilder - + #region Parser - + /// Parses the arbitrary object given and translates it into a string with the appropriate /// syntax for the database this parser is specific to. /// The object to parse and translate. It can be any arbitrary object, including null values (if @@ -8817,10 +8836,10 @@ namespace DynamORM internal virtual string Parse(object node, IDictionary pars = null, bool rawstr = false, bool nulls = false, bool decorate = true, bool isMultiPart = true) { DynamicSchemaColumn? c = null; - + return Parse(node, ref c, pars, rawstr, nulls, decorate, isMultiPart); } - + /// Parses the arbitrary object given and translates it into a string with the appropriate /// syntax for the database this parser is specific to. /// The object to parse and translate. It can be any arbitrary object, including null values (if @@ -8843,31 +8862,31 @@ namespace DynamORM { if (!nulls) throw new ArgumentNullException("node", "Null nodes are not accepted."); - + return Dispatch(node, ref columnSchema, pars, decorate); } - + // Nodes that are strings are parametrized or not depending the "rawstr" flag... if (node is string) { if (rawstr) return (string)node; else return Dispatch(node, ref columnSchema, pars, decorate); } - + // If node is a delegate, parse it to create the logical tree... if (node is Delegate) { using (DynamicParser p = DynamicParser.Parse((Delegate)node)) { node = p.Result; - + return Parse(node, ref columnSchema, pars, rawstr, decorate: decorate); // Intercept containers as in (x => "string") } } - + return Dispatch(node, ref columnSchema, pars, decorate, isMultiPart); } - + private string Dispatch(object node, ref DynamicSchemaColumn? columnSchema, IDictionary pars = null, bool decorate = true, bool isMultiPart = true) { if (node != null) @@ -8882,38 +8901,38 @@ namespace DynamORM else if (node is DynamicParser.Node.Invoke) return ParseInvoke((DynamicParser.Node.Invoke)node, ref columnSchema, pars); else if (node is DynamicParser.Node.Convert) return ParseConvert((DynamicParser.Node.Convert)node, pars); } - + // All other cases are considered constant parameters... return ParseConstant(node, pars, columnSchema); } - + internal virtual string ParseCommand(DynamicQueryBuilder node, IDictionary pars = null) { // Getting the command's text... string str = node.CommandText(); // Avoiding spurious "OUTPUT XXX" statements - + // If there are parameters to transform, but cannot store them, it is an error if (node.Parameters.Count != 0 && pars == null) return string.Format("({0})", str); - + // TODO: Make special condiion ////throw new InvalidOperationException(string.Format("The parameters in this command '{0}' cannot be added to a null collection.", node.Parameters)); - + // Copy parameters to new comand foreach (KeyValuePair parameter in node.Parameters) pars.Add(parameter.Key, parameter.Value); - + return string.Format("({0})", str); } - + protected virtual string ParseArgument(DynamicParser.Node.Argument node, bool isMultiPart = true, bool isOwner = false) { if (!string.IsNullOrEmpty(node.Name) && (isOwner || (isMultiPart && IsTableAlias(node.Name)))) return node.Name; - + return null; } - + protected virtual string ParseGetMember(DynamicParser.Node.GetMember node, ref DynamicSchemaColumn? columnSchema, IDictionary pars = null, bool decorate = true, bool isMultiPart = true) { if (node.Host is DynamicParser.Node.Argument && IsTableAlias(node.Name)) @@ -8921,7 +8940,7 @@ namespace DynamORM decorate = false; isMultiPart = false; } - + // This hack allows to use argument as alias, but when it is not nesesary use other column. // Let say we hace a table Users with alias usr, and we join to table with alias ua which also has a column Users // This allow use of usr => usr.ua.Users to result in ua."Users" instead of "Users" or usr."ua"."Users", se tests for examples. @@ -8938,17 +8957,17 @@ namespace DynamORM else if (isMultiPart) parent = Parse(node.Host, pars, isMultiPart: isMultiPart); } - + ////string parent = node.Host == null || !isMultiPart ? null : Parse(node.Host, pars, isMultiPart: !IsTable(node.Name, node.Host.Name)); string name = parent == null ? decorate ? Database.DecorateName(node.Name) : node.Name : string.Format("{0}.{1}", parent, decorate ? Database.DecorateName(node.Name) : node.Name); - + columnSchema = GetColumnFromSchema(name); - + return name; } - + protected virtual string ParseSetMember(DynamicParser.Node.SetMember node, ref DynamicSchemaColumn? columnSchema, IDictionary pars = null, bool decorate = true, bool isMultiPart = true) { if (node.Host is DynamicParser.Node.Argument && IsTableAlias(node.Name)) @@ -8956,7 +8975,7 @@ namespace DynamORM decorate = false; isMultiPart = false; } - + string parent = null; if (node.Host != null) { @@ -8970,18 +8989,18 @@ namespace DynamORM else if (isMultiPart) parent = Parse(node.Host, pars, isMultiPart: isMultiPart); } - + ////string parent = node.Host == null || !isMultiPart ? null : Parse(node.Host, pars, isMultiPart: !IsTable(node.Name, node.Host.Name)); string name = parent == null ? decorate ? Database.DecorateName(node.Name) : node.Name : string.Format("{0}.{1}", parent, decorate ? Database.DecorateName(node.Name) : node.Name); - + columnSchema = GetColumnFromSchema(name); - + string value = Parse(node.Value, ref columnSchema, pars, nulls: true); return string.Format("{0} = ({1})", name, value); } - + protected virtual string ParseUnary(DynamicParser.Node.Unary node, IDictionary pars = null) { switch (node.Operation) @@ -8989,19 +9008,19 @@ namespace DynamORM // Artifacts from the DynamicParser class that are not usefull here... case ExpressionType.IsFalse: case ExpressionType.IsTrue: return Parse(node.Target, pars); - + // Unary supported operations... case ExpressionType.Not: return string.Format("(NOT {0})", Parse(node.Target, pars)); case ExpressionType.Negate: return string.Format("!({0})", Parse(node.Target, pars)); } - + throw new ArgumentException("Not supported unary operation: " + node); } - + protected virtual string ParseBinary(DynamicParser.Node.Binary node, IDictionary pars = null) { string op = string.Empty; - + switch (node.Operation) { // Arithmetic binary operations... @@ -9011,35 +9030,35 @@ namespace DynamORM case ExpressionType.Divide: op = "/"; break; case ExpressionType.Modulo: op = "%"; break; case ExpressionType.Power: op = "^"; break; - + case ExpressionType.And: op = "AND"; break; case ExpressionType.Or: op = "OR"; break; - + // Logical comparisons... case ExpressionType.GreaterThan: op = ">"; break; case ExpressionType.GreaterThanOrEqual: op = ">="; break; case ExpressionType.LessThan: op = "<"; break; case ExpressionType.LessThanOrEqual: op = "<="; break; - + // Comparisons against 'NULL' require the 'IS' or 'IS NOT' operator instead the numeric ones... case ExpressionType.Equal: op = node.Right == null && !VirtualMode ? "IS" : "="; break; case ExpressionType.NotEqual: op = node.Right == null && !VirtualMode ? "IS NOT" : "<>"; break; - + default: throw new ArgumentException("Not supported operator: '" + node.Operation); } - + DynamicSchemaColumn? columnSchema = null; string left = Parse(node.Left, ref columnSchema, pars); // Not nulls: left is assumed to be an object string right = Parse(node.Right, ref columnSchema, pars, nulls: true); return string.Format("({0} {1} {2})", left, op, right); } - + protected virtual string ParseMethod(DynamicParser.Node.Method node, ref DynamicSchemaColumn? columnSchema, IDictionary pars = null) { string method = node.Name.ToUpper(); string parent = node.Host == null ? null : Parse(node.Host, ref columnSchema, pars: pars); string item = null; - + // Root-level methods... if (node.Host == null) { @@ -9051,7 +9070,7 @@ namespace DynamORM return string.Format("(NOT {0})", item); } } - + // Column-level methods... if (node.Host != null) { @@ -9061,47 +9080,47 @@ namespace DynamORM { if (node.Arguments == null || node.Arguments.Length == 0) throw new ArgumentException("BETWEEN method expects at least one argument: " + node.Arguments.Sketch()); - + if (node.Arguments.Length > 2) throw new ArgumentException("BETWEEN method expects at most two arguments: " + node.Arguments.Sketch()); - + object[] arguments = node.Arguments; - + if (arguments.Length == 1 && (arguments[0] is IEnumerable || arguments[0] is Array) && !(arguments[0] is byte[])) { IEnumerable vals = arguments[0] as IEnumerable; - + if (vals == null && arguments[0] is Array) vals = ((Array)arguments[0]).Cast() as IEnumerable; - + if (vals != null) arguments = vals.ToArray(); else throw new ArgumentException("BETWEEN method expects single argument to be enumerable of exactly two elements: " + node.Arguments.Sketch()); } - + return string.Format("{0} BETWEEN {1} AND {2}", parent, Parse(arguments[0], ref columnSchema, pars: pars), Parse(arguments[1], ref columnSchema, pars: pars)); } - + case "IN": { if (node.Arguments == null || node.Arguments.Length == 0) throw new ArgumentException("IN method expects at least one argument: " + node.Arguments.Sketch()); - + bool firstParam = true; StringBuilder sbin = new StringBuilder(); foreach (object arg in node.Arguments) { if (!firstParam) sbin.Append(", "); - + if ((arg is IEnumerable || arg is Array) && !(arg is byte[])) { IEnumerable vals = arg as IEnumerable; - + if (vals == null && arg is Array) vals = ((Array)arg).Cast() as IEnumerable; - + if (vals != null) foreach (object val in vals) { @@ -9109,7 +9128,7 @@ namespace DynamORM sbin.Append(", "); else firstParam = false; - + sbin.Append(Parse(val, ref columnSchema, pars: pars)); } else @@ -9117,32 +9136,32 @@ namespace DynamORM } else sbin.Append(Parse(arg, ref columnSchema, pars: pars)); - + firstParam = false; } - + return string.Format("{0} IN({1})", parent, sbin.ToString()); } - + case "NOTIN": { if (node.Arguments == null || node.Arguments.Length == 0) throw new ArgumentException("IN method expects at least one argument: " + node.Arguments.Sketch()); - + bool firstParam = true; StringBuilder sbin = new StringBuilder(); foreach (object arg in node.Arguments) { if (!firstParam) sbin.Append(", "); - + if ((arg is IEnumerable || arg is Array) && !(arg is byte[])) { IEnumerable vals = arg as IEnumerable; - + if (vals == null && arg is Array) vals = ((Array)arg).Cast() as IEnumerable; - + if (vals != null) foreach (object val in vals) { @@ -9150,7 +9169,7 @@ namespace DynamORM sbin.Append(", "); else firstParam = false; - + sbin.Append(Parse(val, ref columnSchema, pars: pars)); } else @@ -9158,106 +9177,106 @@ namespace DynamORM } else sbin.Append(Parse(arg, ref columnSchema, pars: pars)); - + firstParam = false; } - + return string.Format("{0} NOT IN({1})", parent, sbin.ToString()); } - + case "LIKE": if (node.Arguments == null || node.Arguments.Length != 1) throw new ArgumentException("LIKE method expects one argument: " + node.Arguments.Sketch()); - + return string.Format("{0} LIKE {1}", parent, Parse(node.Arguments[0], ref columnSchema, pars: pars)); - + case "NOTLIKE": if (node.Arguments == null || node.Arguments.Length != 1) throw new ArgumentException("NOT LIKE method expects one argument: " + node.Arguments.Sketch()); - + return string.Format("{0} NOT LIKE {1}", parent, Parse(node.Arguments[0], ref columnSchema, pars: pars)); - + case "AS": if (node.Arguments == null || node.Arguments.Length != 1) throw new ArgumentException("AS method expects one argument: " + node.Arguments.Sketch()); - + item = Parse(node.Arguments[0], pars: null, rawstr: true, isMultiPart: false); // pars=null to avoid to parameterize aliases item = item.Validated("Alias"); // Intercepting null and empty aliases return string.Format("{0} AS {1}", parent, item); - + case "NOLOCK": if (!SupportNoLock) return parent; - + if (node.Arguments != null && node.Arguments.Length > 1) throw new ArgumentException("NOLOCK method expects no arguments."); - + return string.Format("{0} {1}", parent, "WITH(NOLOCK)"); - + case "COUNT": if (node.Arguments != null && node.Arguments.Length > 1) throw new ArgumentException("COUNT method expects one or none argument: " + node.Arguments.Sketch()); - + if (node.Arguments == null || node.Arguments.Length == 0) return "COUNT(*)"; - + return string.Format("COUNT({0})", Parse(node.Arguments[0], ref columnSchema, pars: Parameters, nulls: true)); - + case "COUNT0": if (node.Arguments != null && node.Arguments.Length > 0) throw new ArgumentException("COUNT0 method doesn't expect arguments"); - + return "COUNT(0)"; } } - + // Default case: parsing the method's name along with its arguments... method = parent == null ? node.Name : string.Format("{0}.{1}", parent, node.Name); StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0}(", method); - + if (node.Arguments != null && node.Arguments.Length != 0) { bool first = true; - + foreach (object argument in node.Arguments) { if (!first) sb.Append(", "); else first = false; - + sb.Append(Parse(argument, ref columnSchema, pars, nulls: true)); // We don't accept raw strings here!!! } } - + sb.Append(")"); return sb.ToString(); } - + protected virtual string ParseInvoke(DynamicParser.Node.Invoke node, ref DynamicSchemaColumn? columnSchema, IDictionary pars = null) { // This is used as an especial syntax to merely concatenate its arguments. It is used as a way to extend the supported syntax without the need of treating all the possible cases... if (node.Arguments == null || node.Arguments.Length == 0) return string.Empty; - + StringBuilder sb = new StringBuilder(); foreach (object arg in node.Arguments) { if (arg is string) { sb.Append((string)arg); - + if (node.Arguments.Length == 1 && !columnSchema.HasValue) columnSchema = GetColumnFromSchema((string)arg); } else sb.Append(Parse(arg, ref columnSchema, pars, rawstr: true, nulls: true)); } - + return sb.ToString(); } - + protected virtual string ParseConvert(DynamicParser.Node.Convert node, IDictionary pars = null) { // The cast mechanism is left for the specific database implementation, that should override this method @@ -9265,16 +9284,16 @@ namespace DynamORM string r = Parse(node.Target, pars); return r; } - + protected virtual string ParseConstant(object node, IDictionary pars = null, DynamicSchemaColumn? columnSchema = null) { if (node == null && !VirtualMode) return ParseNull(); - + if (pars != null) { bool wellKnownName = VirtualMode && node is String && ((String)node).StartsWith("[$") && ((String)node).EndsWith("]") && ((String)node).Length > 4; - + // If we have a list of parameters to store it, let's parametrize it Parameter par = new Parameter() { @@ -9284,60 +9303,60 @@ namespace DynamORM Virtual = VirtualMode, Schema = columnSchema, }; - + // If we are adding parameter we inform external sources about this. if (OnCreateTemporaryParameter != null) OnCreateTemporaryParameter.ForEach(x => x(par)); - + pars.Add(par.Name, par); - + return string.Format("[${0}]", par.Name); } - + return node.ToString(); // Last resort case } - + protected virtual string ParseNull() { return "NULL"; // Override if needed } - + #endregion Parser - + #region Helpers - + internal bool IsTableAlias(string name) { DynamicQueryBuilder builder = this; - + while (builder != null) { if (builder.Tables.Any(t => t.Alias == name)) return true; - + builder = builder._parent; } - + return false; } - + internal bool IsTable(string name, string owner) { DynamicQueryBuilder builder = this; - + while (builder != null) { if ((string.IsNullOrEmpty(owner) && builder.Tables.Any(t => t.Name.ToLower() == name.ToLower())) || (!string.IsNullOrEmpty(owner) && builder.Tables.Any(t => t.Name.ToLower() == name.ToLower() && !string.IsNullOrEmpty(t.Owner) && t.Owner.ToLower() == owner.ToLower()))) return true; - + builder = builder._parent; } - + return false; } - + internal string FixObjectName(string main, bool onlyColumn = false) { if (main.IndexOf("(") > 0 && main.IndexOf(")") > 0) @@ -9345,133 +9364,133 @@ namespace DynamORM else return FixObjectNamePrivate(main, onlyColumn); } - + private string FixObjectNamePrivate(string f, bool onlyColumn = false) { IEnumerable objects = f.Split('.') .Select(x => Database.StripName(x)); - + if (onlyColumn || objects.Count() == 1) f = Database.DecorateName(objects.Last()); else if (!IsTableAlias(objects.First())) f = string.Join(".", objects.Select(o => Database.DecorateName(o))); else f = string.Format("{0}.{1}", objects.First(), string.Join(".", objects.Skip(1).Select(o => Database.DecorateName(o)))); - + return f; } - + internal DynamicSchemaColumn? GetColumnFromSchema(string colName, DynamicTypeMap mapper = null, string table = null) { // This is tricky and will not always work unfortunetly. ////if (colName.ContainsAny(StringExtensions.InvalidMultipartMemberChars)) //// return null; - + // First we need to get real column name and it's owner if exist. string[] parts = colName.Split('.'); for (int i = 0; i < parts.Length; i++) parts[i] = Database.StripName(parts[i]); - + string columnName = parts.Last(); - + // Get table name from mapper string tableName = table; - + if (string.IsNullOrEmpty(tableName)) { tableName = (mapper != null && mapper.Table != null) ? mapper.Table.Name : string.Empty; - + if (parts.Length > 1 && string.IsNullOrEmpty(tableName)) { // OK, we have a multi part identifier, that's good, we can get table name tableName = string.Join(".", parts.Take(parts.Length - 1)); } } - + // Try to get table info from cache ITableInfo tableInfo = !string.IsNullOrEmpty(tableName) ? Tables.FirstOrDefault(x => !string.IsNullOrEmpty(x.Alias) && x.Alias.ToLower() == tableName) ?? Tables.FirstOrDefault(x => x.Name.ToLower() == tableName.ToLower()) ?? Tables.FirstOrDefault() : this is DynamicModifyBuilder || Tables.Count == 1 ? Tables.FirstOrDefault() : null; - + // Try to get column from schema if (tableInfo != null && tableInfo.Schema != null) return tableInfo.Schema.TryGetNullable(columnName.ToLower()); - + // Well, we failed to find a column return null; } - + #endregion Helpers - + #region IExtendedDisposable - + /// Gets a value indicating whether this instance is disposed. public bool IsDisposed { get; private set; } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. public virtual void Dispose() { IsDisposed = true; - + if (Database != null) Database.RemoveFromCache(this); - + if (Parameters != null) { foreach (KeyValuePair p in Parameters) p.Value.Dispose(); - + Parameters.Clear(); Parameters = null; } - + if (Tables != null) { foreach (ITableInfo t in Tables) if (t != null) t.Dispose(); - + Tables.Clear(); Tables = null; } - + WhereCondition = null; Database = null; } - + #endregion IExtendedDisposable } - + /// Implementation of dynamic select query builder. internal class DynamicSelectQueryBuilder : DynamicQueryBuilder, IDynamicSelectQueryBuilder, DynamicQueryBuilder.IQueryWithWhere, DynamicQueryBuilder.IQueryWithHaving { private int? _limit = null; private int? _offset = null; private bool _distinct = false; - + private string _select; private string _from; private string _join; private string _groupby; private string _orderby; - + #region IQueryWithHaving - + /// Gets or sets the having condition. public string HavingCondition { get; set; } - + /// Gets or sets the amount of not closed brackets in having statement. public int HavingOpenBracketsCount { get; set; } - + #endregion IQueryWithHaving - + /// /// Gets a value indicating whether this instance has select columns. /// public bool HasSelectColumns { get { return !string.IsNullOrEmpty(_select); } } - + /// /// Initializes a new instance of the class. /// @@ -9480,7 +9499,7 @@ namespace DynamORM : base(db) { } - + /// /// Initializes a new instance of the class. /// @@ -9490,17 +9509,17 @@ namespace DynamORM : base(db, parent) { } - + /// Generates the text this command will execute against the underlying database. /// The text to execute against the underlying database. public override string CommandText() { bool lused = false; bool oused = false; - + StringBuilder sb = new StringBuilder("SELECT"); if (_distinct) sb.AppendFormat(" DISTINCT"); - + if (_limit.HasValue) { if ((Database.Options & DynamicDatabaseOptions.SupportTop) == DynamicDatabaseOptions.SupportTop) @@ -9514,13 +9533,13 @@ namespace DynamORM lused = true; } } - + if (_offset.HasValue && (Database.Options & DynamicDatabaseOptions.SupportFirstSkip) == DynamicDatabaseOptions.SupportFirstSkip) { sb.AppendFormat(" SKIP {0}", _offset); oused = true; } - + if (_select != null) sb.AppendFormat(" {0}", _select); else sb.Append(" *"); if (_from != null) sb.AppendFormat(" FROM {0}", _from); if (_join != null) sb.AppendFormat(" {0}", _join); @@ -9532,12 +9551,12 @@ namespace DynamORM sb.AppendFormat(" LIMIT {0}", _limit); if (_offset.HasValue && !oused && (Database.Options & DynamicDatabaseOptions.SupportLimitOffset) == DynamicDatabaseOptions.SupportLimitOffset) sb.AppendFormat(" OFFSET {0}", _offset); - + return sb.ToString(); } - + #region Execution - + /// Execute this builder. /// Enumerator of objects expanded from query. public virtual IEnumerable Execute() @@ -9550,11 +9569,11 @@ namespace DynamORM .SetCommand(this) .ExecuteReader()) cache = new DynamicCachedReader(rdr); - + while (cache.Read()) { dynamic val = null; - + // Work around to avoid yield being in try...catchblock: // http://stackoverflow.com/questions/346365/why-cant-yield-return-appear-inside-a-try-block-with-a-catch try @@ -9565,16 +9584,16 @@ namespace DynamORM { StringBuilder sb = new StringBuilder(); cmd.Dump(sb); - + throw new ArgumentException(string.Format("{0}{1}{2}", argex.Message, Environment.NewLine, sb), argex.InnerException.NullOr(a => a, argex)); } - + yield return val; } } } - + /// Execute this builder and map to given type. /// Type of object to map on. /// Enumerator of objects expanded from query. @@ -9582,10 +9601,10 @@ namespace DynamORM { DynamicCachedReader cache = null; DynamicTypeMap mapper = DynamicMapperCache.GetMapper(); - + if (mapper == null) throw new InvalidOperationException("Type can't be mapped for unknown reason."); - + using (IDbConnection con = Database.Open()) using (IDbCommand cmd = con.CreateCommand()) { @@ -9593,11 +9612,11 @@ namespace DynamORM .SetCommand(this) .ExecuteReader()) cache = new DynamicCachedReader(rdr); - + while (cache.Read()) { dynamic val = null; - + // Work around to avoid yield being in try...catchblock: // http://stackoverflow.com/questions/346365/why-cant-yield-return-appear-inside-a-try-block-with-a-catch try @@ -9608,16 +9627,16 @@ namespace DynamORM { StringBuilder sb = new StringBuilder(); cmd.Dump(sb); - + throw new ArgumentException(string.Format("{0}{1}{2}", argex.Message, Environment.NewLine, sb), argex.InnerException.NullOr(a => a, argex)); } - + yield return mapper.Create(val) as T; } } } - + /// Execute this builder as a data reader. /// Action containing reader. public virtual void ExecuteDataReader(Action reader) @@ -9629,24 +9648,24 @@ namespace DynamORM .ExecuteReader()) reader(rdr); } - + /// Execute this builder as a data reader, but /// first makes a full reader copy in memory. /// Action containing reader. public virtual void ExecuteCachedDataReader(Action reader) { DynamicCachedReader cache = null; - + using (IDbConnection con = Database.Open()) using (IDbCommand cmd = con.CreateCommand()) using (IDataReader rdr = cmd .SetCommand(this) .ExecuteReader()) cache = new DynamicCachedReader(rdr); - + reader(cache); } - + /// Returns a single result. /// Result of a query. public virtual object Scalar() @@ -9659,9 +9678,9 @@ namespace DynamORM .ExecuteScalar(); } } - - #if !DYNAMORM_OMMIT_GENERICEXECUTION && !DYNAMORM_OMMIT_TRYPARSE - + +#if !DYNAMORM_OMMIT_GENERICEXECUTION && !DYNAMORM_OMMIT_TRYPARSE + /// Returns a single result. /// Type to parse to. /// Default value. @@ -9676,13 +9695,13 @@ namespace DynamORM .ExecuteScalarAs(defaultValue); } } - - #endif - + +#endif + #endregion Execution - + #region From/Join - + /// /// Adds to the 'From' clause the contents obtained by parsing the dynamic lambda expressions given. The supported /// formats are: @@ -9698,25 +9717,25 @@ namespace DynamORM { if (fn == null) throw new ArgumentNullException("Array of functions cannot be or contain null."); - + int index = FromFunc(-1, fn); foreach (Func f in func) index = FromFunc(index, f); - + return this; } - + private int FromFunc(int index, Func f) { if (f == null) throw new ArgumentNullException("Array of functions cannot be or contain null."); - + index++; ITableInfo tableInfo = null; using (DynamicParser parser = DynamicParser.Parse(f)) { object result = parser.Result; - + // If the expression result is string. if (result is string) { @@ -9733,25 +9752,25 @@ namespace DynamORM Type type = (Type)result; if (type.IsAnonymous()) throw new InvalidOperationException(string.Format("Cant assign anonymous type as a table ({0}). Parsing {1}", type.FullName, result)); - + DynamicTypeMap mapper = DynamicMapperCache.GetMapper(type); - + if (mapper == null) throw new InvalidOperationException(string.Format("Cant assign unmapable type as a table ({0}). Parsing {1}", type.FullName, result)); - + tableInfo = new TableInfo(Database, type); } else if (result is DynamicParser.Node) { // Or if it resolves to a dynamic node DynamicParser.Node node = (DynamicParser.Node)result; - + string owner = null; string main = null; string alias = null; bool nolock = false; Type type = null; - + while (true) { // Support for the AS() virtual method... @@ -9759,62 +9778,62 @@ namespace DynamORM { if (alias != null) throw new ArgumentException(string.Format("Alias '{0}' is already set when parsing '{1}'.", alias, result)); - + object[] args = ((DynamicParser.Node.Method)node).Arguments; - + if (args == null) throw new ArgumentNullException("arg", "AS() is not a parameterless method."); - + if (args.Length != 1) throw new ArgumentException("AS() requires one and only one parameter: " + args.Sketch()); - + alias = Parse(args[0], rawstr: true, decorate: false).Validated("Alias"); - + node = node.Host; continue; } - + // Support for the NoLock() virtual method... if (node is DynamicParser.Node.Method && ((DynamicParser.Node.Method)node).Name.ToUpper() == "NOLOCK") { object[] args = ((DynamicParser.Node.Method)node).Arguments; - + if (args != null && args.Length > 0) throw new ArgumentNullException("arg", "NoLock() doesn't support arguments."); - + nolock = true; - + node = node.Host; continue; } - + /*if (node is DynamicParser.Node.Method && ((DynamicParser.Node.Method)node).Name.ToUpper() == "subquery") { main = Parse(this.SubQuery(((DynamicParser.Node.Method)node).Arguments.Where(p => p is Func).Cast>().ToArray()), Parameters); continue; }*/ - + // Support for table specifications... if (node is DynamicParser.Node.GetMember) { if (owner != null) throw new ArgumentException(string.Format("Owner '{0}.{1}' is already set when parsing '{2}'.", owner, main, result)); - + if (main != null) owner = ((DynamicParser.Node.GetMember)node).Name; else main = ((DynamicParser.Node.GetMember)node).Name; - + node = node.Host; continue; } - + // Support for generic sources... if (node is DynamicParser.Node.Invoke) { if (owner != null) throw new ArgumentException(string.Format("Owner '{0}.{1}' is already set when parsing '{2}'.", owner, main, result)); - + if (main != null) owner = string.Format("{0}", Parse(node, rawstr: true, pars: Parameters)); else @@ -9825,69 +9844,69 @@ namespace DynamORM type = (Type)invoke.Arguments[0]; if (type.IsAnonymous()) throw new InvalidOperationException(string.Format("Cant assign anonymous type as a table ({0}). Parsing {1}", type.FullName, result)); - + DynamicTypeMap mapper = DynamicMapperCache.GetMapper(type); - + if (mapper == null) throw new InvalidOperationException(string.Format("Cant assign unmapable type as a table ({0}). Parsing {1}", type.FullName, result)); - + main = mapper.Table == null || string.IsNullOrEmpty(mapper.Table.Name) ? mapper.Type.Name : mapper.Table.Name; - + owner = (mapper.Table != null) ? mapper.Table.Owner : owner; } else main = string.Format("{0}", Parse(node, rawstr: true, pars: Parameters)); } - + node = node.Host; continue; } - + // Just finished the parsing... if (node is DynamicParser.Node.Argument) break; - + // All others are assumed to be part of the main element... if (main != null) main = Parse(node, pars: Parameters); else main = Parse(node, pars: Parameters); - + break; } - + if (!string.IsNullOrEmpty(main)) tableInfo = type == null ? new TableInfo(Database, main, alias, owner, nolock) : new TableInfo(Database, type, alias, owner, nolock); else throw new ArgumentException(string.Format("Specification #{0} is invalid: {1}", index, result)); } - + // Or it is a not supported expression... if (tableInfo == null) throw new ArgumentException(string.Format("Specification #{0} is invalid: {1}", index, result)); - + Tables.Add(tableInfo); - + // We finally add the contents... StringBuilder sb = new StringBuilder(); - + if (!string.IsNullOrEmpty(tableInfo.Owner)) sb.AppendFormat("{0}.", Database.DecorateName(tableInfo.Owner)); - + sb.Append(tableInfo.Name.ContainsAny(StringExtensions.InvalidMemberChars) ? tableInfo.Name : Database.DecorateName(tableInfo.Name)); - + if (!string.IsNullOrEmpty(tableInfo.Alias)) sb.AppendFormat(" AS {0}", tableInfo.Alias); - + if (SupportNoLock && tableInfo.NoLock) sb.AppendFormat(" WITH(NOLOCK)"); - + _from = string.IsNullOrEmpty(_from) ? sb.ToString() : string.Format("{0}, {1}", _from, sb.ToString()); } - + return index; } - + /// /// Adds to the 'Join' clause the contents obtained by parsing the dynamic lambda expressions given. The supported /// formats are: @@ -9909,7 +9928,7 @@ namespace DynamORM // We need to do two passes to add aliases first. return JoinInternal(true, func).JoinInternal(false, func); } - + /// /// Adds to the 'Join' clause the contents obtained by parsing the dynamic lambda expressions given. The supported /// formats are: @@ -9930,22 +9949,22 @@ namespace DynamORM protected virtual DynamicSelectQueryBuilder JoinInternal(bool justAddTables, params Func[] func) { if (func == null) throw new ArgumentNullException("Array of functions cannot be null."); - + int index = -1; - + foreach (Func f in func) { index++; ITableInfo tableInfo = null; - + if (f == null) throw new ArgumentNullException(string.Format("Specification #{0} cannot be null.", index)); - + using (DynamicParser parser = DynamicParser.Parse(f)) { object result = parser.Result; if (result == null) throw new ArgumentException(string.Format("Specification #{0} resolves to null.", index)); - + string type = null; string main = null; string owner = null; @@ -9953,14 +9972,14 @@ namespace DynamORM string condition = null; bool nolock = false; Type tableType = null; - + // If the expression resolves to a string... if (result is string) { string node = (string)result; - + int n = node.ToUpper().IndexOf("JOIN "); - + if (n < 0) main = node; else @@ -9969,15 +9988,15 @@ namespace DynamORM type = node.Substring(0, n + 4); main = node.Substring(n + 4); } - + n = main.ToUpper().IndexOf("ON"); - + if (n >= 0) { condition = main.Substring(n + 3); main = main.Substring(0, n).Trim(); } - + Tuple tuple = main.SplitSomethingAndAlias(); // In this case we split on the remaining 'main' string[] parts = tuple.Item1.Split('.'); main = Database.StripName(parts.Last()).Validated("Table"); @@ -9995,78 +10014,78 @@ namespace DynamORM { if (condition != null) throw new ArgumentException(string.Format("Condition '{0}' is already set when parsing '{1}'.", alias, result)); - + object[] args = ((DynamicParser.Node.Method)node).Arguments; if (args == null) throw new ArgumentNullException("arg", "ON() is not a parameterless method."); - + if (args.Length != 1) throw new ArgumentException("ON() requires one and only one parameter: " + args.Sketch()); - + condition = Parse(args[0], rawstr: true, pars: justAddTables ? null : Parameters); - + node = node.Host; continue; } - + // Support for the AS() virtual method... if (node is DynamicParser.Node.Method && ((DynamicParser.Node.Method)node).Name.ToUpper() == "AS") { if (alias != null) throw new ArgumentException(string.Format("Alias '{0}' is already set when parsing '{1}'.", alias, result)); - + object[] args = ((DynamicParser.Node.Method)node).Arguments; - + if (args == null) throw new ArgumentNullException("arg", "AS() is not a parameterless method."); - + if (args.Length != 1) throw new ArgumentException("AS() requires one and only one parameter: " + args.Sketch()); - + alias = Parse(args[0], rawstr: true, decorate: false, isMultiPart: false).Validated("Alias"); - + node = node.Host; continue; } - + // Support for the NoLock() virtual method... if (node is DynamicParser.Node.Method && ((DynamicParser.Node.Method)node).Name.ToUpper() == "NOLOCK") { object[] args = ((DynamicParser.Node.Method)node).Arguments; - + if (args != null && args.Length > 0) throw new ArgumentNullException("arg", "NoLock() doesn't support arguments."); - + nolock = true; - + node = node.Host; continue; } - + // Support for table specifications... if (node is DynamicParser.Node.GetMember) { if (owner != null) throw new ArgumentException(string.Format("Owner '{0}.{1}' is already set when parsing '{2}'.", owner, main, result)); - + if (main != null) owner = ((DynamicParser.Node.GetMember)node).Name; else main = ((DynamicParser.Node.GetMember)node).Name; - + node = node.Host; continue; } - + // Support for Join Type specifications... if (node is DynamicParser.Node.Method && (node.Host is DynamicParser.Node.Argument || node.Host is DynamicParser.Node.Invoke)) { if (type != null) throw new ArgumentException(string.Format("Join type '{0}' is already set when parsing '{1}'.", main, result)); type = ((DynamicParser.Node.Method)node).Name; - + bool avoid = false; object[] args = ((DynamicParser.Node.Method)node).Arguments; - + if (args != null && args.Length > 0) { avoid = args[0] is bool && !((bool)args[0]); @@ -10074,7 +10093,7 @@ namespace DynamORM if (!string.IsNullOrEmpty(proposedType)) type = proposedType; } - + type = type.ToUpper(); // Normalizing, and stepping out the trivial case... if (type != "JOIN") { @@ -10083,13 +10102,13 @@ namespace DynamORM type = type.Replace("OUTER", " OUTER ") .Replace(" ", " ") .Trim(' '); - + // x => x.Left()... int n = type.IndexOf("JOIN"); - + if (n < 0 && !avoid) type += " JOIN"; - + // x => x.InnerJoin() / x => x.JoinLeft() ... else { @@ -10100,17 +10119,17 @@ namespace DynamORM } } } - + node = node.Host; continue; } - + // Support for generic sources... if (node is DynamicParser.Node.Invoke) { if (owner != null) throw new ArgumentException(string.Format("Owner '{0}.{1}' is already set when parsing '{2}'.", owner, main, result)); - + if (main != null) owner = string.Format("{0}", Parse(node, rawstr: true, pars: justAddTables ? null : Parameters)); else @@ -10120,23 +10139,23 @@ namespace DynamORM { tableType = (Type)invoke.Arguments[0]; DynamicTypeMap mapper = DynamicMapperCache.GetMapper(tableType); - + if (mapper == null) throw new InvalidOperationException(string.Format("Cant assign unmapable type as a table ({0}).", tableType.FullName)); - + main = mapper.Table == null || string.IsNullOrEmpty(mapper.Table.Name) ? mapper.Type.Name : mapper.Table.Name; - + owner = (mapper.Table != null) ? mapper.Table.Owner : owner; } else main = string.Format("{0}", Parse(node, rawstr: true, pars: justAddTables ? null : Parameters)); } - + node = node.Host; continue; } - + // Just finished the parsing... if (node is DynamicParser.Node.Argument) break; throw new ArgumentException(string.Format("Specification #{0} is invalid: {1}", index, result)); @@ -10147,17 +10166,17 @@ namespace DynamORM // Or it is a not supported expression... throw new ArgumentException(string.Format("Specification #{0} is invalid: {1}", index, result)); } - + // We annotate the aliases being conservative... main = main.Validated("Main"); - + if (justAddTables) { if (!string.IsNullOrEmpty(main)) tableInfo = tableType == null ? new TableInfo(Database, main, alias, owner, nolock) : new TableInfo(Database, tableType, alias, owner, nolock); else throw new ArgumentException(string.Format("Specification #{0} is invalid: {1}", index, result)); - + Tables.Add(tableInfo); } else @@ -10166,40 +10185,40 @@ namespace DynamORM tableInfo = string.IsNullOrEmpty(alias) ? Tables.SingleOrDefault(t => t.Name == main && string.IsNullOrEmpty(t.Alias)) : Tables.SingleOrDefault(t => t.Alias == alias); - + // We finally add the contents if we can... StringBuilder sb = new StringBuilder(); if (string.IsNullOrEmpty(type)) type = "JOIN"; - + sb.AppendFormat("{0} ", type); - + if (!string.IsNullOrEmpty(tableInfo.Owner)) sb.AppendFormat("{0}.", Database.DecorateName(tableInfo.Owner)); - + sb.Append(tableInfo.Name.ContainsAny(StringExtensions.InvalidMemberChars) ? tableInfo.Name : Database.DecorateName(tableInfo.Name)); - + if (!string.IsNullOrEmpty(tableInfo.Alias)) sb.AppendFormat(" AS {0}", tableInfo.Alias); - + if (SupportNoLock && tableInfo.NoLock) sb.AppendFormat(" WITH(NOLOCK)"); - + if (!string.IsNullOrEmpty(condition)) sb.AppendFormat(" ON {0}", condition); - + _join = string.IsNullOrEmpty(_join) ? sb.ToString() : string.Format("{0} {1}", _join, sb.ToString()); // No comma in this case } } } - + return this; } - + #endregion From/Join - + #region Where - + /// /// Adds to the 'Where' clause the contents obtained from parsing the dynamic lambda expression given. The condition /// is parsed to the appropriate syntax, where the specific customs virtual methods supported by the parser are used @@ -10214,7 +10233,7 @@ namespace DynamORM { return this.InternalWhere(func); } - + /// Add where condition. /// Condition column with operator and value. /// Builder instance. @@ -10222,7 +10241,7 @@ namespace DynamORM { return this.InternalWhere(column); } - + /// Add where condition. /// Condition column. /// Condition operator. @@ -10232,7 +10251,7 @@ namespace DynamORM { return this.InternalWhere(column, op, value); } - + /// Add where condition. /// Condition column. /// Condition value. @@ -10241,7 +10260,7 @@ namespace DynamORM { return this.InternalWhere(column, value); } - + /// Add where condition. /// Set conditions as properties and values of an object. /// If true use schema to determine key columns and ignore those which @@ -10251,11 +10270,11 @@ namespace DynamORM { return this.InternalWhere(conditions, schema); } - + #endregion Where - + #region Select - + /// /// Adds to the 'Select' clause the contents obtained by parsing the dynamic lambda expressions given. The supported /// formats are: @@ -10272,41 +10291,41 @@ namespace DynamORM { if (fn == null) throw new ArgumentNullException("Array of specifications cannot be null."); - + int index = SelectFunc(-1, fn); if (func != null) foreach (Func f in func) index = SelectFunc(index, f); - + return this; } - + private int SelectFunc(int index, Func f) { index++; if (f == null) throw new ArgumentNullException(string.Format("Specification #{0} cannot be null.", index)); - + using (DynamicParser parser = DynamicParser.Parse(f)) { object result = parser.Result; if (result == null) throw new ArgumentException(string.Format("Specification #{0} resolves to null.", index)); - + string main = null; string alias = null; bool all = false; bool anon = false; - + // If the expression resolves to a string... if (result is string) { string node = (string)result; Tuple tuple = node.SplitSomethingAndAlias(); main = tuple.Item1.Validated("Table and/or Column"); - + main = FixObjectName(main); - + alias = tuple.Item2.Validated("Alias", canbeNull: true); } else if (result is DynamicParser.Node) @@ -10317,7 +10336,7 @@ namespace DynamORM else if (result.GetType().IsAnonymous()) { anon = true; - + foreach (KeyValuePair prop in result.ToDictionary()) { if (prop.Value is string) @@ -10325,7 +10344,7 @@ namespace DynamORM string node = (string)prop.Value; Tuple tuple = node.SplitSomethingAndAlias(); main = FixObjectName(tuple.Item1.Validated("Table and/or Column")); - + ////alias = tuple.Item2.Validated("Alias", canbeNull: true); } else if (prop.Value is DynamicParser.Node) @@ -10338,7 +10357,7 @@ namespace DynamORM // Or it is a not supported expression... throw new ArgumentException(string.Format("Specification #{0} in anonymous type is invalid: {1}", index, prop.Value)); } - + alias = Database.DecorateName(prop.Key); ParseSelectAddColumn(main, alias, all); } @@ -10348,14 +10367,14 @@ namespace DynamORM // Or it is a not supported expression... throw new ArgumentException(string.Format("Specification #{0} is invalid: {1}", index, result)); } - + if (!anon) ParseSelectAddColumn(main, alias, all); } - + return index; } - + /// Add select columns. /// Columns to add to object. /// Builder instance. @@ -10363,10 +10382,10 @@ namespace DynamORM { foreach (DynamicColumn col in columns) Select(x => col.ToSQLSelectColumn(Database)); - + return this; } - + /// Add select columns. /// Columns to add to object. /// Column format consist of Column Name, Alias and @@ -10377,14 +10396,14 @@ namespace DynamORM DynamicColumn[] cols = new DynamicColumn[columns.Length]; for (int i = 0; i < columns.Length; i++) cols[i] = DynamicColumn.ParseSelectColumn(columns[i]); - + return SelectColumn(cols); } - + #endregion Select - + #region GroupBy - + /// /// Adds to the 'Group By' clause the contents obtained from from parsing the dynamic lambda expression given. /// @@ -10395,48 +10414,48 @@ namespace DynamORM { if (fn == null) throw new ArgumentNullException("Array of specifications cannot be null."); - + int index = GroupByFunc(-1, fn); - + if (func != null) for (int i = 0; i < func.Length; i++) { Func f = func[i]; index = GroupByFunc(index, f); } - + return this; } - + private int GroupByFunc(int index, Func f) { index++; if (f == null) throw new ArgumentNullException(string.Format("Specification #{0} cannot be null.", index)); - + using (DynamicParser parser = DynamicParser.Parse(f)) { object result = parser.Result; if (result == null) throw new ArgumentException(string.Format("Specification #{0} resolves to null.", index)); - + string main = null; - + if (result is string) main = FixObjectName(result as string); else main = Parse(result, pars: Parameters); - + main = main.Validated("Group By"); if (_groupby == null) _groupby = main; else _groupby = string.Format("{0}, {1}", _groupby, main); } - + return index; } - + /// Add select columns. /// Columns to group by. /// Builder instance. @@ -10447,10 +10466,10 @@ namespace DynamORM DynamicColumn col = columns[i]; GroupBy(x => col.ToSQLGroupByColumn(Database)); } - + return this; } - + /// Add select columns. /// Columns to group by. /// Column format consist of Column Name and @@ -10460,11 +10479,11 @@ namespace DynamORM { return GroupByColumn(columns.Select(c => DynamicColumn.ParseSelectColumn(c)).ToArray()); } - + #endregion GroupBy - + #region Having - + /// /// Adds to the 'Having' clause the contents obtained from parsing the dynamic lambda expression given. The condition /// is parsed to the appropriate syntax, Having the specific customs virtual methods supported by the parser are used @@ -10479,7 +10498,7 @@ namespace DynamORM { return this.InternalHaving(func); } - + /// Add Having condition. /// Condition column with operator and value. /// Builder instance. @@ -10487,7 +10506,7 @@ namespace DynamORM { return this.InternalHaving(column); } - + /// Add Having condition. /// Condition column. /// Condition operator. @@ -10497,7 +10516,7 @@ namespace DynamORM { return this.InternalHaving(column, op, value); } - + /// Add Having condition. /// Condition column. /// Condition value. @@ -10506,7 +10525,7 @@ namespace DynamORM { return this.InternalHaving(column, value); } - + /// Add Having condition. /// Set conditions as properties and values of an object. /// If true use schema to determine key columns and ignore those which @@ -10516,11 +10535,11 @@ namespace DynamORM { return this.InternalHaving(conditions, schema); } - + #endregion Having - + #region OrderBy - + /// /// Adds to the 'Order By' clause the contents obtained from from parsing the dynamic lambda expression given. It /// accepts a multipart column specification followed by an optional Ascending() or Descending() virtual methods @@ -10534,44 +10553,44 @@ namespace DynamORM { if (fn == null) throw new ArgumentNullException("Array of specifications cannot be null."); - + int index = OrderByFunc(-1, fn); - + if (func != null) for (int i = 0; i < func.Length; i++) { Func f = func[i]; index = OrderByFunc(index, f); } - + return this; } - + private int OrderByFunc(int index, Func f) { index++; if (f == null) throw new ArgumentNullException(string.Format("Specification #{0} cannot be null.", index)); - + using (DynamicParser parser = DynamicParser.Parse(f)) { object result = parser.Result; if (result == null) throw new ArgumentException(string.Format("Specification #{0} resolves to null.", index)); - + string main = null; bool ascending = true; - + if (result is int) main = result.ToString(); else if (result is string) { string[] parts = ((string)result).Split(' '); main = Database.StripName(parts.First()); - + int colNo; if (!Int32.TryParse(main, out colNo)) main = FixObjectName(main); - + ascending = parts.Length != 2 || parts.Last().ToUpper() == "ASCENDING" || parts.Last().ToUpper() == "ASC"; } else @@ -10588,9 +10607,9 @@ namespace DynamORM throw new ArgumentException(string.Format("{0} must be a parameterless method, but found: {1}.", name, args.Sketch())); else if ((args == null || args.Length != 1) && node.Host is DynamicParser.Node.Argument) throw new ArgumentException(string.Format("{0} requires one numeric parameter, but found: {1}.", name, args.Sketch())); - + ascending = (name == "ASCENDING" || name == "ASC") ? true : false; - + if (args != null && args.Length == 1) { int col = -1; @@ -10606,28 +10625,28 @@ namespace DynamORM else main = Parse(args[0], pars: Parameters); } - + result = node.Host; } } - + // Just parsing the contents... if (!(result is DynamicParser.Node.Argument)) main = Parse(result, pars: Parameters); } - + main = main.Validated("Order By"); main = string.Format("{0} {1}", main, ascending ? "ASC" : "DESC"); - + if (_orderby == null) _orderby = main; else _orderby = string.Format("{0}, {1}", _orderby, main); } - + return index; } - + /// Add select columns. /// Columns to order by. /// Builder instance. @@ -10638,10 +10657,10 @@ namespace DynamORM DynamicColumn col = columns[i]; OrderBy(x => col.ToSQLOrderByColumn(Database)); } - + return this; } - + /// Add select columns. /// Columns to order by. /// Column format consist of Column Name and @@ -10651,11 +10670,11 @@ namespace DynamORM { return OrderByColumn(columns.Select(c => DynamicColumn.ParseOrderByColumn(c)).ToArray()); } - + #endregion OrderBy - + #region Top/Limit/Offset/Distinct - + /// Set top if database support it. /// How many objects select. /// Builder instance. @@ -10663,7 +10682,7 @@ namespace DynamORM { return Limit(top); } - + /// Set top if database support it. /// How many objects select. /// Builder instance. @@ -10673,11 +10692,11 @@ namespace DynamORM (Database.Options & DynamicDatabaseOptions.SupportFirstSkip) != DynamicDatabaseOptions.SupportFirstSkip && (Database.Options & DynamicDatabaseOptions.SupportTop) != DynamicDatabaseOptions.SupportTop) throw new NotSupportedException("Database doesn't support LIMIT clause."); - + _limit = limit; return this; } - + /// Set top if database support it. /// How many objects skip selecting. /// Builder instance. @@ -10686,11 +10705,11 @@ namespace DynamORM if ((Database.Options & DynamicDatabaseOptions.SupportLimitOffset) != DynamicDatabaseOptions.SupportLimitOffset && (Database.Options & DynamicDatabaseOptions.SupportFirstSkip) != DynamicDatabaseOptions.SupportFirstSkip) throw new NotSupportedException("Database doesn't support OFFSET clause."); - + _offset = offset; return this; } - + /// Set distinct mode. /// Distinct mode. /// Builder instance. @@ -10699,31 +10718,31 @@ namespace DynamORM _distinct = distinct; return this; } - + #endregion Top/Limit/Offset/Distinct - + #region Helpers - + private void ParseSelectAddColumn(string main, string alias, bool all) { // We annotate the aliases being conservative... main = main.Validated("Main"); - + ////if (alias != null && !main.ContainsAny(StringExtensions.InvalidMemberChars)) TableAliasList.Add(new KTableAlias(main, alias)); - + // If all columns are requested... if (all) main += ".*"; - + // We finally add the contents... string str = (alias == null || all) ? main : string.Format("{0} AS {1}", main, alias); _select = _select == null ? str : string.Format("{0}, {1}", _select, str); } - + private void ParseSelectNode(object result, ref string column, ref string alias, ref bool all) { string main = null; - + DynamicParser.Node node = (DynamicParser.Node)result; while (true) { @@ -10732,59 +10751,59 @@ namespace DynamORM { if (alias != null) throw new ArgumentException(string.Format("Alias '{0}' is already set when parsing '{1}'.", alias, result)); - + object[] args = ((DynamicParser.Node.Method)node).Arguments; - + if (args == null) throw new ArgumentNullException("arg", "AS() is not a parameterless method."); - + if (args.Length != 1) throw new ArgumentException("AS() requires one and only one parameter: " + args.Sketch()); - + // Yes, we decorate columns alias = Parse(args[0], rawstr: true, decorate: true, isMultiPart: false).Validated("Alias"); - + node = node.Host; continue; } - + // Support for the ALL() virtual method... if (node is DynamicParser.Node.Method && ((DynamicParser.Node.Method)node).Name.ToUpper() == "ALL") { if (all) throw new ArgumentException(string.Format("Flag to select all columns is already set when parsing '{0}'.", result)); - + object[] args = ((DynamicParser.Node.Method)node).Arguments; - + if (args != null) throw new ArgumentException("ALL() must be a parameterless virtual method, but found: " + args.Sketch()); - + all = true; - + node = node.Host; continue; } - + // Support for table and/or column specifications... if (node is DynamicParser.Node.GetMember) { if (main != null) throw new ArgumentException(string.Format("Main '{0}' is already set when parsing '{1}'.", main, result)); - + main = ((DynamicParser.Node.GetMember)node).Name; - + if (node.Host is DynamicParser.Node.GetMember) { // If leaf then decorate main = Database.DecorateName(main); - + // Supporting multipart specifications... node = node.Host; - + // Get table/alias name string table = ((DynamicParser.Node.GetMember)node).Name; bool isAlias = node.Host is DynamicParser.Node.Argument && IsTableAlias(table); - + if (isAlias) main = string.Format("{0}.{1}", table, main); else if (node.Host is DynamicParser.Node.GetMember) @@ -10800,7 +10819,7 @@ namespace DynamORM else if (node.Host is DynamicParser.Node.Argument) { string table = ((DynamicParser.Node.Argument)node.Host).Name; - + if (IsTableAlias(table)) main = string.Format("{0}.{1}", table, Database.DecorateName(main)); else if (!IsTableAlias(main)) @@ -10808,74 +10827,74 @@ namespace DynamORM } else if (!(node.Host is DynamicParser.Node.Argument && IsTableAlias(main))) main = Database.DecorateName(main); - + node = node.Host; - + continue; } - + // Support for generic sources... if (node is DynamicParser.Node.Invoke) { if (main != null) throw new ArgumentException(string.Format("Main '{0}' is already set when parsing '{1}'.", main, result)); - + main = string.Format("{0}", Parse(node, rawstr: true, pars: Parameters)); - + node = node.Host; continue; } - + // Just finished the parsing... if (node is DynamicParser.Node.Argument) { if (string.IsNullOrEmpty(main) && IsTableAlias(node.Name)) main = node.Name; - + break; } - + // All others are assumed to be part of the main element... if (main != null) throw new ArgumentException(string.Format("Main '{0}' is already set when parsing '{1}'.", main, result)); main = Parse(node, pars: Parameters); - + break; } - + column = main; } - + #endregion Helpers - + #region IExtendedDisposable - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. public override void Dispose() { base.Dispose(); - + _select = _from = _join = _groupby = _orderby = null; } - + #endregion IExtendedDisposable } - + /// Update query builder. internal class DynamicUpdateQueryBuilder : DynamicModifyBuilder, IDynamicUpdateQueryBuilder, DynamicQueryBuilder.IQueryWithWhere { private string _columns; - + internal DynamicUpdateQueryBuilder(DynamicDatabase db) : base(db) { } - + public DynamicUpdateQueryBuilder(DynamicDatabase db, string tableName) : base(db, tableName) { } - + /// Generates the text this command will execute against the underlying database. /// The text to execute against the underlying database. /// This method must be override by derived classes. @@ -10888,9 +10907,9 @@ namespace DynamORM string.IsNullOrEmpty(WhereCondition) ? string.Empty : " WHERE ", WhereCondition); } - + #region Update - + /// Add update value or where condition using schema. /// Update or where column name. /// Column value. @@ -10898,18 +10917,18 @@ namespace DynamORM public virtual IDynamicUpdateQueryBuilder Update(string column, object value) { DynamicSchemaColumn? col = GetColumnFromSchema(column); - + if (!col.HasValue && SupportSchema) throw new InvalidOperationException(string.Format("Column '{0}' not found in schema, can't use universal approach.", column)); - + if (col.HasValue && col.Value.IsKey) Where(column, value); else Values(column, value); - + return this; } - + /// Add update values and where condition columns using schema. /// Set values or conditions as properties and values of an object. /// Builder instance. @@ -10918,58 +10937,58 @@ namespace DynamORM if (conditions is DynamicColumn) { DynamicColumn column = (DynamicColumn)conditions; - + DynamicSchemaColumn? col = column.Schema ?? GetColumnFromSchema(column.ColumnName); - + if (!col.HasValue && SupportSchema) throw new InvalidOperationException(string.Format("Column '{0}' not found in schema, can't use universal approach.", column)); - + if (col.HasValue && col.Value.IsKey) Where(column); else Values(column.ColumnName, column.Value); - + return this; } - + IDictionary dict = conditions.ToDictionary(); DynamicTypeMap mapper = DynamicMapperCache.GetMapper(conditions.GetType()); - + foreach (KeyValuePair con in dict) { if (mapper.Ignored.Contains(con.Key)) continue; - + string colName = mapper != null ? mapper.PropertyMap.TryGetValue(con.Key) ?? con.Key : con.Key; DynamicSchemaColumn? col = GetColumnFromSchema(colName); - + if (!col.HasValue && SupportSchema) throw new InvalidOperationException(string.Format("Column '{0}' not found in schema, can't use universal approach.", colName)); - + if (col.HasValue) { colName = col.Value.Name; - + if (col.Value.IsKey) { Where(colName, con.Value); - + continue; } } - + DynamicPropertyInvoker propMap = mapper.ColumnsMap.TryGetValue(colName.ToLower()); if (propMap == null || propMap.Column == null || !propMap.Column.IsNoUpdate) Values(colName, con.Value); } - + return this; } - + #endregion Update - + #region Values - + /// /// Specifies the columns to update using the dynamic lambda expressions given. Each expression correspond to one /// column, and can: @@ -10982,36 +11001,36 @@ namespace DynamORM { if (func == null) throw new ArgumentNullException("Array of specifications cannot be null."); - + int index = -1; foreach (Func f in func) { index++; if (f == null) throw new ArgumentNullException(string.Format("Specification #{0} cannot be null.", index)); - + object result = null; - + using (DynamicParser p = DynamicParser.Parse(f)) { result = p.Result; - + if (result == null) throw new ArgumentException(string.Format("Specification #{0} resolves to null.", index)); - + string main = null; string value = null; string str = null; - + // When 'x => x.Table.Column = value' or 'x => x.Column = value'... if (result is DynamicParser.Node.SetMember) { DynamicParser.Node.SetMember node = (DynamicParser.Node.SetMember)result; - + DynamicSchemaColumn? col = GetColumnFromSchema(node.Name); main = Database.DecorateName(node.Name); value = Parse(node.Value, ref col, pars: Parameters, nulls: true); - + str = string.Format("{0} = {1}", main, value); _columns = _columns == null ? str : string.Format("{0}, {1}", _columns, str); continue; @@ -11021,7 +11040,7 @@ namespace DynamORM Values(result); continue; } - + // Other specifications are considered invalid... string err = string.Format("Specification '{0}' is invalid.", result); str = Parse(result); @@ -11029,10 +11048,10 @@ namespace DynamORM throw new ArgumentException(err); } } - + return this; } - + /// Add insert fields. /// Insert column. /// Insert value. @@ -11042,20 +11061,20 @@ namespace DynamORM if (value is DynamicColumn) { DynamicColumn v = (DynamicColumn)value; - + if (string.IsNullOrEmpty(v.ColumnName)) v.ColumnName = column; - + return Values(v); } - + return Values(new DynamicColumn { ColumnName = column, Value = value, }); } - + /// Add insert fields. /// Set insert value as properties and values of an object. /// Builder instance. @@ -11065,19 +11084,19 @@ namespace DynamORM { DynamicColumn column = (DynamicColumn)o; DynamicSchemaColumn? col = column.Schema ?? GetColumnFromSchema(column.ColumnName); - + string main = FixObjectName(column.ColumnName, onlyColumn: true); string value = Parse(column.Value, ref col, pars: Parameters, nulls: true); - + string str = string.Format("{0} = {1}", main, value); _columns = _columns == null ? str : string.Format("{0}, {1}", _columns, str); - + return this; } - + IDictionary dict = o.ToDictionary(); DynamicTypeMap mapper = DynamicMapperCache.GetMapper(o.GetType()); - + if (mapper != null) { foreach (KeyValuePair con in dict) @@ -11087,14 +11106,14 @@ namespace DynamORM else foreach (KeyValuePair con in dict) Values(con.Key, con.Value); - + return this; } - + #endregion Values - + #region Where - + /// /// Adds to the 'Where' clause the contents obtained from parsing the dynamic lambda expression given. The condition /// is parsed to the appropriate syntax, where the specific customs virtual methods supported by the parser are used @@ -11109,7 +11128,7 @@ namespace DynamORM { return this.InternalWhere(func); } - + /// Add where condition. /// Condition column with operator and value. /// Builder instance. @@ -11117,7 +11136,7 @@ namespace DynamORM { return this.InternalWhere(column); } - + /// Add where condition. /// Condition column. /// Condition operator. @@ -11127,7 +11146,7 @@ namespace DynamORM { return this.InternalWhere(column, op, value); } - + /// Add where condition. /// Condition column. /// Condition value. @@ -11136,7 +11155,7 @@ namespace DynamORM { return this.InternalWhere(column, value); } - + /// Add where condition. /// Set conditions as properties and values of an object. /// If true use schema to determine key columns and ignore those which @@ -11146,27 +11165,27 @@ namespace DynamORM { return this.InternalWhere(conditions, schema); } - + #endregion Where - + #region IExtendedDisposable - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. public override void Dispose() { base.Dispose(); - + _columns = null; } - + #endregion IExtendedDisposable } } } namespace Helpers - { + { /// Defines methods to support the comparison of collections for equality. /// The type of collection to compare. public class CollectionComparer : IEqualityComparer> @@ -11179,7 +11198,7 @@ namespace DynamORM { return Equals(first, second); } - + /// Returns a hash code for the specified object. /// The enumerable for which a hash code is to be returned. /// A hash code for the specified object. @@ -11187,20 +11206,20 @@ namespace DynamORM { return GetHashCode(enumerable); } - + /// Returns a hash code for the specified object. /// The enumerable for which a hash code is to be returned. /// A hash code for the specified object. public static int GetHashCode(IEnumerable enumerable) { int hash = 17; - + foreach (T val in enumerable.OrderBy(x => x)) hash = (hash * 23) + val.GetHashCode(); - + return hash; } - + /// Determines whether the specified objects are equal. /// The first object of type T to compare. /// The second object of type T to compare. @@ -11209,42 +11228,42 @@ namespace DynamORM { if ((first == null) != (second == null)) return false; - + if (!object.ReferenceEquals(first, second) && (first != null)) { if (first.Count() != second.Count()) return false; - + if ((first.Count() != 0) && HaveMismatchedElement(first, second)) return false; } - + return true; } - + private static bool HaveMismatchedElement(IEnumerable first, IEnumerable second) { int firstCount; int secondCount; - + Dictionary firstElementCounts = GetElementCounts(first, out firstCount); Dictionary secondElementCounts = GetElementCounts(second, out secondCount); - + if (firstCount != secondCount) return true; - + foreach (KeyValuePair kvp in firstElementCounts) if (kvp.Value != (secondElementCounts.TryGetNullable(kvp.Key) ?? 0)) return true; - + return false; } - + private static Dictionary GetElementCounts(IEnumerable enumerable, out int nullCount) { Dictionary dictionary = new Dictionary(); nullCount = 0; - + foreach (T element in enumerable) { if (element == null) @@ -11255,11 +11274,11 @@ namespace DynamORM dictionary[element] = ++count; } } - + return dictionary; } } - + /// Extensions for data reader handling. public static class DataReaderExtensions { @@ -11272,66 +11291,66 @@ namespace DynamORM { DataTable schemaTable = r.GetSchemaTable(); DataTable resultTable = new DataTable(name, nameSpace); - + foreach (DataRow col in schemaTable.Rows) { dynamic c = col.RowToDynamicUpper(); - + DataColumn dataColumn = new DataColumn(); dataColumn.ColumnName = c.COLUMNNAME; dataColumn.DataType = (Type)c.DATATYPE; dataColumn.ReadOnly = true; dataColumn.Unique = c.ISUNIQUE; - + resultTable.Columns.Add(dataColumn); } - + while (r.Read()) { DataRow row = resultTable.NewRow(); for (int i = 0; i < resultTable.Columns.Count; i++) row[i] = r[i]; - + resultTable.Rows.Add(row); } - + return resultTable; } } - + /// Framework detection and specific implementations. public static class FrameworkTools { #region Mono or .NET Framework detection - + /// This is pretty simple trick. private static bool _isMono = Type.GetType("Mono.Runtime") != null; - + /// Gets a value indicating whether application is running under mono runtime. public static bool IsMono { get { return _isMono; } } - + #endregion Mono or .NET Framework detection - + static FrameworkTools() { _frameworkTypeArgumentsGetter = CreateTypeArgumentsGetter(); } - + #region GetGenericTypeArguments - + private static Func> _frameworkTypeArgumentsGetter = null; - + private static Func> CreateTypeArgumentsGetter() { // HACK: Creating binders assuming types are correct... this may fail. if (IsMono) { Type binderType = typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly.GetType("Microsoft.CSharp.RuntimeBinder.CSharpInvokeMemberBinder"); - + if (binderType != null) { ParameterExpression param = Expression.Parameter(typeof(InvokeMemberBinder), "o"); - + try { return Expression.Lambda>>( @@ -11343,12 +11362,12 @@ namespace DynamORM catch { } - + PropertyInfo prop = binderType.GetProperty("TypeArguments"); - + if (!prop.CanRead) return null; - + return Expression.Lambda>>( Expression.TypeAs( Expression.Property( @@ -11359,16 +11378,16 @@ namespace DynamORM else { Type inter = typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly.GetType("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); - + if (inter != null) { PropertyInfo prop = inter.GetProperty("TypeArguments"); - + if (!prop.CanRead) return null; - + ParameterExpression objParm = Expression.Parameter(typeof(InvokeMemberBinder), "o"); - + return Expression.Lambda>>( Expression.TypeAs( Expression.Property( @@ -11376,10 +11395,10 @@ namespace DynamORM typeof(IList)), objParm).Compile(); } } - + return null; } - + /// Extension method allowing to easily extract generic type /// arguments from assuming that it /// inherits from @@ -11396,23 +11415,23 @@ namespace DynamORM // First try to use delegate if exist if (_frameworkTypeArgumentsGetter != null) return _frameworkTypeArgumentsGetter(binder); - + if (_isMono) { // HACK: Using Reflection // In mono this is trivial. - + // First we get field info. FieldInfo field = binder.GetType().GetField("typeArguments", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); - + // If this was a success get and return it's value if (field != null) return field.GetValue(binder) as IList; else { PropertyInfo prop = binder.GetType().GetProperty("TypeArguments"); - + // If we have a property, return it's value if (prop != null) return prop.GetValue(binder, null) as IList; @@ -11422,28 +11441,28 @@ namespace DynamORM { // HACK: Using Reflection // In this case, we need more aerobic :D - + // First, get the interface Type inter = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); - + if (inter != null) { // Now get property. PropertyInfo prop = inter.GetProperty("TypeArguments"); - + // If we have a property, return it's value if (prop != null) return prop.GetValue(binder, null) as IList; } } - + // Sadly return null if failed. return null; } - + #endregion GetGenericTypeArguments } - + /// Extends interface. public interface IExtendedDisposable : IDisposable { @@ -11455,7 +11474,7 @@ namespace DynamORM /// bool IsDisposed { get; } } - + /// Extends interface. public interface IFinalizerDisposable : IExtendedDisposable { @@ -11464,7 +11483,7 @@ namespace DynamORM /// If set to true dispose object. void Dispose(bool disposing); } - + /// Class containing useful string extensions. internal static class StringExtensions { @@ -11473,20 +11492,20 @@ namespace DynamORM InvalidMultipartMemberChars = _InvalidMultipartMemberChars.ToCharArray(); InvalidMemberChars = _InvalidMemberChars.ToCharArray(); } - + private static readonly string _InvalidMultipartMemberChars = " +-*/^%[]{}()!\"\\&=?¿"; private static readonly string _InvalidMemberChars = "." + _InvalidMultipartMemberChars; - + /// /// Gets an array with some invalid characters that cannot be used with multipart names for class members. /// public static char[] InvalidMultipartMemberChars { get; private set; } - + /// /// Gets an array with some invalid characters that cannot be used with names for class members. /// public static char[] InvalidMemberChars { get; private set; } - + /// /// Provides with an alternate and generic way to obtain an alternate string representation for this instance, /// applying the following rules: @@ -11508,34 +11527,34 @@ namespace DynamORM { if (obj == null) return nullString; if (obj is string) return (string)obj; - + Type type = obj.GetType(); if (type.IsEnum) return obj.ToString(); - + // If the ToString() method has been overriden (by the type itself, or by its parents), let's use it... MethodInfo method = type.GetMethod("ToString", Type.EmptyTypes); if (method.DeclaringType != typeof(object)) return obj.ToString(); - + // For alll other cases... StringBuilder sb = new StringBuilder(); bool first = true; - + // Dictionaries... if (obj is IDictionary) { if (brackets == null || brackets.Length < 2) brackets = "[]".ToCharArray(); - + sb.AppendFormat("{0}", brackets[0]); first = true; foreach (DictionaryEntry kvp in (IDictionary)obj) { if (!first) sb.Append(", "); else first = false; sb.AppendFormat("'{0}'='{1}'", kvp.Key.Sketch(), kvp.Value.Sketch()); } - + sb.AppendFormat("{0}", brackets[1]); return sb.ToString(); } - + // IEnumerables... IEnumerator ator = null; if (obj is IEnumerable) @@ -11546,7 +11565,7 @@ namespace DynamORM if (method != null) ator = (IEnumerator)method.Invoke(obj, null); } - + if (ator != null) { if (brackets == null || brackets.Length < 2) brackets = "[]".ToCharArray(); @@ -11555,27 +11574,27 @@ namespace DynamORM if (!first) sb.Append(", "); else first = false; sb.AppendFormat("{0}", ator.Current.Sketch()); } - + sb.AppendFormat("{0}", brackets[1]); - + if (ator is IDisposable) ((IDisposable)ator).Dispose(); - + return sb.ToString(); } - + // As a last resort, using the public properties (or fields if needed, or type name)... BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy; PropertyInfo[] props = type.GetProperties(flags); FieldInfo[] infos = type.GetFields(flags); - + if (props.Length == 0 && infos.Length == 0) sb.Append(type.FullName); // Fallback if needed else { if (brackets == null || brackets.Length < 2) brackets = "{}".ToCharArray(); sb.AppendFormat("{0}", brackets[0]); first = true; - + if (props.Length != 0) { foreach (PropertyInfo prop in props) @@ -11595,14 +11614,14 @@ namespace DynamORM } } } - + sb.AppendFormat("{0}", brackets[1]); } - + // And returning... return sb.ToString(); } - + /// /// Returns true if the target string contains any of the characters given. /// @@ -11613,12 +11632,12 @@ namespace DynamORM { if (source == null) throw new ArgumentNullException("source", "Source string cannot be null."); if (items == null) throw new ArgumentNullException("items", "Array of characters to test cannot be null."); - + if (items.Length == 0) return false; // No characters to validate int ix = source.IndexOfAny(items); return ix >= 0 ? true : false; } - + /// /// Returns a new validated string using the rules given. /// @@ -11646,14 +11665,14 @@ namespace DynamORM { // Assuring a valid descriptor... if (string.IsNullOrWhiteSpace(desc)) desc = "Source"; - + // Validating if null sources are accepted... if (source == null) { if (!canbeNull) throw new ArgumentNullException(desc, string.Format("{0} cannot be null.", desc)); return null; } - + // Trimming if needed... if (trim && !(trimStart || trimEnd)) source = source.Trim(); else @@ -11661,47 +11680,47 @@ namespace DynamORM if (trimStart) source = source.TrimStart(' '); if (trimEnd) source = source.TrimEnd(' '); } - + // Adjusting lenght... if (minLen > 0) { if (padLeft != '\0') source = source.PadLeft(minLen, padLeft); if (padRight != '\0') source = source.PadRight(minLen, padRight); } - + if (maxLen > 0) { if (padLeft != '\0') source = source.PadLeft(maxLen, padLeft); if (padRight != '\0') source = source.PadRight(maxLen, padRight); } - + // Validating emptyness and lenghts... if (source.Length == 0) { if (!canbeEmpty) throw new ArgumentException(string.Format("{0} cannot be empty.", desc)); return string.Empty; } - + if (minLen >= 0 && source.Length < minLen) throw new ArgumentException(string.Format("Lenght of {0} '{1}' is lower than '{2}'.", desc, source, minLen)); if (maxLen >= 0 && source.Length > maxLen) throw new ArgumentException(string.Format("Lenght of {0} '{1}' is bigger than '{2}'.", desc, source, maxLen)); - + // Checking invalid chars... if (invalidChars != null) { int n = source.IndexOfAny(invalidChars); if (n >= 0) throw new ArgumentException(string.Format("Invalid character '{0}' found in {1} '{2}'.", source[n], desc, source)); } - + // Checking valid chars... if (validChars != null) { int n = validChars.ToString().IndexOfAny(source.ToCharArray()); if (n >= 0) throw new ArgumentException(string.Format("Invalid character '{0}' found in {1} '{2}'.", validChars.ToString()[n], desc, source)); } - + return source; } - + /// /// Splits the given string with the 'something AS alias' format, returning a tuple containing its 'something' and 'alias' parts. /// If no alias is detected, then its component in the tuple returned is null and all the contents from the source @@ -11712,11 +11731,11 @@ namespace DynamORM public static Tuple SplitSomethingAndAlias(this string source) { source = source.Validated("[Something AS Alias]"); - + string something = null; string alias = null; int n = source.LastIndexOf(" AS ", StringComparison.OrdinalIgnoreCase); - + if (n < 0) something = source; else @@ -11724,10 +11743,10 @@ namespace DynamORM something = source.Substring(0, n); alias = source.Substring(n + 4); } - + return new Tuple(something, alias); } - + /// Allows to replace parameters inside of string. /// String containing parameters in format [$ParameterName]. /// Function that should return value that will be placed in string in place of placed parameter. @@ -11739,29 +11758,29 @@ namespace DynamORM int startPos = 0, endPos = 0; prefix.Validated(); sufix.Validated(); - + startPos = stringToFill.IndexOf(prefix, startPos); while (startPos >= 0) { endPos = stringToFill.IndexOf(sufix, startPos + prefix.Length); int nextStartPos = stringToFill.IndexOf(prefix, startPos + prefix.Length); - + if (endPos > startPos + prefix.Length + 1 && (nextStartPos > endPos || nextStartPos == -1)) { string paramName = stringToFill.Substring(startPos + prefix.Length, endPos - (startPos + prefix.Length)); - + stringToFill = stringToFill .Remove(startPos, (endPos - startPos) + sufix.Length) .Insert(startPos, getValue(paramName)); } - + startPos = stringToFill.IndexOf(prefix, startPos + prefix.Length); } - + return stringToFill; } } - + /// Class contains unclassified extensions. internal static class UnclassifiedExtensions { @@ -11783,7 +11802,7 @@ namespace DynamORM return obj != null && obj != DBNull.Value ? func(obj) : elseValue; } - + /// Easy way to use conditional value. /// Includes . /// Input object type to check. @@ -11803,8 +11822,8 @@ namespace DynamORM return obj != null && obj != DBNull.Value ? func(obj) : elseFunc != null ? elseFunc() : default(R); } - - #if !NET6_0_OR_GREATER + +#if !NET6_0_OR_GREATER /// Simple distinct by selector extension. /// The enumerator of elements distinct by specified selector. /// Source collection. @@ -11818,18 +11837,18 @@ namespace DynamORM if (seenKeys.Add(keySelector(element))) yield return element; } - #endif +#endif } namespace Dynamics - { + { /// /// Class able to parse dynamic lambda expressions. Allows to create dynamic logic. /// public class DynamicParser : IExtendedDisposable { #region Node - + /// /// Generic bindable operation where some of its operands is a dynamic argument, or a dynamic member or /// a method of that argument. @@ -11838,9 +11857,9 @@ namespace DynamORM public class Node : IDynamicMetaObjectProvider, IFinalizerDisposable, ISerializable { private DynamicParser _parser = null; - + #region MetaNode - + /// /// Represents the dynamic binding and a binding logic of /// an object participating in the dynamic binding. @@ -11857,20 +11876,20 @@ namespace DynamORM : base(parameter, rest, value) { } - + // Func was cool but caused memory leaks private DynamicMetaObject GetBinder(Node node) { Node o = (Node)this.Value; node.Parser = o.Parser; o.Parser.Last = node; - + ParameterExpression p = Expression.Variable(typeof(Node), "ret"); BlockExpression exp = Expression.Block(new ParameterExpression[] { p }, Expression.Assign(p, Expression.Constant(node))); - + return new MetaNode(exp, this.Restrictions, node); } - + /// /// Performs the binding of the dynamic get member operation. /// @@ -11882,7 +11901,7 @@ namespace DynamORM { return GetBinder(new GetMember((Node)this.Value, binder.Name)); } - + /// /// Performs the binding of the dynamic set member operation. /// @@ -11895,7 +11914,7 @@ namespace DynamORM { return GetBinder(new SetMember((Node)this.Value, binder.Name, value.Value)); } - + /// /// Performs the binding of the dynamic get index operation. /// @@ -11908,7 +11927,7 @@ namespace DynamORM { return GetBinder(new GetIndex((Node)this.Value, MetaList2List(indexes))); } - + /// /// Performs the binding of the dynamic set index operation. /// @@ -11922,7 +11941,7 @@ namespace DynamORM { return GetBinder(new SetIndex((Node)this.Value, MetaList2List(indexes), value.Value)); } - + /// /// Performs the binding of the dynamic invoke operation. /// @@ -11935,7 +11954,7 @@ namespace DynamORM { return GetBinder(new Invoke((Node)this.Value, MetaList2List(args))); } - + /// /// Performs the binding of the dynamic invoke member operation. /// @@ -11948,7 +11967,7 @@ namespace DynamORM { return GetBinder(new Method((Node)this.Value, binder.Name, MetaList2List(args))); } - + /// /// Performs the binding of the dynamic binary operation. /// @@ -11961,7 +11980,7 @@ namespace DynamORM { return GetBinder(new Binary((Node)this.Value, binder.Operation, arg.Value)); } - + /// /// Performs the binding of the dynamic unary operation. /// @@ -11974,20 +11993,20 @@ namespace DynamORM Node o = (Node)this.Value; Unary node = new Unary(o, binder.Operation) { Parser = o.Parser }; o.Parser.Last = node; - + // If operation is 'IsTrue' or 'IsFalse', we will return false to keep the engine working... object ret = node; if (binder.Operation == ExpressionType.IsTrue) ret = (object)false; if (binder.Operation == ExpressionType.IsFalse) ret = (object)false; - + ParameterExpression p = Expression.Variable(ret.GetType(), "ret"); // the type is now obtained from "ret" BlockExpression exp = Expression.Block( new ParameterExpression[] { p }, Expression.Assign(p, Expression.Constant(ret))); // the expression is now obtained from "ret" - + return new MetaNode(exp, this.Restrictions, node); } - + /// /// Performs the binding of the dynamic conversion operation. /// @@ -12000,11 +12019,11 @@ namespace DynamORM Node o = (Node)this.Value; Convert node = new Convert(o, binder.ReturnType) { Parser = o.Parser }; o.Parser.Last = node; - + // Reducing the object to return if this is an assignment node... object ret = o; bool done = false; - + while (!done) { if (ret is SetMember) @@ -12014,7 +12033,7 @@ namespace DynamORM else done = true; } - + // Creating an instance... if (binder.ReturnType == typeof(string)) ret = ret.ToString(); else @@ -12032,31 +12051,31 @@ namespace DynamORM ret = new object(); } } - + ParameterExpression p = Expression.Variable(binder.ReturnType, "ret"); BlockExpression exp = Expression.Block( new ParameterExpression[] { p }, Expression.Assign(p, Expression.Constant(ret, binder.ReturnType))); // specifying binder.ReturnType - + return new MetaNode(exp, this.Restrictions, node); } - + private static object[] MetaList2List(DynamicMetaObject[] metaObjects) { if (metaObjects == null) return null; - + object[] list = new object[metaObjects.Length]; for (int i = 0; i < metaObjects.Length; i++) list[i] = metaObjects[i].Value; - + return list; } } - + #endregion MetaNode - + #region Argument - + /// /// Describe a dynamic argument used in a dynamic lambda expression. /// @@ -12071,7 +12090,7 @@ namespace DynamORM : base(name) { } - + /// /// Initializes a new instance of the class. /// @@ -12081,7 +12100,7 @@ namespace DynamORM : base(info, context) { } - + /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() @@ -12091,11 +12110,11 @@ namespace DynamORM return Name; } } - + #endregion Argument - + #region GetMember - + /// /// Describe a 'get member' operation, as in 'x => x.Member'. /// @@ -12111,7 +12130,7 @@ namespace DynamORM : base(host, name) { } - + /// /// Initializes a new instance of the class. /// @@ -12121,7 +12140,7 @@ namespace DynamORM : base(info, context) { } - + /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() @@ -12131,11 +12150,11 @@ namespace DynamORM return string.Format("{0}.{1}", Host.Sketch(), Name.Sketch()); } } - + #endregion GetMember - + #region SetMember - + /// /// Describe a 'set member' operation, as in 'x => x.Member = y'. /// @@ -12147,7 +12166,7 @@ namespace DynamORM /// assigned to this instance, or if this instance is disposed. /// public object Value { get; private set; } - + /// /// Initializes a new instance of the class. /// @@ -12159,7 +12178,7 @@ namespace DynamORM { Value = value; } - + /// /// Initializes a new instance of the class. /// @@ -12171,7 +12190,7 @@ namespace DynamORM string type = info.GetString("MemberType"); Value = type == "NULL" ? null : info.GetValue("MemberValue", Type.GetType(type)); } - + /// /// Gets the object data. /// @@ -12182,10 +12201,10 @@ namespace DynamORM info.AddValue("MemberType", Value == null ? "NULL" : Value.GetType().AssemblyQualifiedName); if (Value != null) info.AddValue("MemberValue", Value); - + base.GetObjectData(info, context); } - + /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() @@ -12194,7 +12213,7 @@ namespace DynamORM return "{DynamicParser::Node::SetMember::Disposed}"; return string.Format("({0}.{1} = {2})", Host.Sketch(), Name.Sketch(), Value.Sketch()); } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. /// If set to true dispose object. @@ -12211,10 +12230,10 @@ namespace DynamORM { if (node.IsNodeAncestor(this)) node.Host = null; - + node.Dispose(disposing); } - + Value = null; } } @@ -12222,15 +12241,15 @@ namespace DynamORM { } } - + base.Dispose(disposing); } } - + #endregion SetMember - + #region GetIndex - + /// /// Describe a 'get indexed' operation, as in 'x => x.Member[...]'. /// @@ -12239,7 +12258,7 @@ namespace DynamORM { /// Gets the indexes. public object[] Indexes { get; internal set; } - + /// /// Initializes a new instance of the class. /// @@ -12254,10 +12273,10 @@ namespace DynamORM throw new ArgumentNullException("indexes", "Indexes array cannot be null."); if (indexes.Length == 0) throw new ArgumentException("Indexes array cannot be empty."); - + Indexes = indexes; } - + /// /// Initializes a new instance of the class. /// @@ -12267,7 +12286,7 @@ namespace DynamORM : base(info, context) { int count = (int)info.GetValue("IndexCount", typeof(int)); - + if (count != 0) { Indexes = new object[count]; for (int i = 0; i < count; i++) @@ -12278,7 +12297,7 @@ namespace DynamORM } } } - + /// /// Gets the object data. /// @@ -12292,20 +12311,20 @@ namespace DynamORM info.AddValue("IndexType" + i, Indexes[i] == null ? "NULL" : Indexes[i].GetType().AssemblyQualifiedName); if (Indexes[i] != null) info.AddValue("IndexValue" + i, Indexes[i]); } - + base.GetObjectData(info, context); } - + /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() { if (IsDisposed) return "{DynamicParser::Node::GetIndex::Disposed}"; - + return string.Format("{0}{1}", Host.Sketch(), Indexes == null ? "[empty]" : Indexes.Sketch()); } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. /// If set to true dispose object. @@ -12324,29 +12343,29 @@ namespace DynamORM { if (node.IsNodeAncestor(this)) node.Host = null; - + node.Dispose(disposing); } } - + Array.Clear(Indexes, 0, Indexes.Length); } } catch { } - + Indexes = null; } - + base.Dispose(disposing); } } - + #endregion GetIndex - + #region SetIndex - + /// /// Describe a 'set indexed' operation, as in 'x => x.Member[...] = Value'. /// @@ -12358,7 +12377,7 @@ namespace DynamORM /// assigned to this instance, or if this instance is disposed. /// public object Value { get; private set; } - + /// /// Initializes a new instance of the class. /// @@ -12370,7 +12389,7 @@ namespace DynamORM { Value = value; } - + /// /// Initializes a new instance of the class. /// @@ -12382,7 +12401,7 @@ namespace DynamORM string type = info.GetString("MemberType"); Value = type == "NULL" ? null : info.GetValue("MemberValue", Type.GetType(type)); } - + /// /// Gets the object data. /// @@ -12392,20 +12411,20 @@ namespace DynamORM { info.AddValue("MemberType", Value == null ? "NULL" : Value.GetType().AssemblyQualifiedName); if (Value != null) info.AddValue("MemberValue", Value); - + base.GetObjectData(info, context); } - + /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() { if (IsDisposed) return "{DynamicParser::Node::SetIndex::Disposed}"; - + return string.Format("({0}{1} = {2})", Host.Sketch(), Indexes == null ? "[empty]" : Indexes.Sketch(), Value.Sketch()); } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. /// If set to true dispose object. @@ -12422,10 +12441,10 @@ namespace DynamORM { if (node.IsNodeAncestor(this)) node.Host = null; - + node.Dispose(disposing); } - + Value = null; } } @@ -12433,15 +12452,15 @@ namespace DynamORM { } } - + base.Dispose(disposing); } } - + #endregion SetIndex - + #region Invoke - + /// /// Describe a method invocation operation, as in 'x => x.Method(...)". /// @@ -12450,7 +12469,7 @@ namespace DynamORM { /// Gets the arguments. public object[] Arguments { get; internal set; } - + /// /// Initializes a new instance of the class. /// @@ -12461,7 +12480,7 @@ namespace DynamORM { Arguments = arguments == null || arguments.Length == 0 ? null : arguments; } - + /// /// Initializes a new instance of the class. /// @@ -12471,7 +12490,7 @@ namespace DynamORM : base(info, context) { int count = (int)info.GetValue("ArgumentCount", typeof(int)); - + if (count != 0) { Arguments = new object[count]; for (int i = 0; i < count; i++) @@ -12482,7 +12501,7 @@ namespace DynamORM } } } - + /// /// Gets the object data. /// @@ -12496,10 +12515,10 @@ namespace DynamORM info.AddValue("ArgumentType" + i, Arguments[i] == null ? "NULL" : Arguments[i].GetType().AssemblyQualifiedName); if (Arguments[i] != null) info.AddValue("ArgumentValue" + i, Arguments[i]); } - + base.GetObjectData(info, context); } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. /// If set to true dispose object. @@ -12518,39 +12537,39 @@ namespace DynamORM { if (node.IsNodeAncestor(this)) node.Host = null; - + node.Dispose(disposing); } } - + Array.Clear(Arguments, 0, Arguments.Length); } } catch { } - + Arguments = null; } - + base.Dispose(disposing); } - + /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() { if (IsDisposed) return "{DynamicParser::Node::Invoke::Disposed}"; - + return string.Format("{0}{1}", Host.Sketch(), Arguments == null ? "()" : Arguments.Sketch(brackets: "()".ToCharArray())); } } - + #endregion Invoke - + #region Method - + /// /// Describe a method invocation operation, as in 'x => x.Method(...)". /// @@ -12559,7 +12578,7 @@ namespace DynamORM { /// Gets the arguments. public object[] Arguments { get; internal set; } - + /// /// Initializes a new instance of the class. /// @@ -12571,7 +12590,7 @@ namespace DynamORM { Arguments = arguments == null || arguments.Length == 0 ? null : arguments; } - + /// /// Initializes a new instance of the class. /// @@ -12581,7 +12600,7 @@ namespace DynamORM : base(info, context) { int count = (int)info.GetValue("ArgumentCount", typeof(int)); - + if (count != 0) { Arguments = new object[count]; for (int i = 0; i < count; i++) @@ -12592,7 +12611,7 @@ namespace DynamORM } } } - + /// /// Gets the object data. /// @@ -12606,20 +12625,20 @@ namespace DynamORM info.AddValue("ArgumentType" + i, Arguments[i] == null ? "NULL" : Arguments[i].GetType().AssemblyQualifiedName); if (Arguments[i] != null) info.AddValue("ArgumentValue" + i, Arguments[i]); } - + base.GetObjectData(info, context); } - + /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() { if (IsDisposed) return "{DynamicParser::Node::Method::Disposed}"; - + return string.Format("{0}.{1}{2}", Host.Sketch(), Name.Sketch(), Arguments == null ? "()" : Arguments.Sketch(brackets: "()".ToCharArray())); } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. /// If set to true dispose object. @@ -12638,29 +12657,29 @@ namespace DynamORM { if (node.IsNodeAncestor(this)) node.Host = null; - + node.Dispose(disposing); } } - + Array.Clear(Arguments, 0, Arguments.Length); } } catch { } - + Arguments = null; } - + base.Dispose(disposing); } } - + #endregion Method - + #region Binary - + /// /// Represents a binary operation between a dynamic element and an arbitrary object, including null ones, as in /// 'x => (x && null)'. The left operand must be an instance of , whereas the right one @@ -12671,13 +12690,13 @@ namespace DynamORM { /// Gets the operation. public ExpressionType Operation { get; private set; } - + /// Gets host of the . public Node Left { get { return Host; } } - + /// Gets the right side value. public object Right { get; private set; } - + /// /// Initializes a new instance of the class. /// @@ -12690,7 +12709,7 @@ namespace DynamORM Operation = operation; Right = right; } - + /// /// Initializes a new instance of the class. /// @@ -12700,11 +12719,11 @@ namespace DynamORM : base(info, context) { Operation = (ExpressionType)info.GetValue("Operation", typeof(ExpressionType)); - + string type = info.GetString("RightType"); Right = type == "NULL" ? null : (Node)info.GetValue("RightItem", Type.GetType(type)); } - + /// /// Gets the object data. /// @@ -12713,31 +12732,31 @@ namespace DynamORM public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Operation", Operation); - + info.AddValue("RightType", Right == null ? "NULL" : Right.GetType().AssemblyQualifiedName); if (Right != null) info.AddValue("RightItem", Right); - + base.GetObjectData(info, context); } - + /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() { if (IsDisposed) return "{DynamicParser::Node::Binary::Disposed}"; - + return string.Format("({0} {1} {2})", Host.Sketch(), Operation, Right.Sketch()); } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. /// If set to true dispose object. public override void Dispose(bool disposing) { base.Dispose(disposing); - + if (disposing) { if (Left != null) @@ -12745,32 +12764,32 @@ namespace DynamORM if (Left is Node) { Node n = (Node)Left; - + if (!n.IsDisposed) n.Dispose(disposing); } } - + if (Right != null) { if (Right is Node) { Node n = (Node)Right; - + if (!n.IsDisposed) n.Dispose(disposing); } - + Right = null; } } } } - + #endregion Binary - + #region Unary - + /// /// Represents an unary operation, as in 'x => !x'. The target must be a instance. There /// is no distinction between pre- and post- version of the same operation. @@ -12780,10 +12799,10 @@ namespace DynamORM { /// Gets the operation. public ExpressionType Operation { get; private set; } - + /// Gets host of the . public Node Target { get; private set; } - + /// /// Initializes a new instance of the class. /// @@ -12795,7 +12814,7 @@ namespace DynamORM Operation = operation; Target = target; } - + /// /// Initializes a new instance of the class. /// @@ -12806,7 +12825,7 @@ namespace DynamORM { Operation = (ExpressionType)info.GetValue("Operation", typeof(ExpressionType)); } - + /// /// Gets the object data. /// @@ -12815,20 +12834,20 @@ namespace DynamORM public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Operation", Operation); - + base.GetObjectData(info, context); } - + /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() { if (IsDisposed) return "{DynamicParser::Node::Binary::Disposed}"; - + return string.Format("({0} {1})", Operation, Host.Sketch()); } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. /// If set to true dispose object. @@ -12845,10 +12864,10 @@ namespace DynamORM { if (node.IsNodeAncestor(this)) node.Host = null; - + node.Dispose(disposing); } - + Target = null; } } @@ -12856,15 +12875,15 @@ namespace DynamORM { } } - + base.Dispose(disposing); } } - + #endregion Unary - + #region Convert - + /// /// Represents a conversion operation, as in 'x => (string)x'. /// @@ -12873,10 +12892,10 @@ namespace DynamORM { /// Gets the new type to which value will be converted. public Type NewType { get; private set; } - + /// Gets host of the . public Node Target { get { return Host; } } - + /// /// Initializes a new instance of the class. /// @@ -12887,7 +12906,7 @@ namespace DynamORM { NewType = newType; } - + /// /// Initializes a new instance of the class. /// @@ -12898,7 +12917,7 @@ namespace DynamORM { NewType = (Type)info.GetValue("NewType", typeof(Type)); } - + /// /// Gets the object data. /// @@ -12907,21 +12926,21 @@ namespace DynamORM public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("NewType", NewType); - + base.GetObjectData(info, context); } } - + #endregion Convert - + /// /// Gets the name of the member. It might be null if this instance is disposed. /// public string Name { get; internal set; } - + /// Gets host of the . public Node Host { get; internal set; } - + /// Gets reference to the parser. public DynamicParser Parser { @@ -12933,7 +12952,7 @@ namespace DynamORM _parser._allNodes.Add(this); } } - + /// /// Initializes a new instance of the class. /// @@ -12941,7 +12960,7 @@ namespace DynamORM { IsDisposed = false; } - + /// /// Initializes a new instance of the class. /// @@ -12951,10 +12970,10 @@ namespace DynamORM { if (host == null) throw new ArgumentNullException("host", "Host cannot be null."); - + Host = host; } - + /// /// Initializes a new instance of the class. /// @@ -12964,7 +12983,7 @@ namespace DynamORM { Name = name.Validated("Name"); } - + /// /// Initializes a new instance of the class. /// @@ -12976,7 +12995,7 @@ namespace DynamORM { Name = name.Validated("Name"); } - + /// /// Initializes a new instance of the class. /// @@ -12985,11 +13004,11 @@ namespace DynamORM protected Node(SerializationInfo info, StreamingContext context) { Name = info.GetString("MemberName"); - + string type = info.GetString("HostType"); Host = type == "NULL" ? null : (Node)info.GetValue("HostItem", Type.GetType(type)); } - + /// Returns whether the given node is an ancestor of this instance. /// The node to test. /// True if the given node is an ancestor of this instance. @@ -12998,31 +13017,31 @@ namespace DynamORM if (node != null) { Node parent = Host; - + while (parent != null) { if (object.ReferenceEquals(parent, node)) return true; - + parent = parent.Host; } } - + return false; } - + /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() { if (IsDisposed) return "{DynamicParser::Node::Disposed}"; - + return "{DynamicParser::Node::Empty}"; } - + #region Implementation of IDynamicMetaObjectProvider - + /// Returns the responsible /// for binding operations performed on this object. /// The expression tree representation of the runtime value. @@ -13032,26 +13051,26 @@ namespace DynamORM { if (IsDisposed) throw new ObjectDisposedException("DynamicParser.Node"); - + return new MetaNode( parameter, BindingRestrictions.GetInstanceRestriction(parameter, this), this); } - + #endregion Implementation of IDynamicMetaObjectProvider - + #region Implementation of IFinalizerDisposable - + /// Finalizes an instance of the class. ~Node() { Dispose(false); } - + /// Gets a value indicating whether this instance is disposed. public bool IsDisposed { get; private set; } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. public virtual void Dispose() @@ -13059,7 +13078,7 @@ namespace DynamORM Dispose(true); GC.SuppressFinalize(this); } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. /// If set to true dispose object. @@ -13068,20 +13087,20 @@ namespace DynamORM if (disposing) { IsDisposed = true; - + if (Host != null && !Host.IsDisposed) Host.Dispose(); - + Host = null; - + Parser = null; } } - + #endregion Implementation of IFinalizerDisposable - + #region Implementation of ISerializable - + /// /// Populates a with the data needed to serialize the target object. /// @@ -13091,30 +13110,30 @@ namespace DynamORM { if (!string.IsNullOrEmpty(Name)) info.AddValue("MemberName", Name); - + info.AddValue("HostType", Host == null ? "NULL" : Host.GetType().AssemblyQualifiedName); if (Host != null) info.AddValue("HostItem", Host); } - + #endregion Implementation of ISerializable } - + #endregion Node - + #region Data - + private List _arguments = new List(); private List _allNodes = new List(); private object _uncertainResult; - + #endregion Data - + #region Properties - + /// Gets the last node (root of the tree). public Node Last { get; internal set; } - + /// /// Gets an enumeration containing the dynamic arguments used in the dynamic lambda expression parsed. /// @@ -13125,15 +13144,15 @@ namespace DynamORM List list = new List(); if (!IsDisposed && _arguments != null) list.AddRange(_arguments); - + foreach (Node.Argument arg in list) yield return arg; - + list.Clear(); list = null; } } - + /// /// Gets the number of dynamic arguments used in the dynamic lambda expression parsed. /// @@ -13141,7 +13160,7 @@ namespace DynamORM { get { return _arguments == null ? 0 : _arguments.Count; } } - + /// /// Gets the result of the parsing of the dynamic lambda expression. This result can be either an arbitrary object, /// including null, if the expression resolves to it, or an instance of the class that @@ -13151,9 +13170,9 @@ namespace DynamORM { get { return _uncertainResult ?? Last; } } - + #endregion Properties - + private DynamicParser(Delegate f) { // I know this can be almost a one liner @@ -13170,7 +13189,7 @@ namespace DynamORM else throw new ArgumentException(string.Format("Argument '{0}' must be dynamic.", p.Name)); } - + try { _uncertainResult = f.DynamicInvoke(_arguments.ToArray()); @@ -13181,7 +13200,7 @@ namespace DynamORM else throw e; } } - + /// /// Parses the dynamic lambda expression given in the form of a delegate, and returns a new instance of the /// class that holds the dynamic arguments used in the dynamic lambda expression, and @@ -13193,19 +13212,19 @@ namespace DynamORM { return new DynamicParser(f); } - + /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() { if (IsDisposed) return "{DynamicParser::Disposed}"; - + StringBuilder sb = new StringBuilder(); - + sb.Append("("); bool first = true; - + if (_arguments != null) { foreach (Node.Argument arg in _arguments) @@ -13214,62 +13233,62 @@ namespace DynamORM sb.Append(arg); } } - + sb.Append(")"); - + sb.AppendFormat(" => {0}", Result.Sketch()); - + return sb.ToString(); } - + #region Implementation of IExtendedDisposable - + /// Gets a value indicating whether this instance is disposed. public bool IsDisposed { get; private set; } - + /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// public void Dispose() { IsDisposed = true; - + if (_uncertainResult != null) { if (_uncertainResult is Node) ((Node)_uncertainResult).Dispose(); - + _uncertainResult = null; } - + if (Last != null) { if (!Last.IsDisposed) Last.Dispose(); - + Last = null; } - + if (_arguments != null) { _arguments.ForEach(x => { if (!x.IsDisposed) x.Dispose(); }); - + _arguments.Clear(); _arguments = null; } - + if (_allNodes != null) { _allNodes.ForEach(x => { if (!x.IsDisposed) x.Dispose(); }); - + _allNodes.Clear(); _allNodes = null; } } - + #endregion Implementation of IExtendedDisposable } - + /// Class that allows to use interfaces as dynamic objects. /// Type of class to proxy. /// This is temporary solution. Which allows to use builders as a dynamic type. @@ -13279,7 +13298,7 @@ namespace DynamORM private Type _type; private Dictionary _properties; private Dictionary _methods; - + /// /// Initializes a new instance of the class. /// @@ -13289,18 +13308,18 @@ namespace DynamORM { if (proxiedObject == null) throw new ArgumentNullException("proxiedObject"); - + _proxy = proxiedObject; _type = typeof(T); - + DynamicTypeMap mapper = Mapper.DynamicMapperCache.GetMapper(); - + _properties = mapper .ColumnsMap .ToDictionary( k => k.Value.Name, v => v.Value); - + _methods = GetAllMembers(_type) .Where(x => x is MethodInfo) .Cast() @@ -13315,7 +13334,7 @@ namespace DynamORM Type type = v.ReturnType == typeof(void) ? Expression.GetActionType(v.GetParameters().Select(t => t.ParameterType).ToArray()) : Expression.GetDelegateType(v.GetParameters().Select(t => t.ParameterType).Concat(new[] { v.ReturnType }).ToArray()); - + return Delegate.CreateDelegate(type, _proxy, v.Name); } catch (ArgumentException) @@ -13324,7 +13343,7 @@ namespace DynamORM } }); } - + /// Provides implementation for type conversion operations. /// Classes derived from the /// class can override this method to specify dynamic behavior for @@ -13349,17 +13368,17 @@ namespace DynamORM result = _proxy; return true; } - + if (_proxy != null && binder.Type.IsAssignableFrom(_proxy.GetType())) { result = _proxy; return true; } - + return base.TryConvert(binder, out result); } - + /// Provides the implementation for operations that get member /// values. Classes derived from the /// class can override this method to specify dynamic behavior for @@ -13384,9 +13403,9 @@ namespace DynamORM try { DynamicPropertyInvoker prop = _properties.TryGetValue(binder.Name); - + result = prop.NullOr(p => p.Get.NullOr(g => g(_proxy), null), null); - + return prop != null && prop.Get != null; } catch (Exception ex) @@ -13394,7 +13413,7 @@ namespace DynamORM throw new InvalidOperationException(string.Format("Cannot get member {0}", binder.Name), ex); } } - + /// Provides the implementation for operations that set member /// values. Classes derived from the /// class can override this method to specify dynamic behavior for operations @@ -13419,13 +13438,13 @@ namespace DynamORM try { DynamicPropertyInvoker prop = _properties.TryGetValue(binder.Name); - + if (prop != null && prop.Setter != null) { prop.Set(_proxy, value); return true; } - + return false; } catch (Exception ex) @@ -13433,7 +13452,7 @@ namespace DynamORM throw new InvalidOperationException(string.Format("Cannot set member {0} to '{1}'", binder.Name, value), ex); } } - + /// Provides the implementation for operations that invoke a member. /// Classes derived from the /// class can override this method to specify dynamic behavior for @@ -13459,58 +13478,58 @@ namespace DynamORM { return TryInvokeMethod(binder.Name, out result, args) || base.TryInvokeMember(binder, args, out result); } - + private bool TryInvokeMethod(string name, out object result, object[] args) { result = null; - + MethodInfo mi = _methods.Keys .Where(m => m.Name == name) .FirstOrDefault(m => CompareTypes(m.GetParameters().ToArray(), args.Select(a => a.GetType()).ToArray())); - + Delegate d = _methods.TryGetValue(mi); - + if (d != null) { result = d.DynamicInvoke(CompleteArguments(mi.GetParameters().ToArray(), args)); - + if (d.Method.ReturnType == _type && result is T) result = new DynamicProxy((T)result); - + return true; } else if (mi != null) { result = mi.Invoke(_proxy, CompleteArguments(mi.GetParameters().ToArray(), args)); - + if (mi.ReturnType == _type && result is T) result = new DynamicProxy((T)result); - + return true; } - + return false; } - + private bool CompareTypes(ParameterInfo[] parameters, Type[] types) { if (parameters.Length < types.Length || parameters.Count(p => !p.IsOptional) > types.Length) return false; - + for (int i = 0; i < types.Length; i++) if (types[i] != parameters[i].ParameterType && !parameters[i].ParameterType.IsAssignableFrom(types[i])) return false; - + return true; } - + private object[] CompleteArguments(ParameterInfo[] parameters, object[] arguments) { return arguments.Concat(parameters.Skip(arguments.Length).Select(p => p.DefaultValue)).ToArray(); } - + private IEnumerable GetAllMembers(Type type) { if (type.IsInterface) @@ -13518,47 +13537,47 @@ namespace DynamORM List members = new List(); List considered = new List(); Queue queue = new Queue(); - + considered.Add(type); queue.Enqueue(type); - + while (queue.Count > 0) { Type subType = queue.Dequeue(); foreach (Type subInterface in subType.GetInterfaces()) { if (considered.Contains(subInterface)) continue; - + considered.Add(subInterface); queue.Enqueue(subInterface); } - + MemberInfo[] typeProperties = subType.GetMembers( BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); - + IEnumerable newPropertyInfos = typeProperties .Where(x => !members.Contains(x)); - + members.InsertRange(0, newPropertyInfos); } - + return members; } - + return type.GetMembers(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); } - + /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. public void Dispose() { object res; TryInvokeMethod("Dispose", out res, new object[] { }); - + _properties.Clear(); - + _methods = null; _properties = null; _type = null; @@ -13569,57 +13588,57 @@ namespace DynamORM } namespace Mapper - { + { /// Allows to add table name to class. [AttributeUsage(AttributeTargets.Property)] public class ColumnAttribute : Attribute { /// Gets or sets name. public string Name { get; set; } - + /// Gets or sets column type. /// Used when overriding schema. public DbType? Type { get; set; } - + /// Gets or sets a value indicating whether column is a key. public bool IsKey { get; set; } - + /// Gets or sets a value indicating whether column allows null or not. /// Information only. public bool AllowNull { get; set; } - + /// Gets or sets a value indicating whether column should have unique value. /// Used when overriding schema. public bool? IsUnique { get; set; } - + /// Gets or sets column size. /// Used when overriding schema. public int? Size { get; set; } - + /// Gets or sets column precision. /// Used when overriding schema. public byte? Precision { get; set; } - + /// Gets or sets column scale. /// Used when overriding schema. public byte? Scale { get; set; } - + /// Gets or sets a value indicating whether this column is no allowed to be inserted. /// This is only a suggestion to automated mapping. public bool IsNoInsert { get; set; } - + /// Gets or sets a value indicating whether this column is no allowed to be updated. /// This is only a suggestion to automated mapping. public bool IsNoUpdate { get; set; } - + #region Constructors - + /// Initializes a new instance of the class. public ColumnAttribute() { AllowNull = true; } - + /// Initializes a new instance of the class. /// Name of column. public ColumnAttribute(string name) @@ -13627,7 +13646,7 @@ namespace DynamORM { Name = name; } - + /// Initializes a new instance of the class. /// Set column as a key column. public ColumnAttribute(bool isKey) @@ -13635,7 +13654,7 @@ namespace DynamORM { IsKey = isKey; } - + /// Initializes a new instance of the class. /// Name of column. /// Set column as a key column. @@ -13644,7 +13663,7 @@ namespace DynamORM { IsKey = isKey; } - + /// Initializes a new instance of the class. /// Set column as a key column. /// Set column type. @@ -13653,7 +13672,7 @@ namespace DynamORM { Type = type; } - + /// Initializes a new instance of the class. /// Name of column. /// Set column as a key column. @@ -13663,7 +13682,7 @@ namespace DynamORM { Type = type; } - + /// Initializes a new instance of the class. /// Name of column. /// Set column as a key column. @@ -13674,7 +13693,7 @@ namespace DynamORM { Size = size; } - + /// Initializes a new instance of the class. /// Name of column. /// Set column as a key column. @@ -13687,7 +13706,7 @@ namespace DynamORM Precision = precision; Scale = scale; } - + /// Initializes a new instance of the class. /// Name of column. /// Set column as a key column. @@ -13700,7 +13719,7 @@ namespace DynamORM { Size = size; } - + /// Initializes a new instance of the class. /// Name of column. /// Set column as a key column. @@ -13714,10 +13733,10 @@ namespace DynamORM { IsUnique = isUnique; } - + #endregion Constructors } - + /// Type cast helper. public static class DynamicCast { @@ -13728,7 +13747,7 @@ namespace DynamORM { return type.IsValueType ? TypeDefaults.GetOrAdd(type, t => Activator.CreateInstance(t)) : null; } - + /// Casts the object to this type. /// The type to which cast value. /// The value to cast. @@ -13737,23 +13756,23 @@ namespace DynamORM { return GetConverter(type, val)(val); } - + private static readonly ConcurrentDictionary TypeDefaults = new ConcurrentDictionary(); private static readonly ConcurrentDictionary> TypeAsCasts = new ConcurrentDictionary>(); private static readonly ConcurrentDictionary> TypeConvert = new ConcurrentDictionary>(); private static readonly ParameterExpression ConvParameter = Expression.Parameter(typeof(object), "val"); - + [MethodImpl(MethodImplOptions.Synchronized)] private static Func GetConverter(Type targetType, object val) { Func fn; - + if (!targetType.IsValueType && !val.GetType().IsValueType) { if (!TypeAsCasts.TryGetValue(targetType, out fn)) { UnaryExpression instanceCast = Expression.TypeAs(ConvParameter, targetType); - + fn = Expression.Lambda>(Expression.TypeAs(instanceCast, typeof(object)), ConvParameter).Compile(); TypeAsCasts.AddOrUpdate(targetType, fn, (t, f) => fn); } @@ -13764,51 +13783,51 @@ namespace DynamORM var key = new PairOfTypes(fromType, targetType); if (TypeConvert.TryGetValue(key, out fn)) return fn; - + fn = (Func)Expression.Lambda(Expression.Convert(Expression.Convert(Expression.Convert(ConvParameter, fromType), targetType), typeof(object)), ConvParameter).Compile(); TypeConvert.AddOrUpdate(key, fn, (t, f) => fn); } - + return fn; } - + private class PairOfTypes { private readonly Type _first; private readonly Type _second; - + public PairOfTypes(Type first, Type second) { this._first = first; this._second = second; } - + public override int GetHashCode() { return (31 * _first.GetHashCode()) + _second.GetHashCode(); } - + public override bool Equals(object obj) { if (obj == this) return true; - + var other = obj as PairOfTypes; if (other == null) return false; - + return _first.Equals(other._first) && _second.Equals(other._second); } } } - + /// Class with mapper cache. public static class DynamicMapperCache { private static readonly object SyncLock = new object(); private static Dictionary _cache = new Dictionary(); - + /// Get type mapper. /// Type of mapper. /// Type mapper. @@ -13816,7 +13835,7 @@ namespace DynamORM { return GetMapper(typeof(T)); } - + /// Get type mapper. /// Type of mapper. /// Type mapper. @@ -13826,24 +13845,24 @@ namespace DynamORM return null; /*if (type.IsAnonymous()) return null;*/ - + DynamicTypeMap mapper = null; - + lock (SyncLock) { if (!_cache.TryGetValue(type, out mapper)) { mapper = new DynamicTypeMap(type); - + if (mapper != null) _cache.Add(type, mapper); } } - + return mapper; } } - + /// Exception thrown when mapper fails to set or get a property. /// public class DynamicMapperException : Exception @@ -13852,20 +13871,20 @@ namespace DynamORM public DynamicMapperException() { } - + /// Initializes a new instance of the class. /// The message that describes the error. public DynamicMapperException(string message) : base(message) { } - + /// Initializes a new instance of the class. /// The error message that explains the reason for the exception. /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. public DynamicMapperException(string message, Exception innerException) : base(message, innerException) { } - + /// Initializes a new instance of the class. /// The that holds the serialized object data about the exception being thrown. /// The that contains contextual information about the source or destination. @@ -13873,52 +13892,52 @@ namespace DynamORM { } } - + /// Dynamic property invoker. public class DynamicPropertyInvoker { internal class ParameterSpec { public string Name { get; set; } - + public DbType Type { get; set; } - + public int Ordinal { get; set; } } - + /// Gets the array type of property if main type is a form of collection. public Type ArrayType { get; private set; } - + /// Gets a value indicating whether this property is in fact a generic list. public bool IsGnericEnumerable { get; private set; } - + /// Gets the type of property. public Type Type { get; private set; } - + /// Gets value getter. public Func Get { get; private set; } - + /// Gets value setter. public Action Setter { get; private set; } - + /// Gets the property information. public PropertyInfo PropertyInfo { get; private set; } - + /// Gets name of property. public string Name { get; private set; } - + /// Gets type column description. public ColumnAttribute Column { get; private set; } - + /// Gets type list of property requirements. public List Requirements { get; private set; } - + /// Gets a value indicating whether this is ignored in some cases. public bool Ignore { get; private set; } - + /// Gets a value indicating whether this instance hold data contract type. public bool IsDataContract { get; private set; } - + /// Initializes a new instance of the class. /// Property info to be invoked in the future. /// Column attribute if exist. @@ -13927,45 +13946,45 @@ namespace DynamORM PropertyInfo = property; Name = property.Name; Type = property.PropertyType; - + object[] ignore = property.GetCustomAttributes(typeof(IgnoreAttribute), false); Requirements = property.GetCustomAttributes(typeof(RequiredAttribute), false).Cast().ToList(); - + Ignore = ignore != null && ignore.Length > 0; - + IsGnericEnumerable = Type.IsGenericEnumerable(); - + ArrayType = Type.IsArray ? Type.GetElementType() : IsGnericEnumerable ? Type.GetGenericArguments().First() : Type; - + IsDataContract = ArrayType.GetCustomAttributes(false).Any(x => x.GetType().Name == "DataContractAttribute"); - + if (ArrayType.IsArray) throw new InvalidOperationException("Jagged arrays are not supported"); - + if (ArrayType.IsGenericEnumerable()) throw new InvalidOperationException("Enumerables of enumerables are not supported"); - + Column = attr; - + if (attr != null && attr.AllowNull && Type.IsNullableType()) attr.AllowNull = false; - + if (property.CanRead) Get = CreateGetter(property); - + if (property.CanWrite) Setter = CreateSetter(property); } - + private Func CreateGetter(PropertyInfo property) { if (!property.CanRead) return null; - + ParameterExpression objParm = Expression.Parameter(typeof(object), "o"); - + return Expression.Lambda>( Expression.Convert( Expression.Property( @@ -13973,15 +13992,15 @@ namespace DynamORM property.Name), typeof(object)), objParm).Compile(); } - + private Action CreateSetter(PropertyInfo property) { if (!property.CanWrite) return null; - + ParameterExpression objParm = Expression.Parameter(typeof(object), "o"); ParameterExpression valueParm = Expression.Parameter(typeof(object), "value"); - + return Expression.Lambda>( Expression.Assign( Expression.Property( @@ -13990,14 +14009,14 @@ namespace DynamORM Expression.Convert(valueParm, property.PropertyType)), objParm, valueParm).Compile(); } - + /// Sets the specified value to destination object. /// The destination object. /// The value. public void Set(object dest, object val, bool byProperty = false) { object value = null; - + try { if (!Type.IsAssignableFrom(val.GetType())) @@ -14009,9 +14028,9 @@ namespace DynamORM if (val is IEnumerable) { var lst = (val as IEnumerable).Select(x => GetElementVal(ArrayType, x, byProperty)).ToList(); - + value = Array.CreateInstance(ArrayType, lst.Count); - + int i = 0; foreach (var e in lst) ((Array)value).SetValue(e, i++); @@ -14030,7 +14049,7 @@ namespace DynamORM } else value = val; - + Setter(dest, value); } catch (Exception ex) @@ -14041,12 +14060,12 @@ namespace DynamORM ex); } } - + private object GetElementVal(System.Type etype, object val, bool byProperty) { bool nullable = etype.IsGenericType && etype.GetGenericTypeDefinition() == typeof(Nullable<>); Type type = Nullable.GetUnderlyingType(etype) ?? etype; - + if (val == null && type.IsValueType) { if (nullable) @@ -14067,7 +14086,7 @@ namespace DynamORM { if (nullable) return null; - + throw; } else if (Type == typeof(string) && val.GetType() == typeof(Guid)) @@ -14087,7 +14106,7 @@ namespace DynamORM { if (byProperty) return val.MapByProperty(type); - + return val.Map(type); } else @@ -14099,108 +14118,108 @@ namespace DynamORM { if (nullable) return null; - + throw; } } - + #region Type command cache - + internal ParameterSpec InsertCommandParameter { get; set; } - + internal ParameterSpec UpdateCommandParameter { get; set; } - + internal ParameterSpec DeleteCommandParameter { get; set; } - + #endregion Type command cache } - + /// Represents type columnMap. public class DynamicTypeMap { /// Gets mapper destination type creator. public Type Type { get; private set; } - + /// Gets type table description. public TableAttribute Table { get; private set; } - + /// Gets object creator. public Func Creator { get; private set; } - + /// Gets map of columns to properties. /// Key: Column name (lower), Value: . public Dictionary ColumnsMap { get; private set; } - + /// Gets map of properties to column. /// Key: Property name, Value: Column name. public Dictionary PropertyMap { get; private set; } - + /// Gets list of ignored properties. public List Ignored { get; private set; } - + /// Initializes a new instance of the class. /// Type to which columnMap objects. public DynamicTypeMap(Type type) { Type = type; - + object[] attr = type.GetCustomAttributes(typeof(TableAttribute), false); - + if (attr != null && attr.Length > 0) Table = (TableAttribute)attr[0]; - + Creator = CreateCreator(); CreateColumnAndPropertyMap(); } - + private void CreateColumnAndPropertyMap() { Dictionary columnMap = new Dictionary(); Dictionary propertyMap = new Dictionary(); List ignored = new List(); - + foreach (PropertyInfo pi in GetAllMembers(Type).Where(x => x is PropertyInfo).Cast()) { // Skip indexers if (pi.GetIndexParameters().Any()) continue; - + ColumnAttribute attr = null; - + object[] attrs = pi.GetCustomAttributes(typeof(ColumnAttribute), true); - + if (attrs != null && attrs.Length > 0) attr = (ColumnAttribute)attrs[0]; - + string col = attr == null || string.IsNullOrEmpty(attr.Name) ? pi.Name : attr.Name; - + DynamicPropertyInvoker val = new DynamicPropertyInvoker(pi, attr); columnMap.Add(col.ToLower(), val); - + propertyMap.Add(pi.Name, col); - + if (val.Ignore) ignored.Add(pi.Name); } - + ColumnsMap = columnMap; PropertyMap = propertyMap; - + Ignored = ignored; ////columnMap.Where(i => i.Value.Ignore).Select(i => i.Value.Name).ToList(); } - + private Func CreateCreator() { var c = Type.GetConstructor(Type.EmptyTypes); if (c == null) c = Type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null); - + if (c != null) return Expression.Lambda>(Expression.New(Type)).Compile(); - + return null; } - + /// Create object of type and fill values from source. /// Object containing values that will be mapped to newly created object. /// New object of type with matching values from source. @@ -14208,7 +14227,7 @@ namespace DynamORM { return Map(source, Creator()); } - + /// Create object of type and fill values from source using property names. /// Object containing values that will be mapped to newly created object. /// New object of type with matching values from source. @@ -14216,7 +14235,7 @@ namespace DynamORM { return MapByProperty(source, Creator()); } - + /// Fill values from source to object in destination. /// Object containing values that will be mapped to newly created object. /// Object of type to which copy values from source. @@ -14224,17 +14243,17 @@ namespace DynamORM public object Map(object source, object destination) { DynamicPropertyInvoker dpi = null; - + foreach (KeyValuePair item in source.ToDictionary()) { if (ColumnsMap.TryGetValue(item.Key.ToLower(), out dpi) && item.Value != null) if (dpi.Setter != null) dpi.Set(destination, item.Value); } - + return destination; } - + /// Fill values from source to object in destination using property names. /// Object containing values that will be mapped to newly created object. /// Object of type to which copy values from source. @@ -14243,7 +14262,7 @@ namespace DynamORM { string cn = null; DynamicPropertyInvoker dpi = null; - + foreach (KeyValuePair item in source.ToDictionary()) { if (PropertyMap.TryGetValue(item.Key, out cn) && item.Value != null) @@ -14251,46 +14270,46 @@ namespace DynamORM if (dpi.Setter != null) dpi.Set(destination, item.Value, true); } - + return destination; } - + /// Validates the object. /// The value. /// List of not valid results. public IList ValidateObject(object val) { var result = new List(); - + if (val == null || val.GetType() != Type) return null; - + foreach (var prop in ColumnsMap.Values) { if (prop.Requirements == null || !prop.Requirements.Any()) continue; - + var v = prop.Get(val); - + foreach (var r in prop.Requirements.Where(x => !x.ElementRequirement)) { var valid = r.ValidateSimpleValue(prop, v); - + if (valid == ValidateResult.Valid) { if (prop.Type.IsArray || prop.IsGnericEnumerable) { var map = DynamicMapperCache.GetMapper(prop.ArrayType); - + var list = v as IEnumerable; - + if (list == null) { var enumerable = v as IEnumerable; if (enumerable != null) list = enumerable.Cast(); } - + if (list != null) foreach (var item in list) { @@ -14299,7 +14318,7 @@ namespace DynamORM foreach (var re in prop.Requirements.Where(x => x.ElementRequirement)) { var validelem = re.ValidateSimpleValue(prop.ArrayType, prop.ArrayType.IsGenericEnumerable(), item); - + if (validelem == ValidateResult.NotSupported) { result.AddRange(map.ValidateObject(item)); @@ -14319,16 +14338,16 @@ namespace DynamORM result.AddRange(map.ValidateObject(item)); } } - + continue; } - + if (valid == ValidateResult.NotSupported) { result.AddRange(DynamicMapperCache.GetMapper(prop.Type).ValidateObject(v)); continue; } - + result.Add(new ValidationResult() { Property = prop, @@ -14338,10 +14357,10 @@ namespace DynamORM }); } } - + return result; } - + private IEnumerable GetAllMembers(Type type) { if (type.IsInterface) @@ -14349,66 +14368,66 @@ namespace DynamORM List members = new List(); List considered = new List(); Queue queue = new Queue(); - + considered.Add(type); queue.Enqueue(type); - + while (queue.Count > 0) { Type subType = queue.Dequeue(); foreach (Type subInterface in subType.GetInterfaces()) { if (considered.Contains(subInterface)) continue; - + considered.Add(subInterface); queue.Enqueue(subInterface); } - + MemberInfo[] typeProperties = subType.GetMembers( BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); - + IEnumerable newPropertyInfos = typeProperties .Where(x => !members.Contains(x)); - + members.InsertRange(0, newPropertyInfos); } - + return members; } - + return type.GetMembers(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); } - + #region Type command cache - + internal string InsertCommandText { get; set; } - + internal string UpdateCommandText { get; set; } - + internal string DeleteCommandText { get; set; } - + #endregion Type command cache } - + /// Allows to add ignore action to property. /// Property still get's mapped from output. [AttributeUsage(AttributeTargets.Property)] public class IgnoreAttribute : Attribute { } - + /// Allows to add table name to class. [AttributeUsage(AttributeTargets.Class)] public class TableAttribute : Attribute { /// Gets or sets table owner name. public string Owner { get; set; } - + /// Gets or sets name. public string Name { get; set; } - + /// Gets or sets a value indicating whether override database /// schema values. /// If database doesn't support schema, you still have to @@ -14418,31 +14437,31 @@ namespace DynamORM } namespace Objects - { + { /// Base class for strong typed objects. public class DynamicEntityBase { private Dictionary _changedFields = new Dictionary(); private DynamicEntityState _dynamicEntityState = DynamicEntityState.Unknown; - + /// Occurs when object property is changing. public event EventHandler PropertyChanging; - + /// Gets the state of the dynamic entity. /// Current state of entity. public virtual DynamicEntityState GetDynamicEntityState() { return _dynamicEntityState; } - + /// Sets the state of the dynamic entity. /// Using this method will reset modified fields list. /// The state. public virtual void SetDynamicEntityState(DynamicEntityState state) { _dynamicEntityState = state; - + if (_changedFields != null) _changedFields.Clear(); } - + /// Called when object property is changing. /// Name of the property. /// The old property value. @@ -14451,7 +14470,7 @@ namespace DynamORM { OnPropertyChanging(new DynamicPropertyChangingEventArgs(propertyName, oldValue, newValue)); } - + /// Raises the event. /// The instance containing the event data. protected virtual void OnPropertyChanging(DynamicPropertyChangingEventArgs e) @@ -14460,14 +14479,14 @@ namespace DynamORM if (PropertyChanging != null) PropertyChanging(this, e); } - + /// Validates this object instance. /// Returns list of containing results of validation. public virtual IList Validate() { return DynamicMapperCache.GetMapper(this.GetType()).ValidateObject(this); } - + /// Saves this object to database. /// The database. /// Returns true if operation was successful. @@ -14479,36 +14498,36 @@ namespace DynamORM default: case DynamicEntityState.Unknown: throw new InvalidOperationException("Unknown object state. Unable to decide whish action should be performed."); - + case DynamicEntityState.New: return Insert(database); - + case DynamicEntityState.Existing: if (IsModified()) return Update(database); - + return true; - + case DynamicEntityState.ToBeDeleted: return Delete(database); - + case DynamicEntityState.Deleted: throw new InvalidOperationException("Unable to do any database action on deleted object."); } } - + /// Determines whether this instance is in existing state and fields was modified since this state was set modified. /// Returns true if this instance is modified; otherwise, false. public virtual bool IsModified() { if (GetDynamicEntityState() != DynamicEntityState.Existing) return false; - + return _changedFields != null && _changedFields.Any(); } - + #region Insert/Update/Delete - + /// Inserts this object to database. /// The database. /// Returns true if operation was successful. @@ -14525,10 +14544,10 @@ namespace DynamORM return true; } } - + return false; } - + /// Updates this object in database. /// The database. /// Returns true if operation was successful. @@ -14539,9 +14558,9 @@ namespace DynamORM using (var query = db.Update(t)) { MakeQueryWhere(mapper, query); - + bool any = false; - + if (_changedFields.Any()) { foreach (var cf in _changedFields) @@ -14550,56 +14569,56 @@ namespace DynamORM var pm = mapper.ColumnsMap[cn.ToLower()]; if (pm.Ignore) continue; - + if (pm.Column != null) { if (pm.Column.IsKey || pm.Column.IsNoUpdate) continue; - + if (!pm.Column.AllowNull && cf.Value == null) continue; } - + query.Values(cn, cf.Value); any = true; } } - + if (!any) foreach (var pmk in mapper.ColumnsMap) { var pm = pmk.Value; var val = pm.Get(this); var cn = pm.Name; - + if (pm.Ignore) continue; - + if (pm.Column != null) { if (!string.IsNullOrEmpty(pm.Column.Name)) cn = pm.Column.Name; - + if (pm.Column.IsKey) continue; - + if (!pm.Column.AllowNull && val == null) continue; } - + query.Values(cn, val); } - + if (query.Execute() == 0) return false; - + SetDynamicEntityState(DynamicEntityState.Existing); _changedFields.Clear(); - + return true; } } - + /// Deletes this object from database. /// The database. /// Returns true if operation was successful. @@ -14607,24 +14626,24 @@ namespace DynamORM { var t = this.GetType(); var mapper = DynamicMapperCache.GetMapper(t); - + using (var query = db.Delete(t)) { MakeQueryWhere(mapper, query); - + if (query.Execute() == 0) return false; - + SetDynamicEntityState(DynamicEntityState.Deleted); } - + return true; } - + #endregion Insert/Update/Delete - + #region Select - + /// Refresh non key data from database. /// The database. /// All properties that are primary key values must be filled. @@ -14637,27 +14656,27 @@ namespace DynamORM { MakeQueryWhere(mapper, query); var o = (query.Execute() as IEnumerable).FirstOrDefault(); - + if (o == null) return false; - + mapper.Map(o, this); - + SetDynamicEntityState(DynamicEntityState.Existing); _changedFields.Clear(); } - + return true; } - + #endregion Select - + #region Query Helpers - + private void MakeQueryWhere(DynamicTypeMap mapper, IDynamicUpdateQueryBuilder query) { bool keyNotDefined = true; - + foreach (var cm in mapper.ColumnsMap) { if (cm.Value.Column != null && cm.Value.Column.IsKey) @@ -14666,16 +14685,16 @@ namespace DynamORM keyNotDefined = false; } } - + if (keyNotDefined) throw new InvalidOperationException(String.Format("Class '{0}' have no key columns defined", this.GetType().FullName)); } - + private void MakeQueryWhere(DynamicTypeMap mapper, IDynamicDeleteQueryBuilder query) { bool keyNotDefined = true; - + foreach (var cm in mapper.ColumnsMap) { if (cm.Value.Column != null && cm.Value.Column.IsKey) @@ -14684,39 +14703,39 @@ namespace DynamORM keyNotDefined = false; } } - + if (keyNotDefined) throw new InvalidOperationException(String.Format("Class '{0}' have no key columns defined", this.GetType().FullName)); } - + private void MakeQueryWhere(DynamicTypeMap mapper, IDynamicSelectQueryBuilder query) { bool keyNotDefined = true; - + foreach (var cm in mapper.ColumnsMap) { if (cm.Value.Column != null && cm.Value.Column.IsKey) { var v = cm.Value.Get(this); - + if (v == null) throw new InvalidOperationException(String.Format("Class '{0}' have key columns {1} not filled with data.", this.GetType().FullName, cm.Value.Name)); - + query.Where(cm.Key, DynamicColumn.CompareOperator.Eq, cm.Value.Get(this)); keyNotDefined = false; } } - + if (keyNotDefined) throw new InvalidOperationException(String.Format("Class '{0}' have no key columns defined", this.GetType().FullName)); } - + #endregion Query Helpers } - + /// Possible states of dynamic database objects. public enum DynamicEntityState { @@ -14724,20 +14743,20 @@ namespace DynamORM /// In this state repository will be unable to tell if object with this state should be added /// or updated in database, but you can still manually perform update or insert on such object. Unknown, - + /// This state should be set to new objects in database. New, - + /// This state is ser when data is refreshed from database or object was loaded from repository. Existing, - + /// You can set this state to an object if you want repository to perform delete from database. ToBeDeleted, - + /// This state is set for objects that were deleted from database. Deleted, } - + /// Class containing changed property data. /// public class DynamicPropertyChangingEventArgs : EventArgs @@ -14745,15 +14764,15 @@ namespace DynamORM /// Gets the name of the property. /// The name of the property. public string PropertyName { get; private set; } - + /// Gets the old property value. /// The old value. public object OldValue { get; private set; } - + /// Gets the new property value. /// The new value. public object NewValue { get; private set; } - + /// Initializes a new instance of the class. /// Name of the property. /// The old property value. @@ -14765,20 +14784,20 @@ namespace DynamORM NewValue = newValue; } } - + /// Base repository class for specified object type. /// Type of stored object. public class DynamicRepositoryBase : IDisposable where T : DynamicEntityBase { private DynamicDatabase _database; - + /// Initializes a new instance of the class. /// The database. public DynamicRepositoryBase(DynamicDatabase database) { _database = database; } - + /// Get all rows from database. /// Objects enumerator. public virtual IEnumerable GetAll() @@ -14786,7 +14805,7 @@ namespace DynamORM using (var q = _database.From()) return EnumerateQuery(q); } - + /// Get rows from database by custom query. /// The query. /// Query must be based on object type. @@ -14795,27 +14814,27 @@ namespace DynamORM { return EnumerateQuery(query); } - + private IEnumerable EnumerateQuery(IDynamicSelectQueryBuilder query, bool forceType = true) { if (forceType) { var mapper = DynamicMapperCache.GetMapper(typeof(T)); - + var tn = mapper.Table == null || string.IsNullOrEmpty(mapper.Table.Name) ? mapper.Type.Name : mapper.Table.Name; - + if (!query.Tables.Any(t => t.Name == tn)) throw new InvalidOperationException(string.Format("Query is not related to '{0}' class.", typeof(T).FullName)); } - + foreach (var o in query.Execute()) { o.SetDynamicEntityState(DynamicEntityState.Existing); yield return o; } } - + /// Saves single object to database. /// The element. /// Returns true if operation was successful. @@ -14823,7 +14842,7 @@ namespace DynamORM { return element.Save(_database); } - + /// Saves collection of objects to database. /// The element. /// Returns true if operation was successful. @@ -14831,7 +14850,7 @@ namespace DynamORM { return element.All(x => x.Save(_database)); } - + /// Insert single object to database. /// The element. /// Returns true if operation was successful. @@ -14839,7 +14858,7 @@ namespace DynamORM { return element.Insert(_database); } - + /// Insert collection of objects to database. /// The element. /// Returns true if operation was successful. @@ -14847,7 +14866,7 @@ namespace DynamORM { return element.All(x => x.Insert(_database)); } - + /// Update single object to database. /// The element. /// Returns true if operation was successful. @@ -14855,7 +14874,7 @@ namespace DynamORM { return element.Update(_database); } - + /// Update collection of objects to database. /// The element. /// Returns true if operation was successful. @@ -14863,7 +14882,7 @@ namespace DynamORM { return element.All(x => x.Update(_database)); } - + /// Delete single object to database. /// The element. /// Returns true if operation was successful. @@ -14871,7 +14890,7 @@ namespace DynamORM { return element.Delete(_database); } - + /// Delete collection of objects to database. /// The element. /// Returns true if operation was successful. @@ -14879,7 +14898,7 @@ namespace DynamORM { return element.All(x => x.Delete(_database)); } - + /// Releases unmanaged and - optionally - managed resources. public virtual void Dispose() { @@ -14889,33 +14908,33 @@ namespace DynamORM } namespace Validation - { + { /// Required attribute can be used to validate fields in objects using mapper class. [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] public class RequiredAttribute : Attribute { /// Gets or sets minimum value or length of field. public decimal? Min { get; set; } - + /// Gets or sets maximum value or length of field. public decimal? Max { get; set; } - + /// Gets or sets pattern to verify. public Regex Pattern { get; set; } - + /// Gets or sets a value indicating whether property value is required or not. public bool Required { get; set; } - + /// Gets or sets a value indicating whether this is an element requirement. public bool ElementRequirement { get; set; } - + /// Initializes a new instance of the class. /// This field will be required. public RequiredAttribute(bool required = true) { Required = required; } - + /// Initializes a new instance of the class. /// Limiting value to set. /// Whether set maximum parameter (true) or minimum parameter (false). @@ -14928,7 +14947,7 @@ namespace DynamORM Min = (decimal)val; Required = required; } - + /// Initializes a new instance of the class. /// Minimum value to set. /// Maximum value to set. @@ -14939,7 +14958,7 @@ namespace DynamORM Max = (decimal)max; Required = required; } - + /// Initializes a new instance of the class. /// Minimum value to set. /// Maximum value to set. @@ -14952,12 +14971,12 @@ namespace DynamORM Pattern = new Regex(pattern, RegexOptions.Compiled); Required = required; } - + internal ValidateResult ValidateSimpleValue(DynamicPropertyInvoker dpi, object val) { return ValidateSimpleValue(dpi.Type, dpi.IsGnericEnumerable, val); } - + internal ValidateResult ValidateSimpleValue(Type type, bool isGnericEnumerable, object val) { if (val == null) @@ -14967,42 +14986,42 @@ namespace DynamORM else return ValidateResult.Valid; } - + if (type.IsValueType) { if (val is decimal || val is long || val is int || val is float || val is double || val is short || val is byte || val is decimal? || val is long? || val is int? || val is float? || val is double? || val is short? || val is byte?) { decimal dec = Convert.ToDecimal(val); - + if (Min.HasValue && Min.Value > dec) return ValidateResult.ValueTooSmall; - + if (Max.HasValue && Max.Value < dec) return ValidateResult.ValueTooLarge; - + return ValidateResult.Valid; } else { var str = val.ToString(); - + if (Min.HasValue && Min.Value > str.Length) return ValidateResult.ValueTooShort; - + if (Max.HasValue && Max.Value < str.Length) return ValidateResult.ValueTooLong; - + if (Pattern != null && !Pattern.IsMatch(str)) return ValidateResult.ValueDontMatchPattern; - + return ValidateResult.Valid; } } else if (type.IsArray || isGnericEnumerable) { int? cnt = null; - + var list = val as IEnumerable; if (list != null) cnt = list.Count(); @@ -15012,84 +15031,83 @@ namespace DynamORM if (enumerable != null) cnt = enumerable.Cast().Count(); } - + if (Min.HasValue && Min.Value > cnt) return ValidateResult.TooFewElementsInCollection; - + if (Max.HasValue && Max.Value < cnt) return ValidateResult.TooManyElementsInCollection; - + return ValidateResult.Valid; } else if (type == typeof(string)) { var str = (string)val; - + if (Min.HasValue && Min.Value > str.Length) return ValidateResult.ValueTooShort; - + if (Max.HasValue && Max.Value < str.Length) return ValidateResult.ValueTooLong; - + if (Pattern != null && !Pattern.IsMatch(str)) return ValidateResult.ValueDontMatchPattern; - + return ValidateResult.Valid; } - + return ValidateResult.NotSupported; } } - + /// Validation result enum. public enum ValidateResult { /// The valid value. Valid, - + /// The value is missing. ValueIsMissing, - + /// The value too small. ValueTooSmall, - + /// The value too large. ValueTooLarge, - + /// The too few elements in collection. TooFewElementsInCollection, - + /// The too many elements in collection. TooManyElementsInCollection, - + /// The value too short. ValueTooShort, - + /// The value too long. ValueTooLong, - + /// The value don't match pattern. ValueDontMatchPattern, - + /// The not supported. NotSupported, } - + /// Validation result. public class ValidationResult { /// Gets the property invoker. public DynamicPropertyInvoker Property { get; internal set; } - + /// Gets the requirement definition. public RequiredAttribute Requirement { get; internal set; } - + /// Gets the value that is broken. public object Value { get; internal set; } - + /// Gets the result. - public ValidateResult Result { get;internal set;} + public ValidateResult Result { get; internal set; } } } -} - +} \ No newline at end of file diff --git a/DynamORM.Tests/Modify/DynamicModificationTests.cs b/DynamORM.Tests/Modify/DynamicModificationTests.cs index 53ed113..378f58e 100644 --- a/DynamORM.Tests/Modify/DynamicModificationTests.cs +++ b/DynamORM.Tests/Modify/DynamicModificationTests.cs @@ -71,11 +71,11 @@ namespace DynamORM.Tests.Modify var o = GetTestTable().Single(code: "201"); Assert.AreNotEqual(200, o.id); Assert.AreEqual("201", o.code.ToString()); - Assert.AreEqual(null, o.first); + Assert.IsNull(o.first); Assert.AreEqual("Gagarin", o.last); Assert.AreEqual("juri.gagarin@megacorp.com", o.email); Assert.AreEqual("bla, bla, bla", o.quote); - Assert.AreEqual(null, o.password); + Assert.IsNull(o.password); } /// Test row insertion by dynamic object. @@ -88,11 +88,11 @@ namespace DynamORM.Tests.Modify var o = GetTestTable().Single(code: "202"); Assert.AreNotEqual(200, o.id); Assert.AreEqual("202", o.code.ToString()); - Assert.AreEqual(null, o.first); + Assert.IsNull(o.first); Assert.AreEqual("Gagarin", o.last); Assert.AreEqual("juri.gagarin@megacorp.com", o.email); Assert.AreEqual("bla, bla, bla", o.quote); - Assert.AreEqual(null, o.password); + Assert.IsNull(o.password); } /// Test row insertion by mapped object. @@ -115,11 +115,11 @@ namespace DynamORM.Tests.Modify var o = u.Single(code: "203"); Assert.AreNotEqual(200, o.id); Assert.AreEqual("203", o.code.ToString()); - Assert.AreEqual(null, o.first); + Assert.IsNull(o.first); Assert.AreEqual("Gagarin", o.last); Assert.AreEqual("juri.gagarin@megacorp.com", o.email); Assert.AreEqual("bla, bla, bla", o.quote); - Assert.AreEqual(null, o.password); + Assert.IsNull(o.password); } /// Test row insertion by basic object. @@ -142,11 +142,11 @@ namespace DynamORM.Tests.Modify var o = u.Single(code: "204"); Assert.AreNotEqual(200, o.id); Assert.AreEqual("204", o.code.ToString()); - Assert.AreEqual(null, o.first); + Assert.IsNull(o.first); Assert.AreEqual("Gagarin", o.last); Assert.AreEqual("juri.gagarin@megacorp.com", o.email); Assert.AreEqual("bla, bla, bla", o.quote); - Assert.AreEqual(null, o.password); + Assert.IsNull(o.password); } #endregion Insert @@ -163,11 +163,11 @@ namespace DynamORM.Tests.Modify var o = GetTestTable().Single(code: "201"); Assert.AreEqual(1, o.id); Assert.AreEqual("201", o.code.ToString()); - Assert.AreEqual(null, o.first); + Assert.IsNull(o.first); Assert.AreEqual("Gagarin", o.last); Assert.AreEqual("juri.gagarin@megacorp.com", o.email); Assert.AreEqual("bla, bla, bla", o.quote); - Assert.AreEqual(null, o.password); + Assert.IsNull(o.password); } /// Test row updating by dynamic objects. @@ -180,11 +180,11 @@ namespace DynamORM.Tests.Modify var o = GetTestTable().Single(code: "202"); Assert.AreEqual(2, o.id); Assert.AreEqual("202", o.code.ToString()); - Assert.AreEqual(null, o.first); + Assert.IsNull(o.first); Assert.AreEqual("Gagarin", o.last); Assert.AreEqual("juri.gagarin@megacorp.com", o.email); Assert.AreEqual("bla, bla, bla", o.quote); - Assert.AreEqual(null, o.password); + Assert.IsNull(o.password); } /// Test row updating by mapped object. @@ -207,11 +207,11 @@ namespace DynamORM.Tests.Modify var o = u.Single(code: "203"); Assert.AreEqual(3, o.id); Assert.AreEqual("203", o.code.ToString()); - Assert.AreEqual(null, o.first); + Assert.IsNull(o.first); Assert.AreEqual("Gagarin", o.last); Assert.AreEqual("juri.gagarin@megacorp.com", o.email); Assert.AreEqual("bla, bla, bla", o.quote); - Assert.AreEqual(null, o.password); + Assert.IsNull(o.password); } /// Test row updating by basic object. @@ -234,11 +234,11 @@ namespace DynamORM.Tests.Modify var o = u.Single(code: "204"); Assert.AreEqual(4, o.id); Assert.AreEqual("204", o.code.ToString()); - Assert.AreEqual(null, o.first); + Assert.IsNull(o.first); Assert.AreEqual("Gagarin", o.last); Assert.AreEqual("juri.gagarin@megacorp.com", o.email); Assert.AreEqual("bla, bla, bla", o.quote); - Assert.AreEqual(null, o.password); + Assert.IsNull(o.password); } /// Test row updating by dynamic objects. @@ -251,11 +251,11 @@ namespace DynamORM.Tests.Modify var o = GetTestTable().Single(code: "205"); Assert.AreEqual(5, o.id); Assert.AreEqual("205", o.code.ToString()); - Assert.AreEqual(null, o.first); + Assert.IsNull(o.first); Assert.AreEqual("Gagarin", o.last); Assert.AreEqual("juri.gagarin@megacorp.com", o.email); Assert.AreEqual("bla, bla, bla", o.quote); - Assert.AreEqual(null, o.password); + Assert.IsNull(o.password); } /// Test row updating by mapped objects. @@ -278,11 +278,11 @@ namespace DynamORM.Tests.Modify var o = u.Single(code: "206"); Assert.AreEqual(6, o.id); Assert.AreEqual("206", o.code.ToString()); - Assert.AreEqual(null, o.first); + Assert.IsNull(o.first); Assert.AreEqual("Gagarin", o.last); Assert.AreEqual("juri.gagarin@megacorp.com", o.email); Assert.AreEqual("bla, bla, bla", o.quote); - Assert.AreEqual(null, o.password); + Assert.IsNull(o.password); } /// Test row updating by basic objects. @@ -305,11 +305,11 @@ namespace DynamORM.Tests.Modify var o = u.Single(code: "207"); Assert.AreEqual(7, o.id); Assert.AreEqual("207", o.code.ToString()); - Assert.AreEqual(null, o.first); + Assert.IsNull(o.first); Assert.AreEqual("Gagarin", o.last); Assert.AreEqual("juri.gagarin@megacorp.com", o.email); Assert.AreEqual("bla, bla, bla", o.quote); - Assert.AreEqual(null, o.password); + Assert.IsNull(o.password); } #endregion Update diff --git a/DynamORM/DynamORM.csproj b/DynamORM/DynamORM.csproj index 7b5a50c..f8ecfec 100644 --- a/DynamORM/DynamORM.csproj +++ b/DynamORM/DynamORM.csproj @@ -6,7 +6,7 @@ Copyright © RUSSEK Software 2012-2023 RUSSEK Software Grzegorz Russek - 1.6 + 1.7 https://git.dr4cul4.pl/RUSSEK-Software/DynamORM https://dr4cul4.pl DynamORM diff --git a/DynamORM/DynamicExtensions.cs b/DynamORM/DynamicExtensions.cs index c9b4858..d90e1ed 100644 --- a/DynamORM/DynamicExtensions.cs +++ b/DynamORM/DynamicExtensions.cs @@ -282,9 +282,9 @@ namespace DynamORM p.DbType = TypeMap.TryGetNullable(type) ?? DbType.String; if (type == typeof(DynamicExpando) || type == typeof(ExpandoObject)) - p.Value = ((IDictionary)item).Values.FirstOrDefault(); + p.Value = CorrectValue(p.DbType, ((IDictionary)item).Values.FirstOrDefault()); else - p.Value = item; + p.Value = CorrectValue(p.DbType, item); if (p.DbType == DbType.String) p.Size = item.ToString().Length > 4000 ? -1 : 4000; @@ -324,7 +324,7 @@ namespace DynamORM p.Scale = 4; } - p.Value = value == null ? DBNull.Value : value; + p.Value = CorrectValue(p.DbType, value); } else if (value == null || value == DBNull.Value) p.Value = DBNull.Value; @@ -337,7 +337,7 @@ namespace DynamORM else if (p.DbType == DbType.String) p.Size = value.ToString().Length > 4000 ? -1 : 4000; - p.Value = value; + p.Value = CorrectValue(p.DbType, value); } cmd.Parameters.Add(p); @@ -345,6 +345,24 @@ namespace DynamORM return cmd; } + private static object CorrectValue(DbType type, object value) + { + if (value == null || value == DBNull.Value) + return DBNull.Value; + + if ((type == DbType.String || type == DbType.AnsiString || type == DbType.StringFixedLength || type == DbType.AnsiStringFixedLength) && + !(value is string)) + return value.ToString(); + else if (type == DbType.Guid && value is string) + return Guid.Parse(value.ToString()); + else if (type == DbType.Guid && value is byte[] && ((byte[])value).Length == 16) + return new Guid((byte[])value); + else if (type == DbType.DateTime && value is TimeSpan) // HACK: This is specific for SQL Server, to be verified with other databases + return DateTime.Today.Add((TimeSpan)value); + + return value; + } + /// Extension for adding single parameter determining only type of object. /// Command to handle. /// Query builder containing schema. @@ -377,7 +395,7 @@ namespace DynamORM p.Scale = 4; } - p.Value = item.Value == null ? DBNull.Value : item.Value; + p.Value = item.Value == null ? DBNull.Value : CorrectValue(p.DbType, item.Value); } else if (item.Value == null || item.Value == DBNull.Value) p.Value = DBNull.Value; @@ -390,7 +408,7 @@ namespace DynamORM else if (p.DbType == DbType.String) p.Size = item.Value.ToString().Length > 4000 ? -1 : 4000; - p.Value = item.Value; + p.Value = CorrectValue(p.DbType, item.Value); } cmd.Parameters.Add(p); @@ -417,7 +435,7 @@ namespace DynamORM param.Size = size; param.Precision = precision; param.Scale = scale; - param.Value = value; + param.Value = CorrectValue(param.DbType, value); command.Parameters.Add(param); return command; @@ -463,7 +481,7 @@ namespace DynamORM param.DbType = databaseType; param.Precision = precision; param.Scale = scale; - param.Value = value; + param.Value = CorrectValue(param.DbType, value); command.Parameters.Add(param); return command; @@ -484,7 +502,7 @@ namespace DynamORM param.DbType = databaseType; param.Precision = precision; param.Scale = scale; - param.Value = value; + param.Value = CorrectValue(param.DbType, value); command.Parameters.Add(param); return command; @@ -524,7 +542,7 @@ namespace DynamORM param.Direction = parameterDirection; param.DbType = databaseType; param.Size = size; - param.Value = value ?? DBNull.Value; + param.Value = CorrectValue(param.DbType, value ?? DBNull.Value); command.Parameters.Add(param); return command; @@ -543,7 +561,7 @@ namespace DynamORM param.ParameterName = parameterName; param.DbType = databaseType; param.Size = size; - param.Value = value ?? DBNull.Value; + param.Value = CorrectValue(param.DbType, value ?? DBNull.Value); command.Parameters.Add(param); return command; @@ -560,7 +578,7 @@ namespace DynamORM IDbDataParameter param = command.CreateParameter(); param.ParameterName = parameterName; param.DbType = databaseType; - param.Value = value ?? DBNull.Value; + param.Value = CorrectValue(param.DbType, value ?? DBNull.Value); command.Parameters.Add(param); return command; @@ -611,7 +629,8 @@ namespace DynamORM { try { - ((IDbDataParameter)command.Parameters[parameterName]).Value = value; + var p = ((IDbDataParameter)command.Parameters[parameterName]); + p.Value = CorrectValue(p.DbType, value); } catch (Exception ex) { @@ -630,7 +649,8 @@ namespace DynamORM { try { - ((IDbDataParameter)command.Parameters[index]).Value = value; + var p = ((IDbDataParameter)command.Parameters[index]); + p.Value = CorrectValue(p.DbType, value); } catch (Exception ex) { diff --git a/Tester/Program.cs b/Tester/Program.cs index 8e82ebb..f760fd6 100644 --- a/Tester/Program.cs +++ b/Tester/Program.cs @@ -4,6 +4,7 @@ using System.Data; using System.Linq; using DynamORM; using DynamORM.Helpers; +using DynamORM.Mapper; namespace Tester { @@ -12,7 +13,7 @@ namespace Tester private static DynamicDatabase GetORM() { return new DynamicDatabase(System.Data.SqlClient.SqlClientFactory.Instance, - "packet size=4096;User Id=sa;Password=;data source=192.168.22.;initial catalog=PLAYGROUND;", + "packet size=4096;User Id=sa;Password=sWe7PepR;data source=192.168.22.10;initial catalog=PLAYGROUND;", DynamicDatabaseOptions.SingleConnection | DynamicDatabaseOptions.SingleTransaction | DynamicDatabaseOptions.SupportSchema | DynamicDatabaseOptions.SupportStoredProcedures | DynamicDatabaseOptions.SupportTop | DynamicDatabaseOptions.DumpCommands); @@ -25,41 +26,89 @@ namespace Tester private static void Main(string[] args) { - //var c = new System.Data.SqlClient.SqlConnection("packet size=4096;User Id=sa;Password=sa123;data source=192.168.0.6;initial catalog=DynamORM;"); using (var db = GetORM()) { - db.Execute(@"CREATE OR ALTER PROCEDURE sp_Exp_Scalar AS SELECT 42;"); - var res0 = db.Procedures.sp_Exp_Scalar(); - var res1 = db.Procedures.sp_Exp_Scalar(); + //ProcedureHell(db); - db.Execute(@"CREATE OR ALTER PROCEDURE sp_Exp_ReturnInt AS RETURN 42;"); - var res2 = db.Procedures.sp_Exp_ReturnInt(); + TableFun(db); + } + } - db.Execute(@"CREATE OR ALTER PROCEDURE sp_Exp_SomeData AS + private static void TableFun(DynamicDatabase db) + { + try + { + db.Execute("DROP TABLE Experiments "); + } + catch { } + + db.Execute(@"CREATE TABLE Experiments ( + id int NOT NULL PRIMARY KEY, + t1 nvarchar(50) NOT NULL DEFAULT N'', + t2 varchar(50) NOT NULL DEFAULT '', + dd date, + tt time);"); + + db.Insert().Insert(new Ex + { + id = 1, + t1 = "T1", + t2 = "T1", + dd = DateTime.Now, + tt = TimeSpan.FromDays(2) + TimeSpan.FromHours(10), + }).Execute(); + + var tt = db.From().Where(x => x.id == 1).ToList().FirstOrDefault(); + + db.Update().Where(x => x.id == 1).Set(x => x.tt = TimeSpan.FromMinutes(10), x => x.dd = DateTime.Now.AddDays(2)).Execute(); + + db.Execute("DROP TABLE Experiments "); + } + + [Table(Name = "Experiments")] + private class Ex + { + public int id { get; set; } + public string t1 { get; set; } + public string t2 { get; set; } + public DateTime dd { get; set; } + public TimeSpan tt { get; set; } + } + + private static void ProcedureHell(DynamicDatabase db) + { + db.Execute(@"CREATE OR ALTER PROCEDURE sp_Exp_Scalar AS SELECT 42;"); + var res0 = db.Procedures.sp_Exp_Scalar(); + var res1 = db.Procedures.sp_Exp_Scalar(); + + db.Execute(@"CREATE OR ALTER PROCEDURE sp_Exp_ReturnInt AS RETURN 42;"); + var res2 = db.Procedures.sp_Exp_ReturnInt(); + + db.Execute(@"CREATE OR ALTER PROCEDURE sp_Exp_SomeData AS SELECT 1 Id, 'Some Name 1' [Name], 'Some Desc 1' [Desc], GETDATE() [Date] UNION ALL SELECT 2 Id, 'Some Name 2', 'Some Desc 2', GETDATE() [Date];"); - var res3 = db.Procedures.sp_Exp_SomeData(); - var res4 = db.Procedures.sp_Exp_SomeData>(); + var res3 = db.Procedures.sp_Exp_SomeData(); + var res4 = db.Procedures.sp_Exp_SomeData>(); - db.Execute(@"CREATE OR ALTER PROCEDURE sp_Exp_SomeInputAndOutput + db.Execute(@"CREATE OR ALTER PROCEDURE sp_Exp_SomeInputAndOutput @Name nvarchar(50), @Result nvarchar(256) OUTPUT AS SELECT @Result = 'Hi, ' + @Name + ' your lucky number is 42!';"); - var res5 = db.Procedures.sp_Exp_SomeInputAndOutput(Name: "G4g4r1n", out_Result: new DynamicColumn - { - Schema = new DynamicSchemaColumn - { - Size = 256, - }, - }, ret_Return: 0); - var res6 = db.Procedures.sp_Exp_SomeInputAndOutput(Name: "G4g4r1n", out_Result: new DynamicSchemaColumn + var res5 = db.Procedures.sp_Exp_SomeInputAndOutput(Name: "G4g4r1n", out_Result: new DynamicColumn + { + Schema = new DynamicSchemaColumn { Size = 256, - }, ret_Return: 0); + }, + }, ret_Return: 0); + var res6 = db.Procedures.sp_Exp_SomeInputAndOutput(Name: "G4g4r1n", out_Result: new DynamicSchemaColumn + { + Size = 256, + }, ret_Return: 0); - db.Execute(@"CREATE OR ALTER PROCEDURE sp_Exp_SomeInputAndOutputWithDataAndReturn + db.Execute(@"CREATE OR ALTER PROCEDURE sp_Exp_SomeInputAndOutputWithDataAndReturn @Name nvarchar(50), @Result nvarchar(256) OUTPUT AS @@ -69,52 +118,17 @@ SELECT 1 Id, 'Some Name 1' [Name], 'Some Desc 1' [Desc], GETDATE() [Date] UNION ALL SELECT 2 Id, 'Some Name 2', 'Some Desc 2', GETDATE() [Date] RETURN 42;"); - var res7 = db.Procedures.sp_Exp_SomeInputAndOutputWithDataAndReturn, sp_Exp_SomeInputAndOutputWithDataAndReturn_Result>(Name: "G4g4r1n", out_Result: new DynamicColumn - { - Schema = new DynamicSchemaColumn - { - Size = 256, - }, - }, ret_Return: 0); - var res8 = db.Procedures.sp_Exp_SomeInputAndOutputWithDataAndReturn, sp_Exp_SomeInputAndOutputWithDataAndReturn_Result>(Name: "G4g4r1n", out_Result: new DynamicSchemaColumn + var res7 = db.Procedures.sp_Exp_SomeInputAndOutputWithDataAndReturn, sp_Exp_SomeInputAndOutputWithDataAndReturn_Result>(Name: "G4g4r1n", out_Result: new DynamicColumn + { + Schema = new DynamicSchemaColumn { Size = 256, - }, ret_Return: 0); - - //try - //{ - // db.Execute("DROP TABLE Experiments "); - //} - //catch { } - - //db.Execute("CREATE TABLE Experiments (t1 nvarchar(50) NOT NULL DEFAULT N'', t2 varchar(50) NOT NULL DEFAULT '');"); - - //var q = db.From(x => x.Experiments.As(x.e1)); - //q - // .Where(x => x.t2 = "Dupa") - // .Where(x => x.Exists( - // q.SubQuery() - // .From(y => y.Experiments.As(x.e2)) - // .Where(y => y.e2.t1 == y.e1.t1))) - // .Execute().ToList(); - - //db.Execute("DROP TABLE Experiments "); - - //IDataReader rdr = db.Procedures.sp_getdate(); - //var dt = rdr.ToDataTable(); - //var dt2 = db.Procedures.sp_getdate(); - - //db.Procedures.usp_API_Generate_Doc_Number(key: Guid.NewGuid(), mdn_id: "ZZ"); - - //var resL = (db.Procedures.GetProductDesc>() as IEnumerable) - // .Cast() - // .ToArray(); - //var res = db.Procedures.GetProductDesc_withparameters(PID: 707); - //res = db.Procedures.GetProductDesc_withDefaultparameters(); - - //int id = -1; - //var resD = db.Procedures.ins_NewEmp_with_outputparamaters(Ename: "Test2", out_EId: id); - } + }, + }, ret_Return: 0); + var res8 = db.Procedures.sp_Exp_SomeInputAndOutputWithDataAndReturn, sp_Exp_SomeInputAndOutputWithDataAndReturn_Result>(Name: "G4g4r1n", out_Result: new DynamicSchemaColumn + { + Size = 256, + }, ret_Return: 0); } private class sp_Exp_SomeData_Result