/// <summary>
        /// Updates entity in table "Ts", checks if the entity is modified if the entity is tracked by the Get() extension.
        /// </summary>
        /// <typeparam name="T">Type to be updated</typeparam>
        /// <param name="connection">Open SqlConnection</param>
        /// <param name="entitiesToUpsert">Entity to be updated</param>
        /// <param name="transaction">The transaction to run under, null (the default) if none</param>
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
        /// <returns>true if updated, false if not found or not modified (tracked entities)</returns>
        public async static Task <int> UpsertBulkAsync <T>(
            this SqlConnection connection,
            IEnumerable <T> entitiesToUpsert,
            SqlTransaction transaction       = null,
            int?commandTimeout               = null,
            Action <SqlBulkCopy> sqlBulkCopy = null
            ) where T : class
        {
            var typeMeta = TypeMeta.Get <T>();

            return(await connection.MergeBulkAsync <T>(
                       entitiesToUpsert,
                       transaction,
                       commandTimeout,
                       sqlBulkCopy : sqlBulkCopy,
                       matched =>
            {
                matched.Action = MergeAction.Update;
                matched.Condition = typeMeta.PropertiesExceptKeyAndComputed.ColumnListDifferenceCheck();
            },
                       notMatchedByTarget =>
            {
                notMatchedByTarget.Action = MergeAction.Insert;
            }
                       ));
        }
Example #2
0
        static AssetObject LoadObject(EndianStream es, int format, TypeMeta types)
        {
            var obj = new AssetObject();

            obj.PathId  = es.ReadUInt64();
            obj.DataOfs = es.ReadUInt32();
            obj.Size    = es.ReadUInt32();
            if (format < 17)
            {
                obj.TypeId  = es.ReadInt32();
                obj.ClassId = es.ReadInt16();
            }
            else
            {
                obj.TypeId  = es.ReadInt32();
                obj.ClassId = types.ClassIds[obj.TypeId];
            }
            if (format <= 16)
            {
                es.ReadInt16();
            }
            if (format == 15 || format == 16)
            {
                es.ReadByte();
            }
            return(obj);
        }
Example #3
0
        public void Insert <T>(T item)
        {
            if (ConnectionData == null)
            {
                return;
            }
            try
            {
                using (var command = DbConnection.CreateCommand())
                {
                    var meta       = new TypeMeta(typeof(T));
                    var properties = meta.Properties.Where(p => p.HasGetter).ToList();
                    foreach (var property in properties)
                    {
                        var parameterName = string.Format("@{0}", property.Name);
                        var value         = property.GetValue(item) ?? DBNull.Value;
                        command.Parameters.Add(new SqlParameter(parameterName, value));
                    }

                    var insert = new StringBuilder("insert into ").AppendFormat(meta.Type.Name)
                                 .AppendFormat(" ({0})", string.Join(", ", properties.Select(p => p.Name)))
                                 .Append(" values ")
                                 .AppendFormat(" ({0})", string.Join(", ", command.Parameters.Cast <SqlParameter>().Select(p => p.ParameterName)));
                    command.CommandText = insert.ToString();

                    DbConnection.Open();
                    command.ExecuteNonQuery();
                }
            }
            finally
            {
                DbConnection.Close();
            }
        }
 private static string NicifyNamespaceQualifiedInstallerTitle(Type installerType)
 {
     return(TypeMeta.NicifyNamespaceQualifiedName(
                installerType.Namespace,
                NicifyInstallerTitle(installerType)
                ));
 }
        /// <summary>
        /// Inserts an entity into table "Ts" and returns identity id or number of inserted rows if inserting a list.
        /// </summary>
        /// <typeparam name="T">The type to insert.</typeparam>
        /// <param name="connection">Open SqlConnection</param>
        /// <param name="entitiesToInsert">Entity to insert, can be list of entities</param>
        /// <param name="transaction">The transaction to run under, null (the default) if none</param>
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
        /// <returns>Identity of inserted entity, or number of inserted rows if inserting a list</returns>
        public async static Task <int> InsertBulkAsync <T>(
            this SqlConnection connection,
            IEnumerable <T> entitiesToInsert,
            SqlTransaction transaction       = null,
            int?commandTimeout               = null,
            Action <SqlBulkCopy> sqlBulkCopy = null
            ) where T : class
        {
            var meta = TypeMeta.Get <T>();

            var wasClosed = connection.State == ConnectionState.Closed;

            if (wasClosed)
            {
                connection.Open();
            }

            var insertedTableName = await connection.TransferBulkAsync(entitiesToInsert, transaction : transaction, sqlBulkCopy : sqlBulkCopy);

            var columnList = meta.PropertiesExceptKeyAndComputed.ColumnList();

            var query = $@"
                INSERT INTO {meta.TableName} ({columnList}) 
                SELECT {columnList} FROM {insertedTableName};
			"            ;

            var inserted = await connection.ExecuteAsync(query, commandTimeout, transaction);

            if (wasClosed)
            {
                connection.Close();
            }

            return(inserted);
        }
Example #6
0
 /// <summary>
 /// Gets an array of all the instantiatable <see cref="IElementAdderMenuCommand{TContext}"/>
 /// implementations that are annotated with <see cref="ElementAdderMenuCommandAttribute"/>.
 private static IEnumerable <Type> GetAnnotatedCommandTypes <TContext>()
 {
     return
         (from type in TypeMeta.DiscoverImplementations <IElementAdderMenuCommand <TContext> >()
          where type.IsClass && type.IsDefined(typeof(ElementAdderMenuCommandAttribute), false)
          select type);
 }
        TreeNode CreateTreeNode(TypeMeta tm)
        {
            var children = tm.Properties.Select(p =>
                                                new TreeNode(p.Name, new[]
            {
                new TreeNode("Type:" + p.BaseType.ToString())
                {
                    Tag = p.BaseType
                },
                new TreeNode("IsOptional:" + p.IsOptional.ToString())
                {
                    Tag = p.IsOptional
                }
            })
            {
                Tag = p
            })
                           .ToArray();
            var tn = new TreeNode(tm.Name, children)
            {
                Tag = tm
            };

            return(tn);
        }
Example #8
0
        /// <summary>
        /// Updates entity in table "Ts", checks if the entity is modified if the entity is tracked by the Get() extension.
        /// </summary>
        /// <typeparam name="T">Type to be updated</typeparam>
        /// <param name="connection">Open SqlConnection</param>
        /// <param name="entitiesToDelete">Entity to be updated</param>
        /// <param name="transaction">The transaction to run under, null (the default) if none</param>
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
        /// <returns>true if updated, false if not found or not modified (tracked entities)</returns>
        public async static Task <int> DeleteBulkAsync <T>(
            this SqlConnection connection,
            IEnumerable <T> entitiesToDelete,
            SqlTransaction transaction       = null,
            int?commandTimeout               = null,
            Action <SqlBulkCopy> sqlBulkCopy = null
            ) where T : class
        {
            var entityCount = entitiesToDelete.Count();

            if (entityCount == 0)
            {
                return(0);
            }

            if (entityCount == 1)
            {
                return(await connection.DeleteAsync(entitiesToDelete.First(), transaction : transaction, commandTimeout : commandTimeout) ? 1 : 0);
            }

            var typeMeta = TypeMeta.Get <T>();

            if (typeMeta.PropertiesKey.Count == 0 && typeMeta.PropertiesExplicit.Count == 0)
            {
                throw new ArgumentException("Entity must have at least one [Key] or [ExplicitKey] property");
            }

            var wasClosed = connection.State == ConnectionState.Closed;

            if (wasClosed)
            {
                connection.Open();
            }

            var insertedTableName = await connection.TransferBulkAsync(
                entitiesToDelete,
                typeMeta.TableName,
                typeMeta.PropertiesKeyAndExplicit,
                transaction : transaction,
                sqlBulkCopy : sqlBulkCopy
                );

            var query = $@"
				DELETE Target
				FROM
					{ insertedTableName } AS Source
					INNER JOIN { typeMeta.TableName } AS Target
						ON { typeMeta.PropertiesKeyAndExplicit.ColumnListEquals(" AND ") };
			"            ;

            var deleted = await connection.ExecuteAsync(query, commandTimeout : commandTimeout, transaction : transaction);

            if (wasClosed)
            {
                connection.Close();
            }

            return(deleted);
        }
