Пример #1
0
        private void SaveTableInfo(string tableName)
        {
            if (tableName.IsEmptyOrNull())
            {
                return;
            }

            var cnn      = this.ConnectionsCombo.SelectedItem as GeneratorConfig.Connection;
            var tableObj = cnn != null?cnn.Tables.FirstOrDefault(x => x.Tablename == tableName) : null;

            if (tableObj == null && cnn != null)
            {
                tableObj           = new GeneratorConfig.Table();
                tableObj.Tablename = tableName;
                cnn.Tables.Add(tableObj);
            }

            if (tableObj != null)
            {
                tableObj.Identifier    = EntitySingular;
                tableObj.PermissionKey = Permission;
                tableObj.Module        = Module;
                tableObj.ConnectionKey = ConnectionKey;
            }

            config.Save();
        }
Пример #2
0
        private void ConnectionsCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this._tables.Clear();
            GenerateCodeButton.IsEnabled = false;

            if (this.ConnectionsCombo.SelectedItem != null)
            {
                var conn = (GeneratorConfig.Connection) this.ConnectionsCombo.SelectedItem;

                try
                {
                    using (var connection = SqlConnections.New(conn.ConnectionString, conn.ProviderName))
                    {
                        connection.Open();

                        var schemaProvider = SchemaHelper.GetSchemaProvider(connection.GetDialect().ServerType);
                        foreach (var t in schemaProvider.GetTableNames(connection))
                        {
                            var table = conn != null?conn.Tables.FirstOrDefault(x => x.Tablename == t.Tablename) : null;

                            var identifier = (table == null || table.Identifier.IsEmptyOrNull()) ?
                                             RowGenerator.ClassNameFromTableName(t.Table) : table.Identifier;
                            var permission    = table == null ? "Administration:General" : table.PermissionKey;
                            var connectionKey = (table != null && !table.ConnectionKey.IsEmptyOrNull()) ?
                                                table.ConnectionKey : conn.Key;

                            var module = (table != null && table.Module != null) ? table.Module :
                                         (Inflector.Inflector.Pascalize(connectionKey) ?? "").Replace(" ", "");

                            var tableItem = new TableItem
                            {
                                IsChecked     = false,
                                ConnectionKey = conn.Key,
                                Module        = module,
                                Identifier    = identifier,
                                PermissionKey = permission,
                                FullName      = t.Tablename
                            };

                            _tables.Add(tableItem);
                            tableItem.PropertyChanged += (s, e2) =>
                            {
                                var t2 = conn.Tables.FirstOrDefault(x => x.Tablename == tableItem.FullName);
                                if (t2 == null)
                                {
                                    t2           = new GeneratorConfig.Table();
                                    t2.Tablename = tableItem.FullName;
                                    conn.Tables.Add(t2);
                                }
                                t2.Identifier    = tableItem.Identifier;
                                t2.Module        = tableItem.Module;
                                t2.ConnectionKey = tableItem.ConnectionKey;
                                t2.PermissionKey = tableItem.PermissionKey;
                                this.config.Save();

                                GenerateCodeButton.IsEnabled = _tables.Any(x => x.IsChecked);
                            };
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
Пример #3
0
        private void GenerateCodes_Click(object sender, RoutedEventArgs e)
        {
            if (this.ConnectionsCombo.SelectedItem == null ||
                this.TablesCombo.SelectedItem == null)
            {
                MessageBox.Show("A connection string and table name must be selected!");
                return;
            }

            if (EntitySingular.IsTrimmedEmpty())
            {
                MessageBox.Show("Entity class identifier must be entered!");
                return;
            }

            if (Permission.IsTrimmedEmpty())
            {
                MessageBox.Show("Permission key must be entered!");
                return;
            }

            string tableName = (string)this.TablesCombo.SelectedItem;

            try
            {
                EntityCodeGenerationModel rowModel;
                var conn = (GeneratorConfig.Connection) this.ConnectionsCombo.SelectedItem;
                using (var connection = SqlConnections.New(conn.ConnectionString, conn.ProviderName))
                {
                    connection.Open();
                    var    table       = (string)this.TablesCombo.SelectedItem;
                    string tableSchema = null;
                    if (table.IndexOf('.') > 0)
                    {
                        tableSchema = table.Substring(0, table.IndexOf('.'));
                        table       = table.Substring(table.IndexOf('.') + 1);
                    }
                    rowModel = RowGenerator.GenerateModel(connection, tableSchema, table,
                                                          Module, ConnectionKey, EntitySingular, Permission, config);
                    new EntityCodeGenerator(rowModel, config).Run();

                    MessageBox.Show("Code files for the selected table is generated!");

                    GenerateCodeButton.IsEnabled = false;
                }

                var cnn      = this.ConnectionsCombo.SelectedItem as GeneratorConfig.Connection;
                var tableObj = cnn != null?cnn.Tables.FirstOrDefault(x => x.Tablename == tableName) : null;

                if (tableObj == null && cnn != null)
                {
                    tableObj           = new GeneratorConfig.Table();
                    tableObj.Tablename = tableName;
                    cnn.Tables.Add(tableObj);
                }

                if (tableObj != null)
                {
                    tableObj.Identifier    = EntitySingular;
                    tableObj.PermissionKey = Permission;
                    tableObj.Module        = Module;
                    tableObj.ConnectionKey = ConnectionKey;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            File.WriteAllText(GetConfigurationFilePath(), JSON.StringifyIndented(config));
        }
Пример #4
0
        public void Run(string projectJson, string[] args)
        {
            var projectDir = Path.GetDirectoryName(projectJson);

            var outFile       = args.FirstOrDefault(x => x.StartsWith("-o:"))?.Substring(3).TrimToNull();
            var connectionKey = args.FirstOrDefault(x => x.StartsWith("-c:"))?.Substring(3).TrimToNull();
            var table         = args.FirstOrDefault(x => x.StartsWith("-t:"))?.Substring(3).TrimToNull();
            var what          = args.FirstOrDefault(x => x.StartsWith("-w:"))?.Substring(3).TrimToNull();
            var module        = args.FirstOrDefault(x => x.StartsWith("-m:"))?.Substring(3).TrimToNull();
            var identifier    = args.FirstOrDefault(x => x.StartsWith("-i:"))?.Substring(3).TrimToNull();
            var permissionKey = args.FirstOrDefault(x => x.StartsWith("-p:"))?.Substring(3).TrimToNull();

            if (identifier != null)
            {
                CodeFileHelper.Overwrite = true;
            }

            var config         = GeneratorConfig.LoadFromFile(Path.Combine(projectDir, "sergen.json"));
            var connectionKeys = config.Connections
                                 .Where(x => !x.ConnectionString.IsEmptyOrNull())
                                 .Select(x => x.Key).ToList();

            var appSettingsFile = Path.Combine(projectDir, "appsettings.json");
            AppSettingsFormat appSettings;

            if (File.Exists(appSettingsFile))
            {
                appSettings = JSON.ParseTolerant <AppSettingsFormat>(File.ReadAllText(appSettingsFile).TrimToNull() ?? "{}");
            }
            else
            {
                appSettings = new AppSettingsFormat();
            }

            connectionKeys.AddRange(appSettings.Data.Keys);

            var appSettingsFile2 = Path.Combine(projectDir, "appsettings.machine.json");

            if (File.Exists(appSettingsFile2))
            {
                var appSettings2 = JSON.ParseTolerant <AppSettingsFormat>(File.ReadAllText(appSettingsFile2).TrimToNull() ?? "{}");
                foreach (var pair in appSettings2.Data)
                {
                    appSettings.Data[pair.Key] = pair.Value;
                }
            }

            connectionKeys.AddRange(appSettings.Data.Keys);

            connectionKeys = connectionKeys.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(x => x).ToList();

            if (connectionKeys.Count == 0)
            {
                Console.Error.WriteLine("No connections in appsettings.json or sergen.json!");
                Environment.Exit(1);
            }

            if (outFile == null && connectionKey == null)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("=== Table Code Generation ===");
                Console.WriteLine("");
                Console.ResetColor();

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Available Connections:");
                Console.ResetColor();
                foreach (var x in connectionKeys)
                {
                    Console.WriteLine(x);
                }
                Console.ResetColor();
                Console.WriteLine();
            }
            else if (connectionKey == null)
            {
                File.WriteAllText(outFile, JSON.Stringify(connectionKeys));
                Environment.Exit(0);
            }

            string userInput = null;

            if (outFile == null && connectionKey == null)
            {
                userInput = connectionKeys.Count == 1 ? connectionKeys[0] : null;
                while (connectionKey == null ||
                       !connectionKeys.Contains(connectionKey, StringComparer.OrdinalIgnoreCase))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Connection: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    connectionKey           = Hinter.ReadHintedLine(connectionKeys, userInput: userInput);
                    userInput = connectionKey;

                    if (connectionKey == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            userInput     = connectionKey;
            connectionKey = connectionKeys.Find(x => string.Compare(x, userInput, StringComparison.OrdinalIgnoreCase) == 0);
            if (connectionKey == null)
            {
                Console.Error.WriteLine("Can't find connection with key: " + userInput + "!");
                Environment.Exit(1);
            }

            if (outFile == null)
            {
                Console.ResetColor();
                Console.WriteLine();
            }

            var dataConnection = appSettings.Data.ContainsKey(connectionKey) ?
                                 appSettings.Data[connectionKey] : null;

            var confConnection = config.Connections.FirstOrDefault(x =>
                                                                   string.Compare(x.Key, connectionKey, StringComparison.OrdinalIgnoreCase) == 0);

            var connectionString = dataConnection != null?dataConnection.ConnectionString.TrimToNull() : null;

            if (connectionString == null && confConnection != null)
            {
                connectionString = confConnection.ConnectionString.TrimToNull();
            }

            var providerName = dataConnection != null?dataConnection.ProviderName.TrimToNull() : null;

            if (providerName == null && confConnection != null)
            {
                providerName = confConnection.ProviderName.TrimToNull();
            }
            providerName = providerName ?? "System.Data.SqlClient";

            DbProviderFactories.RegisterFactory("System.Data.SqlClient", SqlClientFactory.Instance);
            DbProviderFactories.RegisterFactory("Microsoft.Data.Sqlite", Microsoft.Data.Sqlite.SqliteFactory.Instance);
            DbProviderFactories.RegisterFactory("Npgsql", Npgsql.NpgsqlFactory.Instance);
            DbProviderFactories.RegisterFactory("FirebirdSql.Data.FirebirdClient", FirebirdSql.Data.FirebirdClient.FirebirdClientFactory.Instance);
            DbProviderFactories.RegisterFactory("MySql.Data.MySqlClient", MySql.Data.MySqlClient.MySqlClientFactory.Instance);

            if (connectionString.IndexOf("../../..") >= 0)
            {
                connectionString = connectionString.Replace("../../..", Path.GetDirectoryName(projectJson));
            }
            else if (connectionString.IndexOf(@"..\..\..\") >= 0)
            {
                connectionString = connectionString.Replace(@"..\..\..\", Path.GetDirectoryName(projectJson));
            }

            ISchemaProvider  schemaProvider;
            List <TableName> tableNames;

            using (var connection = SqlConnections.New(connectionString, providerName))
            {
                schemaProvider = SchemaHelper.GetSchemaProvider(connection.GetDialect().ServerType);
                tableNames     = schemaProvider.GetTableNames(connection).ToList();
            }

            var tables = tableNames.Select(x => x.Tablename).ToList();

            if (outFile == null && table == null)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Available Tables:");
                Console.ResetColor();

                foreach (var x in tables)
                {
                    Console.WriteLine(x);
                }
            }
            else if (table == null)
            {
                File.WriteAllText(outFile, JSON.Stringify(tableNames.Select(x =>
                {
                    var xct = confConnection == null ? null : confConnection.Tables.FirstOrDefault(z => string.Compare(z.Tablename, table, StringComparison.OrdinalIgnoreCase) == 0);
                    return(new
                    {
                        name = x.Tablename,
                        module = xct == null || xct.Module.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(connectionKey) : xct.Module,
                        permission = xct == null || xct.PermissionKey.IsTrimmedEmpty() ? "Administration:General" : xct.PermissionKey,
                        identifier = xct == null || xct.Identifier.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(x.Table) : xct.Identifier,
                    });
                })));

                Environment.Exit(0);
            }

            userInput = tables.Count == 1 ? tables[0] : null;
            if (userInput == null && schemaProvider.DefaultSchema != null &&
                tables.Any(x => x.StartsWith(schemaProvider.DefaultSchema + ".")))
            {
                userInput = schemaProvider.DefaultSchema + ".";
            }

            if (outFile == null)
            {
                Console.WriteLine();

                while (table == null ||
                       !tables.Contains(table, StringComparer.OrdinalIgnoreCase))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    table     = Hinter.ReadHintedLine(tables, userInput: userInput);
                    userInput = table;

                    if (table == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            userInput = table;
            var tableName = tableNames.First(x => string.Compare(x.Tablename, userInput, StringComparison.OrdinalIgnoreCase) == 0);

            if (tableName == null)
            {
                Console.Error.WriteLine("Can't find table with name: " + userInput + "!");
                Environment.Exit(1);
            }

            var confTable = confConnection == null ? null : confConnection.Tables.FirstOrDefault(x =>
                                                                                                 string.Compare(x.Tablename, table, StringComparison.OrdinalIgnoreCase) == 0);

            if (module == null)
            {
                userInput = confTable == null || confTable.Module.IsEmptyOrNull() ?
                            RowGenerator.ClassNameFromTableName(connectionKey) : confTable.Module;

                Console.WriteLine();

                while (module.IsTrimmedEmpty())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Module name for table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    module    = Hinter.ReadHintedLine(new string[0], userInput: userInput);
                    userInput = module;

                    if (module == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            if (identifier == null)
            {
                userInput = confTable == null || confTable.Identifier.IsEmptyOrNull() ?
                            RowGenerator.ClassNameFromTableName(tableName.Table) : confTable.Identifier;

                Console.WriteLine();

                while (identifier.IsTrimmedEmpty())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a class Identifier for table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    identifier = Hinter.ReadHintedLine(new string[0], userInput: userInput);
                    userInput  = identifier;

                    if (identifier == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            if (permissionKey == null)
            {
                userInput = confTable == null || confTable.PermissionKey.IsTrimmedEmpty() ?
                            "Administration:General" : confTable.PermissionKey;

                Console.WriteLine();

                while (permissionKey.IsTrimmedEmpty())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Permission Key for table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    permissionKey           = Hinter.ReadHintedLine(new string[0], userInput: userInput);
                    userInput = permissionKey;

                    if (permissionKey == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }


            if (what == null)
            {
                Console.WriteLine();

                userInput = "RSU";
                while (what.IsEmptyOrNull())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Choose What to Generate (R:Row, S:Repo+Svc, U=Cols+Form+Page+Grid+Dlg+Css)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    what      = Hinter.ReadHintedLine(new string[0], userInput: userInput);
                    userInput = what;

                    if (what == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            config.GenerateRow     = what.IndexOf("R", StringComparison.OrdinalIgnoreCase) >= 0;
            config.GenerateService = what.IndexOf("S", StringComparison.OrdinalIgnoreCase) >= 0;
            config.GenerateUI      = what.IndexOf("U", StringComparison.OrdinalIgnoreCase) >= 0;

            Console.ResetColor();
            Console.WriteLine();

            if (confConnection == null)
            {
                confConnection = new GeneratorConfig.Connection
                {
                    Key = connectionKey
                };
                config.Connections.Add(confConnection);
            }

            if (confTable == null)
            {
                confTable = new GeneratorConfig.Table
                {
                    Identifier    = identifier,
                    Module        = module,
                    PermissionKey = permissionKey,
                    Tablename     = tableName.Tablename
                };

                confConnection.Tables.Add(confTable);
            }
            else
            {
                confTable.Identifier    = identifier;
                confTable.Module        = module;
                confTable.PermissionKey = permissionKey;
            }

            File.WriteAllText(Path.Combine(projectDir, "sergen.json"), config.SaveToJson());

            using (var connection = SqlConnections.New(connectionString, providerName))
            {
                connection.Open();

                var rowModel = RowGenerator.GenerateModel(connection, tableName.Schema, tableName.Table,
                                                          module, connectionKey, identifier, permissionKey, config);

                new EntityCodeGenerator(rowModel, config, projectJson).Run();
            }
        }
Пример #5
0
        public void Run(string csproj, string[] args)
        {
            var projectDir = Path.GetDirectoryName(csproj);

            var outFile       = GetOption(args, "o").TrimToNull();
            var connectionKey = GetOption(args, "c").TrimToNull();
            var table         = GetOption(args, "t").TrimToNull();
            var what          = GetOption(args, "w").TrimToNull();
            var module        = GetOption(args, "m").TrimToNull();
            var identifier    = GetOption(args, "i").TrimToNull();
            var permissionKey = GetOption(args, "p").TrimToNull();

            if (identifier != null)
            {
                CodeFileHelper.Overwrite = true;
            }

            var config = GeneratorConfig.LoadFromFile(Path.Combine(projectDir, "sergen.json"));

            var connectionStringOptions = new ConnectionStringOptions();

            if (!string.IsNullOrEmpty(config.CustomTemplates))
            {
                Templates.TemplatePath = Path.Combine(projectDir, config.CustomTemplates);
            }

            foreach (var x in config.Connections.Where(x => !x.ConnectionString.IsEmptyOrNull()))
            {
                connectionStringOptions[x.Key] = new ConnectionStringEntry
                {
                    ConnectionString = x.ConnectionString,
                    ProviderName     = x.ProviderName,
                    Dialect          = x.Dialect
                };
            }

            foreach (var name in config.GetAppSettingsFiles())
            {
                var path = Path.Combine(projectDir, name);
                if (File.Exists(name))
                {
                    var appSettings = JSON.ParseTolerant <AppSettingsFormat>(File.ReadAllText(path).TrimToNull() ?? "{}");
                    if (appSettings.Data != null)
                    {
                        foreach (var data in appSettings.Data)
                        {
                            // not so nice fix for relative paths, e.g. sqlite etc.
                            if (data.Value.ConnectionString.Contains("../../..", StringComparison.Ordinal))
                            {
                                data.Value.ConnectionString = data.Value
                                                              .ConnectionString.Replace("../../..", Path.GetDirectoryName(csproj), StringComparison.Ordinal);
                            }
                            else if (data.Value.ConnectionString.Contains(@"..\..\..\", StringComparison.Ordinal))
                            {
                                data.Value.ConnectionString = data.Value.ConnectionString.Replace(@"..\..\..\",
                                                                                                  Path.GetDirectoryName(csproj), StringComparison.Ordinal);
                            }

                            connectionStringOptions[data.Key] = data.Value;
                        }
                    }
                }
            }

            if (connectionStringOptions.Count == 0)
            {
                Console.Error.WriteLine("No connections in appsettings files or sergen.json!");
                Environment.Exit(1);
            }

            var connectionKeys = connectionStringOptions.Keys.OrderBy(x => x).ToArray();

            if (outFile == null && connectionKey == null)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("=== Table Code Generation ===");
                Console.WriteLine("");
                Console.ResetColor();

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Available Connections:");
                Console.ResetColor();
                foreach (var x in connectionKeys)
                {
                    Console.WriteLine(x);
                }
                Console.ResetColor();
                Console.WriteLine();
            }
            else if (connectionKey == null)
            {
                File.WriteAllText(outFile, JSON.Stringify(connectionStringOptions.Keys.OrderBy(x => x)));
                Environment.Exit(0);
            }

            string userInput = null;

            if (outFile == null && connectionKey == null)
            {
                userInput = connectionKeys.Length == 1 ? connectionKeys[0] : null;
                while (connectionKey == null ||
                       !connectionKeys.Contains(connectionKey, StringComparer.OrdinalIgnoreCase))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Connection: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    connectionKey           = Hinter.ReadHintedLine(connectionKeys, userInput: userInput);
                    userInput = connectionKey;

                    if (connectionKey == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            userInput = connectionKey;
            if (!connectionStringOptions.ContainsKey(userInput))
            {
                Console.Error.WriteLine("Can't find connection with key: " + userInput + "!");
                Environment.Exit(1);
            }

            if (outFile == null)
            {
                Console.ResetColor();
                Console.WriteLine();
            }

            DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient",
                                                Microsoft.Data.SqlClient.SqlClientFactory.Instance);
            DbProviderFactories.RegisterFactory("System.Data.SqlClient",
                                                Microsoft.Data.SqlClient.SqlClientFactory.Instance);
            DbProviderFactories.RegisterFactory("Microsoft.Data.Sqlite",
                                                Microsoft.Data.Sqlite.SqliteFactory.Instance);
            DbProviderFactories.RegisterFactory("Npgsql",
                                                Npgsql.NpgsqlFactory.Instance);
            DbProviderFactories.RegisterFactory("FirebirdSql.Data.FirebirdClient",
                                                FirebirdSql.Data.FirebirdClient.FirebirdClientFactory.Instance);
            DbProviderFactories.RegisterFactory("MySql.Data.MySqlClient",
                                                MySqlConnector.MySqlConnectorFactory.Instance);

            var sqlConnections = new DefaultSqlConnections(
                new DefaultConnectionStrings(connectionStringOptions));

            ISchemaProvider  schemaProvider;
            List <TableName> tableNames;

            using (var connection = sqlConnections.NewByKey(connectionKey))
            {
                schemaProvider = SchemaHelper.GetSchemaProvider(connection.GetDialect().ServerType);
                tableNames     = schemaProvider.GetTableNames(connection).ToList();
            }

            var tables         = tableNames.Select(x => x.Tablename).ToList();
            var confConnection = config.Connections.FirstOrDefault(x =>
                                                                   string.Compare(x.Key, connectionKey, StringComparison.OrdinalIgnoreCase) == 0);

            if (outFile == null && table == null)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Available Tables:");
                Console.ResetColor();

                foreach (var x in tables)
                {
                    Console.WriteLine(x);
                }
            }
            else if (table == null)
            {
                File.WriteAllText(outFile, JSON.Stringify(tableNames.Select(x =>
                {
                    var xct = confConnection == null ? null : confConnection.Tables.FirstOrDefault(z => string.Compare(z.Tablename, table, StringComparison.OrdinalIgnoreCase) == 0);
                    return(new
                    {
                        name = x.Tablename,
                        module = xct == null || xct.Module.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(connectionKey) : xct.Module,
                        permission = xct == null || xct.PermissionKey.IsTrimmedEmpty() ? "Administration:General" : xct.PermissionKey,
                        identifier = xct == null || xct.Identifier.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(x.Table) : xct.Identifier,
                    });
                })));

                Environment.Exit(0);
            }

            userInput = tables.Count == 1 ? tables[0] : null;
            if (userInput == null && schemaProvider.DefaultSchema != null &&
                tables.Any(x => x.StartsWith(schemaProvider.DefaultSchema + ".", StringComparison.Ordinal)))
            {
                userInput = schemaProvider.DefaultSchema + ".";
            }

            if (outFile == null)
            {
                Console.WriteLine();

                while (table == null ||
                       !tables.Contains(table, StringComparer.OrdinalIgnoreCase))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    table     = Hinter.ReadHintedLine(tables, userInput: userInput);
                    userInput = table;

                    if (table == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            userInput = table;
            var tableName = tableNames.First(x => string.Compare(x.Tablename, userInput, StringComparison.OrdinalIgnoreCase) == 0);

            if (tableName == null)
            {
                Console.Error.WriteLine("Can't find table with name: " + userInput + "!");
                Environment.Exit(1);
            }

            var confTable = confConnection == null ? null : confConnection.Tables.FirstOrDefault(x =>
                                                                                                 string.Compare(x.Tablename, table, StringComparison.OrdinalIgnoreCase) == 0);

            if (module == null)
            {
                userInput = confTable == null || confTable.Module.IsEmptyOrNull() ?
                            RowGenerator.ClassNameFromTableName(connectionKey) : confTable.Module;

                Console.WriteLine();

                while (module.IsTrimmedEmpty())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Module name for table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    module    = Hinter.ReadHintedLine(Array.Empty <string>(), userInput: userInput);
                    userInput = module;

                    if (module == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            if (identifier == null)
            {
                userInput = confTable == null || confTable.Identifier.IsEmptyOrNull() ?
                            RowGenerator.ClassNameFromTableName(tableName.Table) : confTable.Identifier;

                Console.WriteLine();

                while (identifier.IsTrimmedEmpty())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a class Identifier for table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    identifier = Hinter.ReadHintedLine(Array.Empty <string>(), userInput: userInput);
                    userInput  = identifier;

                    if (identifier == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            if (permissionKey == null)
            {
                userInput = confTable == null || confTable.PermissionKey.IsTrimmedEmpty() ?
                            "Administration:General" : confTable.PermissionKey;

                Console.WriteLine();

                while (permissionKey.IsTrimmedEmpty())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Permission Key for table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    permissionKey           = Hinter.ReadHintedLine(Array.Empty <string>(), userInput: userInput);
                    userInput = permissionKey;

                    if (permissionKey == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }


            if (what == null)
            {
                Console.WriteLine();

                userInput = "RSUC";
                while (what.IsEmptyOrNull())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Choose What to Generate (R:Row, S:Repo+Svc, U=UI, C=Custom)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    what      = Hinter.ReadHintedLine(Array.Empty <string>(), userInput: userInput);
                    userInput = what;

                    if (what == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            config.GenerateRow     = what.IndexOf("R", StringComparison.OrdinalIgnoreCase) >= 0;
            config.GenerateService = what.IndexOf("S", StringComparison.OrdinalIgnoreCase) >= 0;
            config.GenerateUI      = what.IndexOf("U", StringComparison.OrdinalIgnoreCase) >= 0;
            config.GenerateCustom  = what.IndexOf("C", StringComparison.OrdinalIgnoreCase) >= 0;

            Console.ResetColor();
            Console.WriteLine();

            if (confConnection == null)
            {
                confConnection = new GeneratorConfig.Connection
                {
                    Key = connectionKey
                };
                config.Connections.Add(confConnection);
            }

            if (confTable == null)
            {
                confTable = new GeneratorConfig.Table
                {
                    Identifier    = identifier,
                    Module        = module,
                    PermissionKey = permissionKey,
                    Tablename     = tableName.Tablename
                };

                confConnection.Tables.Add(confTable);
            }
            else
            {
                confTable.Identifier    = identifier;
                confTable.Module        = module;
                confTable.PermissionKey = permissionKey;
            }

            File.WriteAllText(Path.Combine(projectDir, "sergen.json"), config.SaveToJson());

            using (var connection = sqlConnections.NewByKey(connectionKey))
            {
                connection.Open();

                var csprojContent = File.ReadAllText(csproj);
                var net5Plus      = !new Regex(@"\<TargetFramework\>.*netcoreapp.*\<\/TargetFramework\>", RegexOptions.Multiline | RegexOptions.Compiled)
                                    .IsMatch(csprojContent);

                var rowModel = RowGenerator.GenerateModel(connection, tableName.Schema, tableName.Table,
                                                          module, connectionKey, identifier, permissionKey, config, net5Plus);

                rowModel.AspNetCore = true;
                rowModel.NET5Plus   = net5Plus;

                var kdiff3Paths = new[]
                {
                    config.KDiff3Path
                };

                CodeFileHelper.Kdiff3Path = kdiff3Paths.FirstOrDefault(File.Exists);
                CodeFileHelper.TSCPath    = config.TSCPath ?? "tsc";

                new EntityCodeGenerator(rowModel, config, csproj).Run();
            }
        }
Пример #6
0
        private void ConnectionsCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this._tables.Clear();
            GenerateCodeButton.IsEnabled = false;

            if (this.ConnectionsCombo.SelectedItem != null)
            {
                var conn = (GeneratorConfig.Connection) this.ConnectionsCombo.SelectedItem;

                try
                {
                    using (var connection = SqlConnections.New(conn.ConnectionString, conn.ProviderName))
                    {
                        connection.Open();

                        var schemaProvider = SchemaHelper.GetSchemaProvider(connection.GetDialect().ServerType);
                        //foreach (var t in schemaProvider.GetTableNames(connection))
                        List <Data.Schema.TableName> excluiTabelas = new List <Data.Schema.TableName>();
                        excluiTabelas.Add(new Data.Schema.TableName()
                        {
                            Table = "EXCEPTIONS"
                        });
                        excluiTabelas.Add(new Data.Schema.TableName()
                        {
                            Table = "LANGUAGES"
                        });
                        excluiTabelas.Add(new Data.Schema.TableName()
                        {
                            Table = "ROLEPERMISSIONS"
                        });
                        excluiTabelas.Add(new Data.Schema.TableName()
                        {
                            Table = "ROLES"
                        });
                        excluiTabelas.Add(new Data.Schema.TableName()
                        {
                            Table = "USERPERMISSIONS"
                        });
                        excluiTabelas.Add(new Data.Schema.TableName()
                        {
                            Table = "USERPREFERENCES"
                        });
                        excluiTabelas.Add(new Data.Schema.TableName()
                        {
                            Table = "USERROLES"
                        });
                        excluiTabelas.Add(new Data.Schema.TableName()
                        {
                            Table = "USERS"
                        });
                        excluiTabelas.Add(new Data.Schema.TableName()
                        {
                            Table = "VERSIONINFO"
                        });

                        //foreach (var t in schemaProvider.GetTableNames(connection).Where(x => x.Table != "Exceptions"))
                        foreach (var t in schemaProvider.GetTableNames(connection).Where(x => !excluiTabelas.Any(t => t.Table == x.Table.ToUpper())))
                        {
                            //INICIO - ROLEMBERG FILHO - NÃO MOSTRA AS TABELAS PADRÃO DO SERENITY !!!
                            //switch (t.Table.ToUpper())
                            //{
                            //    case "EXCEPTIONS":
                            //    case "LANGUAGES":
                            //    case "ROLEPERMISSIONS":
                            //    case "ROLES":
                            //    case "USERPERMISSIONS":
                            //    case "USERPREFERENCES":
                            //    case "USERROLES":
                            //    case "USERS":
                            //    case "VERSIONINFO":
                            //        // TABELAS PADRÃO DO SERENITY. NÃO MOSTRA NO SERGEN!!!!
                            //        continue;
                            //    default:
                            //        break;
                            //}
                            //FIM - ROLEMBERG FILHO - NÃO MOSTRA AS TABELAS PADRÃO DO SERENITY !!!



                            var table = conn != null?conn.Tables.FirstOrDefault(x => x.Tablename == t.Tablename) : null;

                            var identifier = (table == null || table.Identifier.IsEmptyOrNull()) ?
                                             RowGenerator.ClassNameFromTableName(t.Table) : table.Identifier;
                            var permission    = table == null ? "Administration:General" : table.PermissionKey;
                            var connectionKey = (table != null && !table.ConnectionKey.IsEmptyOrNull()) ?
                                                table.ConnectionKey : conn.Key;

                            var module = (table != null && table.Module != null) ? table.Module :
                                         (Inflector.Inflector.Pascalize(connectionKey) ?? "").Replace(" ", "");

                            var tableItem = new TableItem
                            {
                                IsChecked     = false,
                                ConnectionKey = conn.Key,
                                Module        = module,
                                Identifier    = identifier,
                                PermissionKey = permission,
                                FullName      = t.Tablename
                            };

                            _tables.Add(tableItem);
                            tableItem.PropertyChanged += (s, e2) =>
                            {
                                var t2 = conn.Tables.FirstOrDefault(x => x.Tablename == tableItem.FullName);
                                if (t2 == null)
                                {
                                    t2           = new GeneratorConfig.Table();
                                    t2.Tablename = tableItem.FullName;
                                    conn.Tables.Add(t2);
                                }
                                t2.Identifier    = tableItem.Identifier;
                                t2.Module        = tableItem.Module;
                                t2.ConnectionKey = tableItem.ConnectionKey;
                                t2.PermissionKey = tableItem.PermissionKey;
                                this.config.Save();

                                GenerateCodeButton.IsEnabled = _tables.Any(x => x.IsChecked);
                            };
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
Пример #7
0
        private void GenerateCodes_Click(object sender, RoutedEventArgs e)
        {
            if (this.ConnectionsCombo.SelectedItem == null ||
                this.TablesCombo.SelectedItem == null)
            {
                MessageBox.Show("A connection string and table name must be selected!");
                return;
            }

            if (EntitySingular.IsTrimmedEmpty())
            {
                MessageBox.Show("Entity class identifier must be entered!");
                return;
            }

            if (Permission.IsTrimmedEmpty())
            {
                MessageBox.Show("Permission key must be entered!");
                return;
            }

            string tableName = (string)this.TablesCombo.SelectedItem;
            try
            {
                EntityCodeGenerationModel rowModel;
                var conn = (GeneratorConfig.Connection)this.ConnectionsCombo.SelectedItem;
                using (var connection = SqlConnections.New(conn.ConnectionString, conn.ProviderName))
                {
                    connection.Open();
                    var table = (string)this.TablesCombo.SelectedItem;
                    string tableSchema = null;
                    if (table.IndexOf('.') > 0)
                    {
                        tableSchema = table.Substring(0, table.IndexOf('.'));
                        table = table.Substring(table.IndexOf('.') + 1);
                    }
                    rowModel = RowGenerator.GenerateModel(connection, tableSchema, table,
                        Module, ConnectionKey, EntitySingular, Permission, config);
                    new EntityCodeGenerator(rowModel, config).Run();

                    MessageBox.Show("Code files for the selected table is generated!");

                    GenerateCodeButton.IsEnabled = false;
                }

                var cnn = this.ConnectionsCombo.SelectedItem as GeneratorConfig.Connection;
                var tableObj = cnn != null ? cnn.Tables.FirstOrDefault(x => x.Tablename == tableName) : null;
                if (tableObj == null && cnn != null)
                {
                    tableObj = new GeneratorConfig.Table();
                    tableObj.Tablename = tableName;
                    cnn.Tables.Add(tableObj);
                }

                if (tableObj != null)
                {
                    tableObj.Identifier = EntitySingular;
                    tableObj.PermissionKey = Permission;
                    tableObj.Module = Module;
                    tableObj.ConnectionKey = ConnectionKey;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            File.WriteAllText(GetConfigurationFilePath(), JSON.StringifyIndented(config));
        }
Пример #8
0
        private void SaveTableInfo(string tableName)
        {
            if (tableName.IsEmptyOrNull())
                return;

            var cnn = this.ConnectionsCombo.SelectedItem as GeneratorConfig.Connection;
            var tableObj = cnn != null ? cnn.Tables.FirstOrDefault(x => x.Tablename == tableName) : null;
            if (tableObj == null && cnn != null)
            {
                tableObj = new GeneratorConfig.Table();
                tableObj.Tablename = tableName;
                cnn.Tables.Add(tableObj);
            }

            if (tableObj != null)
            {
                tableObj.Identifier = EntitySingular;
                tableObj.PermissionKey = Permission;
                tableObj.Module = Module;
                tableObj.ConnectionKey = ConnectionKey;
            }

            config.Save();
        }
Пример #9
0
        public void Run(string projectJson, string[] args)
        {
            var projectDir = Path.GetDirectoryName(projectJson);

            var outFile = args.FirstOrDefault(x => x.StartsWith("-o:"))?.Substring(3).TrimToNull();
            var connectionKey = args.FirstOrDefault(x => x.StartsWith("-c:"))?.Substring(3).TrimToNull();
            var table = args.FirstOrDefault(x => x.StartsWith("-t:"))?.Substring(3).TrimToNull();
            var what = args.FirstOrDefault(x => x.StartsWith("-w:"))?.Substring(3).TrimToNull();
            var module = args.FirstOrDefault(x => x.StartsWith("-m:"))?.Substring(3).TrimToNull();
            var identifier = args.FirstOrDefault(x => x.StartsWith("-i:"))?.Substring(3).TrimToNull();
            var permissionKey = args.FirstOrDefault(x => x.StartsWith("-p:"))?.Substring(3).TrimToNull();
            if (identifier != null)
                CodeFileHelper.Overwrite = true;

            var config = GeneratorConfig.LoadFromFile(Path.Combine(projectDir, "sergen.json"));
            var connectionKeys = config.Connections
                .Where(x => !x.ConnectionString.IsEmptyOrNull())
                .Select(x => x.Key).ToList();

            var appSettingsFile = Path.Combine(projectDir, "appsettings.json");
            AppSettingsFormat appSettings;
            if (File.Exists(appSettingsFile))
                appSettings = JSON.ParseTolerant<AppSettingsFormat>(File.ReadAllText(appSettingsFile).TrimToNull() ?? "{}");
            else
                appSettings = new AppSettingsFormat();

            connectionKeys.AddRange(appSettings.Data.Keys);

            var appSettingsFile2 = Path.Combine(projectDir, "appsettings.machine.json");
            if (File.Exists(appSettingsFile2))
            {
                var appSettings2 = JSON.ParseTolerant<AppSettingsFormat>(File.ReadAllText(appSettingsFile2).TrimToNull() ?? "{}");
                foreach (var pair in appSettings2.Data)
                    appSettings.Data[pair.Key] = pair.Value;
            }

            connectionKeys.AddRange(appSettings.Data.Keys);

            connectionKeys = connectionKeys.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(x => x).ToList();

            if (connectionKeys.Count == 0)
            {
                Console.Error.WriteLine("No connections in appsettings.json or sergen.json!");
                Environment.Exit(1);
            }

            if (outFile == null && connectionKey == null)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("=== Table Code Generation ===");
                Console.WriteLine("");
                Console.ResetColor();

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Available Connections:");
                Console.ResetColor();
                foreach (var x in connectionKeys)
                    Console.WriteLine(x);
                Console.ResetColor();
                Console.WriteLine();
            }
            else if (connectionKey == null)
            {
                File.WriteAllText(outFile, JSON.Stringify(connectionKeys));
                Environment.Exit(0);
            }

            string userInput = null;

            if (outFile == null && connectionKey == null)
            {
                userInput = connectionKeys.Count == 1 ? connectionKeys[0] : null;
                while (connectionKey == null ||
                    !connectionKeys.Contains(connectionKey, StringComparer.OrdinalIgnoreCase))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Connection: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    connectionKey = Hinter.ReadHintedLine(connectionKeys, userInput: userInput);
                    userInput = connectionKey;

                    if (connectionKey == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            userInput = connectionKey;
            connectionKey = connectionKeys.Find(x => string.Compare(x, userInput, StringComparison.OrdinalIgnoreCase) == 0);
            if (connectionKey == null)
            {
                Console.Error.WriteLine("Can't find connection with key: " + userInput + "!");
                Environment.Exit(1);
            }

            if (outFile == null)
            {
                Console.ResetColor();
                Console.WriteLine();
            }

            var dataConnection = appSettings.Data.ContainsKey(connectionKey) ?
                appSettings.Data[connectionKey] : null;

            var confConnection = config.Connections.FirstOrDefault(x =>
                string.Compare(x.Key, connectionKey, StringComparison.OrdinalIgnoreCase) == 0);

            var connectionString = dataConnection != null ? dataConnection.ConnectionString.TrimToNull() : null;
            if (connectionString == null && confConnection != null)
                connectionString = confConnection.ConnectionString.TrimToNull();

            var providerName = dataConnection != null ? dataConnection.ProviderName.TrimToNull() : null;
            if (providerName == null && confConnection != null)
                providerName = confConnection.ProviderName.TrimToNull();
            providerName = providerName ?? "System.Data.SqlClient";

            // TODO: register other factories from config file?
            DbProviderFactories.RegisterFactory("System.Data.SqlClient", SqlClientFactory.Instance);

            List<TableName> tableNames;
            using (var connection = SqlConnections.New(connectionString, providerName))
                tableNames = SqlSchemaInfo.GetTableNames(connection);

            var tables = tableNames.Select(x => x.Tablename).ToList();

            if (outFile == null && table == null)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Available Tables:");
                Console.ResetColor();

                foreach (var x in tables)
                    Console.WriteLine(x);
            }
            else if (table == null)
            {
                File.WriteAllText(outFile, JSON.Stringify(tableNames.Select(x =>
                {
                    var xct = confConnection == null ? null : confConnection.Tables.FirstOrDefault(z => string.Compare(z.Tablename, table, StringComparison.OrdinalIgnoreCase) == 0);
                    return new
                    {
                        name = x.Tablename,
                        module = xct == null || xct.Module.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(connectionKey) : xct.Module,
                        permission = xct == null || xct.PermissionKey.IsTrimmedEmpty() ? "Administration:General" : xct.PermissionKey,
                        identifier = xct == null || xct.Identifier.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(x.Table) : xct.Identifier,
                    };
                })));
                
                Environment.Exit(0);
            }

            userInput = tables.Count == 1 ? tables[0] : null;
            if (userInput == null && tables.Any(x => x.StartsWith("dbo.")))
                userInput = "dbo.";

            if (outFile == null)
            {
                Console.WriteLine();

                while (table == null ||
                    !tables.Contains(table, StringComparer.OrdinalIgnoreCase))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    table = Hinter.ReadHintedLine(tables, userInput: userInput);
                    userInput = table;

                    if (table == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            userInput = table;
            var tableName = tableNames.First(x => string.Compare(x.Tablename, userInput, StringComparison.OrdinalIgnoreCase) == 0);
            if (tableName == null)
            {
                Console.Error.WriteLine("Can't find table with name: " + userInput + "!");
                Environment.Exit(1);
            }

            var confTable = confConnection == null ? null : confConnection.Tables.FirstOrDefault(x =>
                string.Compare(x.Tablename, table, StringComparison.OrdinalIgnoreCase) == 0);

            if (module == null)
            {
                userInput = confTable == null || confTable.Module.IsEmptyOrNull() ?
                    RowGenerator.ClassNameFromTableName(connectionKey) : confTable.Module;

                Console.WriteLine();

                while (module.IsTrimmedEmpty())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Module name for table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    module = Hinter.ReadHintedLine(new string[0], userInput: userInput);
                    userInput = module;

                    if (module == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            if (identifier == null)
            {
                userInput = confTable == null || confTable.Identifier.IsEmptyOrNull() ?
                    RowGenerator.ClassNameFromTableName(tableName.Table) : confTable.Identifier;

                Console.WriteLine();

                while (identifier.IsTrimmedEmpty())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a class Identifier for table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    identifier = Hinter.ReadHintedLine(new string[0], userInput: userInput);
                    userInput = identifier;

                    if (identifier == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            if (permissionKey == null)
            {
                userInput = confTable == null || confTable.PermissionKey.IsTrimmedEmpty() ?
                    "Administration:General" : confTable.PermissionKey;

                Console.WriteLine();

                while (permissionKey.IsTrimmedEmpty())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Permission Key for table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    permissionKey = Hinter.ReadHintedLine(new string[0], userInput: userInput);
                    userInput = permissionKey;

                    if (permissionKey == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }


            if (what == null)
            { 
                Console.WriteLine();

                userInput = "RSU";
                while (what.IsEmptyOrNull())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Choose What to Generate (R:Row, S:Repo+Svc, U=Cols+Form+Page+Grid+Dlg+Css)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    what = Hinter.ReadHintedLine(new string[0], userInput: userInput);
                    userInput = what;

                    if (what == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            config.GenerateRow = what.IndexOf("R", StringComparison.OrdinalIgnoreCase) >= 0;
            config.GenerateService = what.IndexOf("S", StringComparison.OrdinalIgnoreCase) >= 0;
            config.GenerateUI = what.IndexOf("U", StringComparison.OrdinalIgnoreCase) >= 0;

            Console.ResetColor();
            Console.WriteLine();

            if (confConnection == null)
            {
                confConnection = new GeneratorConfig.Connection
                {
                    Key = connectionKey
                };
                config.Connections.Add(confConnection);
            }

            if (confTable == null)
            {
                confTable = new GeneratorConfig.Table
                {
                    Identifier = identifier,
                    Module = module,
                    PermissionKey = permissionKey,
                    Tablename = tableName.Tablename
                };

                confConnection.Tables.Add(confTable);
            }
            else
            {
                confTable.Identifier = identifier;
                confTable.Module = module;
                confTable.PermissionKey = permissionKey;
            }

            File.WriteAllText(Path.Combine(projectDir, "sergen.json"), config.SaveToJson());

            using (var connection = SqlConnections.New(connectionString, providerName))
            {
                connection.Open();

                var rowModel = RowGenerator.GenerateModel(connection, tableName.Schema, tableName.Table,
                    module, connectionKey, identifier, permissionKey, config);

                new EntityCodeGenerator(rowModel, config, projectJson).Run();
            }
        }
            public ExitCodes Run()
            {
                AnsiConsole.WriteLine();
                AnsiConsole.Write(new Spectre.Console.Rule($"[bold springgreen3_1]Table Code Generation[/]")
                {
                    Alignment = Justify.Left
                });

                var csproj = SelectCsProj();

                if (csproj is null)
                {
                    return(ExitCodes.NoProjectFiles);
                }

                var projectDir = Path.GetDirectoryName(csproj);
                var config     = GeneratorConfig.LoadFromFile(Path.Combine(projectDir, "sergen.json"));

                if (!string.IsNullOrEmpty(config.CustomTemplates))
                {
                    Templates.TemplatePath = Path.Combine(projectDir, config.CustomTemplates);
                }

                var connectionString = SelectConnectionString(config, projectDir);

                if (connectionString.connectionKey is null)
                {
                    return(ExitCodes.NoConnectionString);
                }
                var confConnection = config.Connections?.FirstOrDefault(x =>
                                                                        string.Compare(x.Key, connectionString.connectionKey, StringComparison.OrdinalIgnoreCase) == 0);

                var tables = SelectedTables(connectionString.sqlConnections, connectionString.connectionKey);

                var module        = string.Empty;
                var permissionKey = "Administration:General";

                var generateData = new Dictionary <string, (string module, string identifier, string permissionKey, TableName table)>();


                foreach (var table in tables.selectedTables)
                {
                    var confTable = confConnection?.Tables.FirstOrDefault(x => string.Compare(x.Tablename, table.Tablename, StringComparison.OrdinalIgnoreCase) == 0);

                    if (string.IsNullOrEmpty(module))
                    {
                        module = confTable?.Module?.TrimToNull() is null?
                                 RowGenerator.ClassNameFromTableName(connectionString.connectionKey) : confTable.Module;
                    }

                    module = SelectModule(table.Tablename, module);

                    var defaultIdentifier = confTable?.Identifier?.TrimToNull() is null?
                                            RowGenerator.ClassNameFromTableName(table.Table) : confTable.Identifier;

                    var identifier = SelectIdentifier(table.Tablename, defaultIdentifier);

                    permissionKey = SelectPermissionKey(table.Tablename, confTable?.PermissionKey?.TrimToNull() ?? permissionKey);
                    generateData.Add(table.Tablename, (module, identifier, permissionKey, table));
                }

                var whatToGenerate = SelectWhatToGenerate();

                config.GenerateRow     = whatToGenerate.Contains("Row");
                config.GenerateService = whatToGenerate.Contains("Repository & Service");
                config.GenerateUI      = whatToGenerate.Contains("User Interface");
                config.GenerateCustom  = whatToGenerate.Contains("Custom");

                foreach (var data in generateData)
                {
                    var confTable = confConnection?.Tables.FirstOrDefault(x => string.Compare(x.Tablename, data.Key, StringComparison.OrdinalIgnoreCase) == 0);

                    if (confConnection == null)
                    {
                        confConnection = new GeneratorConfig.Connection
                        {
                            Key = connectionString.connectionKey
                        };
                        config.Connections.Add(confConnection);
                    }

                    if (confTable == null)
                    {
                        confTable = new GeneratorConfig.Table
                        {
                            Identifier    = data.Value.identifier,
                            Module        = data.Value.module,
                            PermissionKey = data.Value.permissionKey,
                            Tablename     = data.Key
                        };

                        confConnection.Tables.Add(confTable);
                    }
                    else
                    {
                        confTable.Identifier    = data.Value.identifier;
                        confTable.Module        = data.Value.module;
                        confTable.PermissionKey = data.Value.permissionKey;
                    }

                    File.WriteAllText(Path.Combine(projectDir, "sergen.json"), config.SaveToJson());

                    using var connection = connectionString.sqlConnections.NewByKey(connectionString.connectionKey);
                    connection.Open();

                    var csprojContent = File.ReadAllText(csproj);
                    var net5Plus      = !new Regex(@"\<TargetFramework\>.*netcoreapp.*\<\/TargetFramework\>", RegexOptions.Multiline | RegexOptions.Compiled)
                                        .IsMatch(csprojContent);

                    var rowModel = RowGenerator.GenerateModel(connection, data.Value.table.Schema, data.Value.table.Table,
                                                              data.Value.module, connectionString.connectionKey, data.Value.identifier, data.Value.permissionKey, config, net5Plus);

                    rowModel.AspNetCore = true;
                    rowModel.NET5Plus   = net5Plus;

                    var kdiff3Paths = new[]
                    {
                        config.KDiff3Path
                    };

                    CodeFileHelper.Kdiff3Path = kdiff3Paths.FirstOrDefault(File.Exists);
                    CodeFileHelper.TSCPath    = config.TSCPath ?? "tsc";

                    new EntityCodeGenerator(rowModel, config, csproj).Run();
                }


                return(ExitCodes.Success);
            }
Пример #11
0
        private void ConnectionsCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this._tables.Clear();
            GenerateCodeButton.IsEnabled = false;

            if (this.ConnectionsCombo.SelectedItem != null)
            {
                var conn = (GeneratorConfig.Connection) this.ConnectionsCombo.SelectedItem;

                try
                {
                    using (var connection = SqlConnections.New(conn.ConnectionString, conn.ProviderName))
                    {
                        connection.Open();

                        foreach (var t in SqlSchemaInfo.GetTableNames(connection))
                        {
                            var table = conn != null?conn.Tables.FirstOrDefault(x => x.Tablename == t.Tablename) : null;

                            var permission    = table == null ? "Administration:General" : table.PermissionKey;
                            var connectionKey = (table != null && !table.ConnectionKey.IsEmptyOrNull()) ?
                                                table.ConnectionKey : conn.Key;
                            var module = (table != null && table.Module != null) ? table.Module :
                                         this.adminTables.Any(atbl => $"{config.TablePrefixSettings?.ModulePrefixes?["Administration"]}_{atbl}".Equals(t.Tablename, StringComparison.InvariantCultureIgnoreCase)) ?
                                         "Administration"
                                : Inflector.Inflector.Capitalize(connectionKey);
                            var identifier = (table == null || table.Identifier.IsEmptyOrNull()) ?
                                             RowGenerator.ClassNameFromTableName(RowGenerator.UnprefixTable(t.Table, module, this.config)) : table.Identifier;

                            var tableItem = new TableItem
                            {
                                IsChecked     = false,
                                ConnectionKey = conn.Key,
                                Module        = module,
                                Identifier    = identifier,
                                PermissionKey = permission,
                                FullName      = t.Tablename
                            };

                            _tables.Add(tableItem);
                            tableItem.PropertyChanged += (s, e2) =>
                            {
                                var t2 = conn.Tables.FirstOrDefault(x => x.Tablename == tableItem.FullName);
                                if (t2 == null)
                                {
                                    t2           = new GeneratorConfig.Table();
                                    t2.Tablename = tableItem.FullName;
                                    conn.Tables.Add(t2);
                                }
                                t2.Module = tableItem.Module;
                                if (e2.PropertyName.Equals("Module"))
                                {
                                    tableItem.Identifier = RowGenerator.ClassNameFromTableName(RowGenerator.UnprefixTable(t2.Tablename, t2.Module, this.config));
                                }
                                t2.Identifier    = tableItem.Identifier;
                                t2.ConnectionKey = tableItem.ConnectionKey;
                                t2.PermissionKey = tableItem.PermissionKey;
                                this.config.Save();

                                GenerateCodeButton.IsEnabled = _tables.Any(x => x.IsChecked);
                            };
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
Пример #12
0
        private void ConnectionsCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this._tables.Clear();
            GenerateCodeButton.IsEnabled = false;

            if (this.ConnectionsCombo.SelectedItem != null)
            {
                var conn = (GeneratorConfig.Connection)this.ConnectionsCombo.SelectedItem;

                try
                {
                    using (var connection = SqlConnections.New(conn.ConnectionString, conn.ProviderName))
                    {
                        connection.Open();

                        foreach (var t in SqlSchemaInfo.GetTableNames(connection))
                        {
                            var table = conn != null ? conn.Tables.FirstOrDefault(x => x.Tablename == t.Tablename) : null;
                            var identifier = (table == null || table.Identifier.IsEmptyOrNull()) ?
                                RowGenerator.ClassNameFromTableName(t.Table) : table.Identifier;
                            var permission = table == null ? "Administration:General" : table.PermissionKey;
                            var connectionKey = (table != null && !table.ConnectionKey.IsEmptyOrNull()) ?
                                table.ConnectionKey : conn.Key;

                            var module = (table != null && table.Module != null) ? table.Module :
                                Inflector.Inflector.Capitalize(connectionKey);

                            var tableItem = new TableItem
                            {
                                IsChecked = false,
                                ConnectionKey = conn.Key,
                                Module = module,
                                Identifier = identifier,
                                PermissionKey = permission,
                                FullName = t.Tablename
                            };

                            _tables.Add(tableItem);
                            tableItem.PropertyChanged += (s, e2) =>
                            {
                                var t2 = conn.Tables.FirstOrDefault(x => x.Tablename == tableItem.FullName);
                                if (t2 == null)
                                {
                                    t2 = new GeneratorConfig.Table();
                                    t2.Tablename = tableItem.FullName;
                                    conn.Tables.Add(t2);
                                }
                                t2.Identifier = tableItem.Identifier;
                                t2.Module = tableItem.Module;
                                t2.ConnectionKey = tableItem.ConnectionKey;
                                t2.PermissionKey = tableItem.PermissionKey;
                                this.config.Save();

                                GenerateCodeButton.IsEnabled = _tables.Any(x => x.IsChecked);
                            };
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }