예제 #1
0
        protected override ICommandResult ExecuteDeleteCommand(SqlModelCommand <T> dataCommand, IDbCommand command)
        {
            var result = new ModelCommandResult <T>();

            if (TableMapFromDatabase)
            {
                dataCommand.GetTableMap();
            }

            dataCommand.BuildSqlParameters(command);
            dataCommand.BuildSqlCommand();
            command.CommandText = dataCommand.SqlCommandText;

            OnBeforeCommandExecute(this, new ModelCommandBeforeExecuteEventArgs(dataCommand, command, DataCommandType.Delete));

            if (command.CommandText.ToUpper().Contains("WHERE"))
            {
                int records = command.ExecuteNonQuery();
                result.RecordsAffected = records;
                result.AddMessage(string.Format("{0} executed with {1} rows affected", dataCommand.SqlCommandText,
                                                records));
                dataCommand.ResetCommand();
            }
            else
            {
                result.AddError(LogType.Information, "No where in delete " + command.CommandText);
            }
            result.DataCommand = dataCommand;

            return(result);
        }
예제 #2
0
        protected override ICommandResult ExecuteSelectCommand(SqlModelCommand <T> dataCommand, IDbCommand command)
        {
            if (TableMapFromDatabase)
            {
                var map = dataCommand.GetTableMap();
                if (dataCommand.SelectAll == false)
                {
                    if (!string.IsNullOrEmpty(map))
                    {
                        var columns = dataCommand.GetColumnAttributes();
                        foreach (var columnMap in columns)
                        {
                            bool addColumn = true;
                            if (dataCommand.TableMap == null)
                            {
                                addColumn = false;
                            }

                            var column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == columnMap.ColumnName);
                            if (column == null)
                            {
                                addColumn = false;
                            }


                            if (addColumn)
                            {
                                dataCommand.Column(columnMap.ColumnName);
                            }
                        }
                        dataCommand.SelectAll = false;
                    }
                }
            }


            dataCommand.BuildSqlCommand();
            dataCommand.BuildSqlParameters(command);
            command.CommandText = dataCommand.SqlCommandText;
            var            items  = new List <T>();
            ICommandResult result = null;

            try
            {
                int rowsIndex = 0;


                OnBeforeCommandExecute(this, new ModelCommandBeforeExecuteEventArgs(dataCommand, command, DataCommandType.Select));
                using (SqlDataReader r = command.ExecuteReader() as SqlDataReader)
                {
                    Type objectType = typeof(T);

                    if (objectType == typeof(DataTable))
                    {
                        result = new DataTableCommandResult();
                        var dt = new DataTable(dataCommand.TableName);
                        dt.Load(r);


                        ((DataTableCommandResult)result).Data = dt;
                        result.RecordsAffected = dt.Rows.Count;

                        foreach (var item in dataCommand.TableMap.ColumnMaps)
                        {
                            if (item.ColumnName != item.PropertyName)
                            {
                                foreach (System.Data.DataColumn column in dt.Columns)
                                {
                                    if (item.ColumnName == column.ColumnName)
                                    {
                                        if (!string.IsNullOrEmpty(item.PropertyName))
                                        {
                                            if (item.IsMapped)
                                            {
                                                column.ColumnName = item.PropertyName;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        return(result);
                    }
                    result = new ModelCommandResult <T>();

                    var tablename = dataCommand.GetTableAttribute();

                    var accessor = TypeAccessor.Create(objectType);

                    ConstructorInfo ctor = objectType.GetConstructor(Type.EmptyTypes);
                    TrinityActivator.ObjectActivator <T> createdActivator = TrinityActivator.GetActivator <T>(ctor);

                    while (r.Read())
                    {
                        bool userDataManager = false;

                        //https://vagifabilov.wordpress.com/2010/04/02/dont-use-activator-createinstance-or-constructorinfo-invoke-use-compiled-lambda-expressions/

                        var newObject = createdActivator();
                        //var newObject = (T)Activator.CreateInstance(objectType);
                        var dataManager = newObject as IObjectDataManager;


                        if (dataCommand.TableMap != null)
                        {
                            if (dataCommand.TableName != objectType.Name)
                            {
                                if (tablename == dataCommand.TableName)
                                {
                                    if (dataManager != null)
                                    {
                                        userDataManager = true;
                                    }
                                    else
                                    {
                                        userDataManager = false;
                                    }
                                }
                            }
                            else
                            {
                                if (dataManager != null)
                                {
                                    userDataManager = true;
                                }
                            }
                        }

                        if (userDataManager)
                        {
                            dataManager.SetData(r);
                        }
                        else
                        {
                            //TODO Change code to use Reflection.Emit
                            int counter = r.FieldCount;
                            for (int i = 0; i < counter; i++)
                            {
                                var name = r.GetName(i);
                                try
                                {
                                    var fieldType = r.GetFieldType(i);
                                    var value     = r.GetValue(i);
                                    if (dataCommand.TableMap != null)
                                    {
                                        var column =
                                            dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == name);

                                        if (column != null)
                                        {
                                            if (!string.IsNullOrEmpty(column.PropertyName))
                                            {
                                                try
                                                {
                                                    if (value != DBNull.Value)
                                                    {
                                                        accessor[newObject, column.PropertyName] = value;
                                                    }
                                                }
                                                catch (Exception e)
                                                {
                                                    try
                                                    {
                                                        if (value != DBNull.Value)
                                                        {
                                                            var prop = objectType.GetProperty(column.PropertyName);
                                                            accessor[newObject, column.PropertyName] = value.ConvertValue(prop);
                                                        }
                                                    }
                                                    catch (Exception exception)
                                                    {
                                                        var prop = objectType.GetProperty(column.PropertyName);
                                                        if (prop != null)
                                                        {
                                                            if (value != DBNull.Value)
                                                            {
                                                                try
                                                                {
                                                                    prop.SetValue(newObject, value, null);
                                                                }
                                                                catch (Exception)
                                                                {
                                                                    prop.SetValue(newObject, value.ConvertValue(prop), null);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                try
                                                {
                                                    if (value != DBNull.Value)
                                                    {
                                                        accessor[newObject, name] = value;
                                                    }
                                                }
                                                catch (Exception e)
                                                {
                                                    TrySetValue(dataCommand, newObject, objectType, name, value);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            try
                                            {
                                                if (value != DBNull.Value)
                                                {
                                                    accessor[newObject, name] = value;
                                                }
                                            }
                                            catch (Exception e)
                                            {
                                                TrySetValue(dataCommand, newObject, objectType, name, value);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        var prop = objectType.GetProperty(name);
                                        if (prop != null)
                                        {
                                            if (value != DBNull.Value)
                                            {
                                                prop.SetValue(newObject, value, null);
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    result.AddError(LogType.Error, string.Format("{1} {0} ", name, dataCommand.TableName), ex);
                                }
                            }
                        }
                        items.Add(newObject);
                        rowsIndex++;
                    }
                }
                result.RecordsAffected = rowsIndex;
            }
            catch (Exception exception)
            {
                result.AddError(LogType.Error, $"{dataCommand.TableName} {dataCommand.SqlCommandText} {typeof(T).FullName}", exception);
            }
            ((ModelCommandResult <T>)result).Data = items;
            result.AddMessage(string.Format("{0} executed with {1} rows affected", dataCommand.SqlCommandText, result.RecordsAffected));
            //TODO change class to use base type


            dataCommand.OnCommandExecuted(new ModelCommandExecutedEventArgs <T> {
                Result = (ModelCommandResult <T>)result
            });

            dataCommand.ResetCommand();
            result.DataCommand = dataCommand;
            return(result);
        }
예제 #3
0
        protected override async Task <ICommandResult> ExecuteSelectCommandAsync(SqlModelCommand <T> dataCommand,
                                                                                 IDbCommand command)
        {
            if (TableMapFromDatabase)
            {
                dataCommand.GetTableMap();
            }

            dataCommand.BuildSqlCommand();
            dataCommand.BuildSqlParameters(command);
            command.CommandText = dataCommand.SqlCommandText;
            var            items  = new List <T>();
            ICommandResult result = null;

            try
            {
                int rowsIndex  = 0;
                var sqlCommand = command as SqlCommand;

                OnBeforeCommandExecute(this, new ModelCommandBeforeExecuteEventArgs(dataCommand, command, DataCommandType.Select));

                using (SqlDataReader r = await sqlCommand.ExecuteReaderAsync())
                {
                    Type objectType = typeof(T);

                    if (objectType == typeof(DataTable))
                    {
                        result = new DataTableCommandResult();
                        var dt = new DataTable(dataCommand.TableName);
                        dt.Load(r);
                        ((DataTableCommandResult)result).Data = dt;
                        result.RecordsAffected = dt.Rows.Count;

                        return(result);
                    }
                    result = new ModelCommandResult <T>();

                    var tablename = dataCommand.GetTableAttribute();
                    while (await r.ReadAsync())
                    {
                        bool userDataManager = false;
                        var  newObject       = (T)Activator.CreateInstance(objectType);
                        var  dataManager     = newObject as IObjectDataManager;

                        if (dataManager != null)
                        {
                            userDataManager = true;
                        }

                        if (dataCommand.TableMap != null)
                        {
                            if (dataCommand.TableName != objectType.Name)
                            {
                                if (tablename == dataCommand.TableName)
                                {
                                    if (dataManager != null)
                                    {
                                        userDataManager = true;
                                    }
                                    else
                                    {
                                        userDataManager = false;
                                    }
                                }
                            }
                        }

                        if (userDataManager)
                        {
                            dataManager.SetData(r);
                        }
                        else
                        {
                            //TODO Change code to use Reflection.Emit
                            int counter = r.FieldCount;
                            for (int i = 0; i < counter; i++)
                            {
                                var name = r.GetName(i);
                                try
                                {
                                    var fieldType = r.GetFieldType(i);
                                    var value     = r.GetValue(i);
                                    if (dataCommand.TableMap != null)
                                    {
                                        var column =
                                            dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == name);

                                        if (column != null)
                                        {
                                            if (!string.IsNullOrEmpty(column.PropertyName))
                                            {
                                                var prop = objectType.GetProperty(column.PropertyName);
                                                if (prop != null)
                                                {
                                                    if (value != DBNull.Value)
                                                    {
                                                        prop.SetValue(newObject, value, null);
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                TrySetValue(dataCommand, newObject, objectType, name, value);
                                            }
                                        }
                                        else
                                        {
                                            TrySetValue(dataCommand, newObject, objectType, name, value);
                                        }
                                    }
                                    else
                                    {
                                        var prop = objectType.GetProperty(name);
                                        if (prop != null)
                                        {
                                            if (value != DBNull.Value)
                                            {
                                                prop.SetValue(newObject, value, null);
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    result.AddError(LogType.Error,
                                                    string.Format("{1} {0} ", name, dataCommand.TableName), ex);
                                }
                            }
                        }
                        items.Add(newObject);
                        rowsIndex++;
                    }
                }
                result.RecordsAffected = rowsIndex;
            }
            catch (Exception exception)
            {
                result.AddError(LogType.Error, dataCommand.TableName + " " + typeof(T).FullName, exception);
            }

            ((ModelCommandResult <T>)result).Data = items;
            result.AddMessage(string.Format("{0} executed with {1} rows affected", dataCommand.SqlCommandText,
                                            result.RecordsAffected));
            //TODO change class to use base type
            dataCommand.OnCommandExecuted(new ModelCommandExecutedEventArgs <T> {
                Result = (ModelCommandResult <T>)result
            });
            dataCommand.ResetCommand();
            result.DataCommand = dataCommand;
            return(result);
        }
예제 #4
0
        protected override ICommandResult ExecuteInsertCommand(SqlModelCommand <T> dataCommand, IDbCommand command)
        {
            var result = new ModelCommandResult <T>();
            var item   = dataCommand.Model as IModelBase;

            if (item != null)
            {
                if (item.Errors != null)
                {
                    if (item.HasErrors())
                    {
                        result.AddError(LogType.Error, "Model has validation error");
                        return(result);
                    }
                }
            }
            if (TableMapFromDatabase)
            {
                dataCommand.GetTableMap();
            }


            var  select      = string.Empty;
            bool identity    = false;
            var  retunColums = new Dictionary <string, string>();

            dataCommand.AddChanges();
            foreach (var key in dataCommand.PrimaryKeys)
            {
                var column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.PropertyName == key);

                if (column == null)
                {
                    column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == key);
                }

                if (column != null)
                {
                    if (column.IsIdentity)
                    {
                        select  += string.Format(" {0},", column.ColumnName);
                        identity = true;
                        retunColums.Add(column.ColumnName, column.PropertyName);
                        if (dataCommand.Changes.Contains(column.PropertyName))
                        {
                            dataCommand.Changes.Remove(column.PropertyName);
                        }
                    }
                }
            }

            var guidIdColumns =
                dataCommand.TableMap.ColumnMaps.Where(map => !string.IsNullOrEmpty(map.Default))
                .Where(
                    map =>
                    map.Default.ToUpper().Contains("NEWSEQUENTIALID") ||
                    map.Default.ToUpper().ToUpper().Contains("NEWID"))
                .ToList();

            foreach (var guidIdColumn in guidIdColumns)
            {
                select += string.Format(" {0},", guidIdColumn.ColumnName);
                retunColums.Add(guidIdColumn.ColumnName, guidIdColumn.PropertyName);
            }

            if (identity)
            {
                dataCommand.SetWhereText(string.Format(
                                             " SELECT SCOPE_IDENTITY() as [{0}]", retunColums.FirstOrDefault().Key
                                             ));
            }


            foreach (var change in dataCommand.Changes)
            {
                var column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.PropertyName == change);
                if (column != null)
                {
                    dataCommand.Value(column.ColumnName, dataCommand.GetValue(change));
                }
            }

            dataCommand.BuildSqlParameters(command);
            dataCommand.BuildSqlCommand();
            command.CommandText = dataCommand.SqlCommandText;

            OnBeforeCommandExecute(this, new ModelCommandBeforeExecuteEventArgs(dataCommand, command, DataCommandType.Insert));


            using (var dataReader = command.ExecuteReader())
            {
                result.RecordsAffected = dataReader.RecordsAffected;
                if (dataReader.RecordsAffected == 0)
                {
                    result.AddError(LogType.Information, "No rows affected");
                }
                else
                {
                    dataCommand.SetWhereText(string.Empty);
                    dataCommand.CommandType = DataCommandType.Update;
                }
                while (dataReader.Read())
                {
                    for (int i = 0; i < 1; ++i)
                    {
                        var name     = dataReader.GetName(i);
                        var property = retunColums[name];
                        dataCommand.SetValue(property, dataReader.GetValue(i).ToInt());
                    }
                }
            }
            //TODO error when transaction is full
            result.AddMessage(string.Format("{0} executed with {1} rows affected", dataCommand.SqlCommandText,
                                            result.RecordsAffected));
            dataCommand.ResetCommand();
            result.DataCommand = dataCommand;
            return(result);
        }
예제 #5
0
        protected override ICommandResult ExecuteUpdateCommand(SqlModelCommand <T> dataCommand, IDbCommand command)
        {
            var result = new ModelCommandResult <T>();
            var item   = dataCommand.Model as IModelBase;

            //TODO beforeExectute
            if (item != null)
            {
                if (item.Error == null)
                {
                    if (item.HasErrors())
                    {
                        result.AddError(LogType.Error, "Model has validation error");
                        return(result);
                    }
                }
            }
            if (TableMapFromDatabase)
            {
                dataCommand.GetTableMap();
            }


            if (dataCommand.TableMap.TableType == "VIEW")
            {
                if (item.Configuration == null)
                {
                    result.AddMessage(string.Format("The command is type of View and has no merge configuration"));
                    return(result);
                }
            }
            else
            {
                if (dataCommand.Track == false)
                {
                    dataCommand.AddChanges();
                }
                dataCommand.BuildKeys();
                foreach (var change in dataCommand.Changes)
                {
                    if (dataCommand.TableMap != null)
                    {
                        var column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.PropertyName == change);

                        if (column == null)
                        {
                            column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == change);
                        }

                        if (column?.IsIdentity == false)
                        {
                            dataCommand.Value(column.ColumnName, dataCommand.GetValue(change));
                        }
                    }
                    else
                    {
                        dataCommand.Value(change, dataCommand.GetValue(change));
                    }
                }

                OnBeforeCommandExecute(this, new ModelCommandBeforeExecuteEventArgs(dataCommand, command, DataCommandType.Update));

                if (dataCommand.Columns.Count > 0 && dataCommand.Changes.Count > 0)
                {
                    dataCommand.BuildSqlParameters(command);
                    dataCommand.BuildSqlCommand();
                    command.CommandText = dataCommand.SqlCommandText;



                    if (command.CommandText.Contains("WHERE"))
                    {
                        int resultIndex = command.ExecuteNonQuery();
                        result.RecordsAffected = resultIndex;
                        if (resultIndex == 0)
                        {
                            result.AddError(LogType.Information, "No rows affected");
                        }
                        else
                        {
                            dataCommand.ResetCommand();
                        }
                    }
                    else
                    {
                        result.AddError(LogType.Information, "No where in update");
                    }
                    result.AddMessage(string.Format("{0} executed with {1} rows affected", command.CommandText,
                                                    result.RecordsAffected));
                }
                result.DataCommand = dataCommand;
            }
            return(result);
        }
예제 #6
0
        static void Main(string[] args)
        {
            /*
             *
             */
            CommandLine options = new CommandLine();

            if (options.Parse(args) == false)
            {
                Environment.Exit(1001);
                return;
            }

            if (options.Help == true)
            {
                options.HelpShow();
                Environment.Exit(1002);
                return;
            }

            _options = options;


            /*
             *
             */
            string[] files = Yttrium.Glob.Do(options.FilePatterns.ToArray());

            if (files == null || files.Length == 0)
            {
                Console.WriteLine("error: no matching files.");
                Environment.Exit(2);
            }


            /*
             *
             */
            Console.WriteLine("~ mode: '{0}'", _options.Mode);


            /*
             *
             */
            Microsoft.Office.Interop.Visio.Application visio = null;
            bool anyError = false;

            try
            {
                /*
                 *
                 */
                ModelExporter exporter = new ModelExporter();
                exporter.PageStart += new EventHandler <PageEventArgs>(OnPageStart);
                exporter.PageEnd   += new EventHandler <PageEventArgs>(OnPageEnd);
                exporter.StepStart += new EventHandler <PageStepEventArgs>(OnStepStart);
                exporter.StepEnd   += new EventHandler <PageStepEventArgs>(OnStepEnd);

                /*
                 *
                 */
                visio = new Microsoft.Office.Interop.Visio.Application();
                visio.AlertResponse = 1;
                visio.Visible       = false;

                foreach (string file in files)
                {
                    /*
                     *
                     */
                    Console.Write("+ opening '{0}'...", Path2.RelativePath(file));
                    FileInfo fileInfo = new FileInfo(file);

                    if (fileInfo.Exists == false)
                    {
                        ConsoleFail();
                        Console.WriteLine(" - file does not exist");

                        anyError = true;
                        continue;
                    }


                    /*
                     * Open the document: if the document is not a valid/compatible Visio
                     * document, this will fail.
                     */
                    Microsoft.Office.Interop.Visio.Document document;

                    try
                    {
                        document = visio.Documents.Open(fileInfo.FullName);
                        ConsoleOk();
                    }
                    catch (Exception ex)
                    {
                        ConsoleFail();

                        if (options.Verbose == true)
                        {
                            ConsoleDump(ex);
                        }

                        anyError = true;
                        continue;
                    }


                    /*
                     * Settings
                     */
                    ModelExportSettings exportSettings = new ModelExportSettings();
                    exportSettings.Program = "ModelExport";
                    exportSettings.Mode    = options.Mode;
                    exportSettings.Path    = options.OutputDirectory ?? fileInfo.DirectoryName;

                    exporter.Settings = exportSettings;


                    /*
                     * Export.
                     */
                    ModelCommandResult result = null;

                    ModelCommand command = new ModelCommand();
                    command.Document  = document;
                    command.Operation = ModelOperation.ExportAll;

                    if (options.ValidateOnly == true)
                    {
                        command.Operation = ModelOperation.ValidateAll;
                    }


                    try
                    {
                        result = exporter.Execute(command);
                    }
                    catch (Exception ex)
                    {
                        anyError = true;

                        if (options.Verbose == true)
                        {
                            ConsoleDump(ex);
                        }
                    }
                    finally
                    {
                        document.Close();
                    }

                    if (result == null)
                    {
                        continue;
                    }


                    /*
                     *
                     */
                    Console.WriteLine("");
                    Console.WriteLine("execution summary");
                    Console.WriteLine("-------------------------------------------------------------------------");

                    foreach (ModelCommandPageResult pageResult in result.Pages)
                    {
                        Console.Write(pageResult.Name);

                        if (pageResult.Success == true)
                        {
                            ConsoleOk();
                        }
                        else
                        {
                            ConsoleFail();
                        }

                        foreach (ModelResultItem item in pageResult.Items)
                        {
                            string marker;

                            switch (item.ItemType)
                            {
                            case ModelResultItemType.Error:
                                Console.ForegroundColor = ConsoleColor.DarkRed;
                                marker = "!";
                                break;

                            case ModelResultItemType.Warning:
                                Console.ForegroundColor = ConsoleColor.DarkYellow;
                                marker = "W";
                                break;

                            default:
                                marker = " ";
                                break;
                            }

                            if (item.VisioShapeId == null)
                            {
                                Console.WriteLine("{0} [page] {1}#{2}: {3}", marker, item.Actor, item.Code, item.Description);
                            }
                            else
                            {
                                Console.WriteLine("{0} [{1}] {2}#{3}: {4}", marker, item.VisioShapeId, item.Actor, item.Code, item.Description);
                            }

                            Console.ResetColor();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ConsoleDump(ex);
            }
            finally
            {
                // This _needs_ to be performed here: in case an exception is caught,
                // make sure that Visio is closed or otherwise a zombie process will
                // be left running on the machine.
                if (visio != null)
                {
                    visio.Quit();
                }
            }


            /*
             *
             */
            if (anyError == true)
            {
                Environment.Exit(3);
            }
            else
            {
                Environment.Exit(0);
            }
        }