Example #9
0
        private string FormatTypeDisplayName(Type type)
        {
            var formatter = this.TypeDisplayNameFormatter;

            return(formatter != null
                ? formatter.Invoke(type)
                : TypeMeta.NicifyName(type.Name));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceDescriptor"/> class.
        /// </summary>
        /// <param name="serviceType">The type representing the service.</param>
        public ServiceDescriptor(Type serviceType)
        {
            this.ServiceType  = serviceType;
            this.dependencies = ForDependenciesOf(serviceType).ToArray();

            this.Title = TypeMeta.NicifyCompoundName(this.ServiceType.Name, unwantedSuffix: "_Service");
            this.TitleWithNamespace = TypeMeta.NicifyNamespaceQualifiedName(this.ServiceType.Namespace, this.Title);
        }
 public ProxyTypeDescriptor(Type type)
 {
     Meta                = TypeMeta.Get(type);
     ProxyType           = typeof(PlatformProxy <>).MakeGenericType(type);
     _properties         = Meta.Members.Select(m => new ProxyPropertyDescriptor(this, m)).ToArray();
     _propertyCollection = new PropertyDescriptorCollection(_properties);
     _events             = new EventDescriptorCollection(type.GetEvents().Select(e => new ProxyEventDescriptor(e)).ToArray());
 }
        public MergeActionOptions <T> Insert()
        {
            var typeMeta = TypeMeta.Get <T>();

            Action = MergeAction.Insert;
            ColumnsByPropertyInfo(typeMeta.PropertiesExceptKeyAndComputed);

            return(this);
        }
Example #13
0
        /// <summary>
        /// Merges entity in table "Ts", checks if the entity is modified if the entity is tracked by the Get() extension.
        /// </summary>
        /// <typeparam name="T">Type to be updated</typeparam>
        /// <param name="connection">Open SqlConnection</param>
        /// <param name="entitiesToMerge">Entity to be updated</param>
        /// <param name="transaction">The transaction to run under, null (the default) if none</param>
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
        /// <returns>true if updated, false if not found or not modified (tracked entities)</returns>
        public async static Task <int> MergeBulkAsync <T>(
            this SqlConnection connection,
            IEnumerable <T> entitiesToMerge,
            SqlTransaction transaction                          = null,
            int?commandTimeout                                  = null,
            Action <SqlBulkCopy> sqlBulkCopy                    = null,
            Action <MergeKeyOptions> key                        = null,
            Action <MergeActionOptions <T> > matched            = null,
            Action <MergeActionOptions <T> > notMatchedByTarget = null,
            Action <MergeActionOptions <T> > notMatchedBySource = null
            ) where T : class
        {
            if (entitiesToMerge == null)
            {
                throw new ArgumentNullException(nameof(entitiesToMerge));
            }

            var entityCount = entitiesToMerge.Count();

            if (entityCount == 0)
            {
                return(0);
            }

            var typeMeta = TypeMeta.Get <T>();

            if (typeMeta.PropertiesKey.Count == 0 && typeMeta.PropertiesExplicit.Count == 0)
            {
                throw new ArgumentException("Entity must have at least one [Key] or [ExplicitKey] property");
            }

            var result = await connection.Execute(
                entitiesToMerge,
                typeMeta.PropertiesExceptComputed,
                async (connection, transaction, source, parameters, properties) =>
            {
                var sb = new StringBuilder($@"
						MERGE INTO {typeMeta.TableName} AS Target
						USING {source} AS Source
						ON ({OnColumns(typeMeta, keyAction: key).ColumnListEquals(" AND ")})"
                                           );
                sb.AppendLine();

                MergeMatchResult.Matched.Format(typeMeta, matched, sb);
                MergeMatchResult.NotMatchedBySource.Format(typeMeta, notMatchedBySource, sb);
                MergeMatchResult.NotMatchedByTarget.Format(typeMeta, notMatchedByTarget, sb);
                //MergeOutputFormat(typeMeta.PropertiesKey.Union(typeMeta.PropertiesComputed).ToList(), sb);
                sb.Append(";");

                return(await connection.ExecuteAsync(sb.ToString(), param: parameters, commandTimeout: commandTimeout, transaction: transaction));
            },
                transaction : transaction
                );

            return(result.Sum());
        }
        public MergeActionOptions <T> Update()
        {
            var typeMeta = TypeMeta.Get <T>();

            Action = MergeAction.Update;
            ColumnsByPropertyInfo(typeMeta.PropertiesExceptKeyAndComputed);
            CheckConditionOnColumns();

            return(this);
        }
        /// <summary>
        /// Merges entity in table "Ts", checks if the entity is modified if the entity is tracked by the Get() extension.
        /// </summary>
        /// <typeparam name="T">Type to be updated</typeparam>
        /// <param name="connection">Open SqlConnection</param>
        /// <param name="entitiesToMerge">Entity to be updated</param>
        /// <param name="transaction">The transaction to run under, null (the default) if none</param>
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
        /// <returns>true if updated, false if not found or not modified (tracked entities)</returns>
        public async static Task <int> MergeBulkAsync <T>(
            this SqlConnection connection,
            IEnumerable <T> entitiesToMerge,
            SqlTransaction transaction                     = null,
            int?commandTimeout                             = null,
            Action <SqlBulkCopy> sqlBulkCopy               = null,
            Action <MergeActionOptions> matched            = null,
            Action <MergeActionOptions> notMatchedByTarget = null,
            Action <MergeActionOptions> notMatchedBySource = null
            ) where T : class
        {
            var typeMeta = TypeMeta.Get <T>();

            if (typeMeta.PropertiesKey.Count == 0 && typeMeta.PropertiesExplicit.Count == 0)
            {
                throw new ArgumentException("Entity must have at least one [Key] or [ExplicitKey] property");
            }

            var wasClosed = connection.State == System.Data.ConnectionState.Closed;

            if (wasClosed)
            {
                connection.Open();
            }

            var insertedTableName = await connection.TransferBulkAsync(
                entitiesToMerge,
                typeMeta.TableName,
                typeMeta.Properties,
                transaction : transaction,
                sqlBulkCopy : sqlBulkCopy
                );

            var sb = new StringBuilder($@"
				MERGE INTO {typeMeta.TableName} AS Target
				USING {insertedTableName} AS Source
				ON ({typeMeta.PropertiesKeyAndExplicit.ColumnListEquals(" AND ")})"
                                       );

            MergeMatchResult.Matched.Format(typeMeta, matched, sb);
            MergeMatchResult.NotMatchedBySource.Format(typeMeta, notMatchedBySource, sb);
            MergeMatchResult.NotMatchedByTarget.Format(typeMeta, notMatchedByTarget, sb);
            sb.Append(";");

            var merged = await connection.ExecuteAsync(sb.ToString(), commandTimeout : commandTimeout, transaction : transaction);

            if (wasClosed)
            {
                connection.Close();
            }

            return(merged);
        }
Example #16
0
        /// <summary>
        /// Updates entity in table "Ts", checks if the entity is modified if the entity is tracked by the Get() extension.
        /// </summary>
        /// <typeparam name="T">Type to be updated</typeparam>
        /// <param name="connection">Open SqlConnection</param>
        /// <param name="entitiesToUpdate">Entity to be updated</param>
        /// <param name="transaction">The transaction to run under, null (the default) if none</param>
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
        /// <returns>true if updated, false if not found or not modified (tracked entities)</returns>
        public async static Task <int> UpdateBulkAsync <T>(
            this SqlConnection connection,
            IEnumerable <T> entitiesToUpdate,
            SqlTransaction transaction       = null,
            int?commandTimeout               = null,
            Action <SqlBulkCopy> sqlBulkCopy = null
            ) where T : class
        {
            entitiesToUpdate = entitiesToUpdate.Where(x => (x is SqlMapperExtensions.IProxy proxy && !proxy.IsDirty) || !(x is SqlMapperExtensions.IProxy));

            var entityCount = entitiesToUpdate.Count();

            if (entityCount == 0)
            {
                return(0);
            }

            if (entityCount == 1)
            {
                return(await connection.UpdateAsync(entitiesToUpdate.First(), transaction : transaction, commandTimeout : commandTimeout) ? 1 : 0);
            }

            var typeMeta = TypeMeta.Get <T>();

            if (typeMeta.PropertiesKey.Count == 0 && typeMeta.PropertiesExplicit.Count == 0)
            {
                throw new ArgumentException("Entity must have at least one [Key] or [ExplicitKey] property");
            }

            var result = await connection.Execute(
                entitiesToUpdate,
                typeMeta.PropertiesExceptComputed,
                async (connection, transaction, source, parameters, properties) =>
            {
                var query = $@"
						UPDATE Target
						SET
							{ typeMeta.PropertiesExceptKeyAndComputed.ColumnListEquals(", ") }
						FROM
							{ source } AS Source
							INNER JOIN { typeMeta.TableName } AS Target
								ON { typeMeta.PropertiesKeyAndExplicit.ColumnListEquals(" AND ") };
					"                    ;

                return(await connection.ExecuteAsync(query, param: parameters, commandTimeout: commandTimeout, transaction: transaction));
            },
                transaction : transaction
                );

            return(result.Sum());
        }
Example #17
0
        /// <summary>
        /// Discovers all of the available installer types for a given service.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <returns>
        /// An array of zero-or-more non-abstract installer types.
        /// </returns>
        public static Type[] DiscoverInstallerTypes(IServiceDescriptor service)
        {
            if (s_ServiceInstallerTypes == null)
            {
                s_ServiceInstallerTypes = TypeMeta.DiscoverImplementations <ZenjectServiceInstaller>();
            }

            var genericInstallerType = typeof(ZenjectServiceInstaller <>).MakeGenericType(service.ServiceType);

            return(s_ServiceInstallerTypes
                   .Where(installerType => genericInstallerType.IsAssignableFrom(installerType))
                   .Where(installerType => !installerType.IsAbstract && installerType.IsClass)
                   .ToArray());
        }
Example #18
0
        public static ProxyXamlType Get(Type type)
        {
            var meta = TypeMeta.Get(type);

            lock (_cache)
            {
                ProxyXamlType result;
                if (!_cache.TryGetValue(type, out result))
                {
                    _cache[type] = result = new ProxyXamlType(meta);
                }
                return(result);
            }
        }
        /// <summary>
        /// Updates entity in table "Ts", checks if the entity is modified if the entity is tracked by the Get() extension.
        /// </summary>
        /// <typeparam name="T">Type to be updated</typeparam>
        /// <param name="connection">Open SqlConnection</param>
        /// <param name="entitiesToUpdate">Entity to be updated</param>
        /// <param name="transaction">The transaction to run under, null (the default) if none</param>
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
        /// <returns>true if updated, false if not found or not modified (tracked entities)</returns>
        public async static Task <bool> UpdateBulkAsync <T>(
            this SqlConnection connection,
            IEnumerable <T> entitiesToUpdate,
            SqlTransaction transaction       = null,
            int?commandTimeout               = null,
            Action <SqlBulkCopy> sqlBulkCopy = null
            ) where T : class
        {
            entitiesToUpdate = entitiesToUpdate.Where(x => x is SqlMapperExtensions.IProxy proxy && !proxy.IsDirty);
            if (!entitiesToUpdate.Any())
            {
                return(false);
            }

            var typeMeta = TypeMeta.Get <T>();

            if (typeMeta.PropertiesKey.Count == 0 && typeMeta.PropertiesExplicit.Count == 0)
            {
                throw new ArgumentException("Entity must have at least one [Key] or [ExplicitKey] property");
            }

            var wasClosed = connection.State == ConnectionState.Closed;

            if (wasClosed)
            {
                connection.Open();
            }

            var insertedTableName = await connection.TransferBulkAsync(entitiesToUpdate, transaction : transaction, sqlBulkCopy : sqlBulkCopy);

            var query = $@"
				UPDATE Target
				SET
					{ typeMeta.PropertiesExceptKeyAndComputed.ColumnListEquals(", ") }
				FROM
					{ insertedTableName } AS Source
					INNER JOIN { typeMeta.TableName } AS Target
						ON { typeMeta.PropertiesKeyAndExplicit.ColumnListEquals(" AND ") };
			"            ;

            var updated = await connection.ExecuteAsync(query, commandTimeout : commandTimeout, transaction : transaction);

            if (wasClosed)
            {
                connection.Close();
            }

            return(updated > 0);
        }
Example #20
0
        public static IEnumerable <string> OnColumns(TypeMeta typeMeta, Action <MergeKeyOptions> keyAction = null)
        {
            var options = new MergeKeyOptions();

            if (keyAction == null)
            {
                options.ColumnsByPropertyInfo(typeMeta.PropertiesKeyAndExplicit);
            }
            else
            {
                keyAction(options);
            }

            return(options.Columns);
        }
        public static Type Build(TypeMeta meta)
        {
            TypeBuilder            builder = moduleBuilder.DefineType(meta.TypeName, TypeAttributes.Public);
            CustomAttributeBuilder tableAttributeBuilder = new CustomAttributeBuilder(typeof(TableAttribute).GetConstructor(new Type[1] {
                typeof(string)
            }), new object[] { "RuntimeModel_" + meta.TypeName });

            builder.SetParent(meta.BaseType);
            builder.SetCustomAttribute(tableAttributeBuilder);

            foreach (var item in meta.PropertyMetas)
            {
                AddProperty(item, builder, meta.BaseType);
            }
            return(builder.CreateTypeInfo().UnderlyingSystemType);
        }
Example #22
0
        public async static Task <IEnumerable <T> > GetBulkAsync <T>(
            this SqlConnection connection,
            IEnumerable <T> entitiesToGet,
            SqlTransaction transaction       = null,
            int?commandTimeout               = null,
            Action <SqlBulkCopy> sqlBulkCopy = null
            )
        {
            var typeMeta = TypeMeta.Get <T>();

            if (typeMeta.PropertiesKey.Count == 0 && typeMeta.PropertiesExplicit.Count == 0)
            {
                throw new ArgumentException("Entity must have at least one [Key] or [ExplicitKey] property");
            }

            var wasClosed = connection.State == ConnectionState.Closed;

            if (wasClosed)
            {
                connection.Open();
            }

            var insertedTableName = await connection.TransferBulkAsync(
                entitiesToGet,
                typeMeta.TableName,
                typeMeta.PropertiesKeyAndExplicit,
                transaction : transaction,
                sqlBulkCopy : sqlBulkCopy
                );

            var query = $@"
				SELECT *
				FROM
					{ insertedTableName } AS Source
					INNER JOIN { typeMeta.TableName } AS Target
						ON { typeMeta.PropertiesKeyAndExplicit.ColumnListEquals(" AND ") };
			"            ;

            var enities = await connection.QueryAsync <T>(query, commandTimeout : commandTimeout, transaction : transaction);

            if (wasClosed)
            {
                connection.Close();
            }

            return(enities);
        }
Example #23
0
        public static async Task <string> TransferBulkAsync <T>(
            this SqlConnection connection,
            IEnumerable <T> entitiesToInsert,
            SqlTransaction transaction       = null,
            Action <SqlBulkCopy> sqlBulkCopy = null
            )
        {
            var meta = TypeMeta.Get <T>();

            return(await connection.TransferBulkAsync(
                       entitiesToInsert,
                       meta.TableName,
                       meta.Properties,
                       transaction : transaction,
                       sqlBulkCopy : sqlBulkCopy
                       ));
        }
Example #24
0
        /// <summary>
        /// Populates a menu with concrete element types.
        /// </summary>
        /// <param name="menu">Editor menu.</param>
        /// <exception cref="System.ArgumentNullException">
        /// If <paramref name="menu"/> is <c>null</c>.
        /// </exception>
        public void PopulateWithConcreteTypes(EditorMenu menu)
        {
            ExceptionUtility.CheckArgumentNotNull(menu, "menu");

            menu.AddSeparator();

            foreach (var concreteType in ApplyTypeFilter(TypeMeta.DiscoverImplementations(this.ElementContractType)))
            {
                menu.AddCommand(this.FormatTypeDisplayName(concreteType))
                .Enabled(this.ElementAdder != null && this.ElementAdder.CanAddElement(concreteType))
                .Action(() => {
                    if (this.ElementAdder.CanAddElement(concreteType))
                    {
                        this.ElementAdder.AddElement(concreteType);
                    }
                });
            }
        }
        private static void Format(this MergeMatchResult result, TypeMeta typeMeta, Action <MergeActionOptions> optionsAction, StringBuilder sb)
        {
            if (optionsAction == null)
            {
                return;
            }

            var options = new MergeActionOptions();

            optionsAction(options);
            if (options.Action == MergeAction.None)
            {
                return;
            }

            if (options.Columns == null)
            {
                options.Columns = typeMeta.PropertiesExceptKeyAndComputed;
            }

            switch (result)
            {
            case MergeMatchResult.Matched:
                sb.Append("WHEN MATCHED");
                break;

            case MergeMatchResult.NotMatchedBySource:
                sb.AppendLine("WHEN NOT MATCHED BY SOURCE");
                break;

            case MergeMatchResult.NotMatchedByTarget:
                sb.AppendLine("WHEN NOT MATCHED BY TARGET");
                break;
            }

            if (!string.IsNullOrEmpty(options.Condition))
            {
                sb.AppendFormat(" AND ({0})", options.Condition);
            }
            sb.AppendLine(" THEN");

            MergeActionFormat(options, sb);
        }
Example #26
0
        protected virtual void AddEntry(SerializedProperty entries, int index, TypeMeta typeMeta)
        {
            if (index < 0 || index > entries.arraySize)
            {
                return;
            }

            entries.serializedObject.Update();
            entries.InsertArrayElementAtIndex(index);
            SerializedProperty entryProperty = entries.GetArrayElementAtIndex(index);

            entryProperty.FindPropertyRelative("TypeName").stringValue     = typeMeta.Type.FullName;
            entryProperty.FindPropertyRelative("PropertyName").stringValue = typeMeta.Members[0];
            entryProperty.FindPropertyRelative("Key").stringValue          = "";
            entryProperty.FindPropertyRelative("Mode").enumValueIndex      = (int)BindingMode.OneWay;

            entries.serializedObject.ApplyModifiedProperties();
            GUI.FocusControl(null);
        }
Example #27
0
        /// <summary>
        /// Inserts an entity into table "Ts" and returns identity id or number of inserted rows if inserting a list.
        /// </summary>
        /// <typeparam name="T">The type to insert.</typeparam>
        /// <param name="connection">Open SqlConnection</param>
        /// <param name="entitiesToInsert">Entity to insert, can be list of entities</param>
        /// <param name="transaction">The transaction to run under, null (the default) if none</param>
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
        /// <returns>Identity of inserted entity, or number of inserted rows if inserting a list</returns>
        public async static Task <int> InsertBulkAsync <T>(
            this SqlConnection connection,
            IEnumerable <T> entitiesToInsert,
            SqlTransaction transaction       = null,
            int?commandTimeout               = null,
            Action <SqlBulkCopy> sqlBulkCopy = null
            ) where T : class
        {
            var entityCount = entitiesToInsert.Count();

            if (entityCount == 0)
            {
                return(0);
            }

            if (entityCount == 1)
            {
                return(await connection.InsertAsync(entitiesToInsert, transaction : transaction, commandTimeout : commandTimeout));
            }

            var typeMeta = TypeMeta.Get <T>();

            var result = await connection.Execute(
                entitiesToInsert,
                typeMeta.PropertiesExceptKeyAndComputed,
                async (connection, transaction, source, parameters, properties) =>
            {
                var columnList = properties.ColumnList();

                var query = $@"
							INSERT INTO {typeMeta.TableName} ({columnList}) 
							SELECT {columnList} FROM {source} AS Source;
						"                        ;

                return(await connection.ExecuteAsync(query, param: parameters, commandTimeout: commandTimeout, transaction: transaction));
            },
                transaction : transaction
                );

            return(result.Sum());
        }
Example #28
0
        private ITypeMap CreateMap(Type sourceType, Type targetType)
        {
            var target = new TypeMeta(targetType);

            if (target.IsSimple)
            {
                return(new SimpleTypeMap(sourceType, targetType, this));
            }
            if (target.IsDictionary)
            {
            }
            if (target.IsCollection)
            {
                return(new CollectionTypeMap(sourceType, targetType, this));
            }
            if (target.IsComplex)
            {
                return(new TypeMap(sourceType, targetType, this));
            }
            throw new Tantrum(string.Format("Don't know how to map {0}", targetType));
        }
Example #29
0
        public override object Map(object source)
        {
            if (source == null)
            {
                return(null);
            }
            var target = TypeMeta.New(TargetType.Type);

            foreach (var propertyMap in _propertyMaps)
            {
                try
                {
                    propertyMap.Map(source, target);
                }
                catch (Exception ex)
                {
                    throw new MappingException(string.Format("Could not map property {0}", propertyMap.FullName), ex);
                }
            }
            return(target);
        }
Example #30
0
        /// <summary>
        /// Updates entity in table "Ts", checks if the entity is modified if the entity is tracked by the Get() extension.
        /// </summary>
        /// <typeparam name="T">Type to be updated</typeparam>
        /// <param name="connection">Open SqlConnection</param>
        /// <param name="entitiesToUpsert">Entity to be updated</param>
        /// <param name="transaction">The transaction to run under, null (the default) if none</param>
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
        /// <returns>true if updated, false if not found or not modified (tracked entities)</returns>
        public async static Task <int> UpsertBulkAsync <T>(
            this SqlConnection connection,
            IEnumerable <T> entitiesToUpsert,
            SqlTransaction transaction       = null,
            int?commandTimeout               = null,
            Action <SqlBulkCopy> sqlBulkCopy = null,
            Action <MergeKeyOptions> key     = null
            ) where T : class
        {
            var typeMeta = TypeMeta.Get <T>();

            return(await connection.MergeBulkAsync <T>(
                       entitiesToUpsert,
                       transaction,
                       commandTimeout,
                       sqlBulkCopy : sqlBulkCopy,
                       key : key,
                       matched : options => options.Update(),
                       notMatchedByTarget : options => options.Insert()
                       ));
        }
Example #31
0
 public InstructionType(InstructionKindEnum aKind, int aIndex, TypeMeta aType)
     : base(aKind, aIndex)
 {
     Type = aType;
 }