public override DataProvider GetDataProvider() { var connOptions = Options.Create(ConnectionStringOptions.GetLegacyConnectionStrings()); return(new MsSqlDataProvider(Options.Create(DataOptions.GetLegacyConfiguration()), connOptions, new MsSqlDataInstaller(connOptions, NullLoggerFactory.Instance.CreateLogger <MsSqlDataInstaller>()))); }
public static string GetConnectionString(ConnectionInfo connectionInfo, ConnectionStringOptions connectionStrings) { string cnstr; if (string.IsNullOrEmpty(connectionInfo.ConnectionName)) { cnstr = connectionStrings.Repository; } else if (!connectionStrings.AllConnectionStrings.TryGetValue(connectionInfo.ConnectionName, out cnstr) || cnstr == null) { throw new InvalidOperationException("Unknown connection name: " + connectionInfo.ConnectionName); } var connectionBuilder = new SqlConnectionStringBuilder(cnstr); switch (connectionInfo.InitialCatalog) { case InitialCatalog.Initial: break; case InitialCatalog.Master: connectionBuilder.InitialCatalog = "master"; break; default: throw new NotSupportedException("Unknown InitialCatalog"); } if (!string.IsNullOrEmpty(connectionInfo.DataSource)) { connectionBuilder.DataSource = connectionInfo.DataSource; } if (!string.IsNullOrEmpty(connectionInfo.InitialCatalogName) && connectionInfo.InitialCatalog != InitialCatalog.Master) { connectionBuilder.InitialCatalog = connectionInfo.InitialCatalogName; } if (!string.IsNullOrWhiteSpace(connectionInfo.UserName)) { if (string.IsNullOrWhiteSpace(connectionInfo.Password)) { throw new NotSupportedException("Invalid credentials."); } connectionBuilder.UserID = connectionInfo.UserName; connectionBuilder.Password = connectionInfo.Password; connectionBuilder.IntegratedSecurity = false; } else { connectionBuilder.Remove("User ID"); connectionBuilder.Remove("Password"); connectionBuilder.Remove("Persist Security Info"); connectionBuilder.IntegratedSecurity = true; } return(connectionBuilder.ToString()); }
private static bool ParseArguments(string[] args, ConnectionStringOptions options) { var passed = CommandLine.Parser.Default.ParseArguments(args, options); options.GuardArgumentsValid(); return(passed); }
public void DC_MSSQL_Construction_ConnectionInfo_Named_CustomDb() { var connectionInfo = new ConnectionInfo { ConnectionName = "CustomCnStr", InitialCatalog = InitialCatalog.Initial, InitialCatalogName = "CustomDb" }; // ACTION var connectionStrings = new ConnectionStringOptions { Repository = "Data Source=ds;Initial Catalog=ic;Integrated Security=True", AllConnectionStrings = new Dictionary <string, string> { { "CustomCnStr", "Data Source=CustomServer;Initial Catalog=InitialCatalog1;Integrated Security=True" } } }; var connectionString = MsSqlDataContext.GetConnectionString(connectionInfo, connectionStrings); // ASSERT var expected = "Data Source=CustomServer;Initial Catalog=CustomDb;Integrated Security=True"; Assert.AreEqual(expected, connectionString); }
public ArtGalleryData(IOptions <ConnectionStringOptions> options) { ConnectionStringOptions conStrOptions = options.Value; this.connectionString = conStrOptions.GalleryLite; setTargetTable(); }
public override IBlobStorageMetaDataProvider GetBlobMetaDataProvider(DataProvider dataProvider) { //TODO: get services and options from outside return(new MsSqlBlobMetaDataProvider(Providers.Instance.BlobProviders, Options.Create(DataOptions.GetLegacyConfiguration()), Options.Create(BlobStorageOptions.GetLegacyConfiguration()), Options.Create(ConnectionStringOptions.GetLegacyConnectionStrings()))); }
public MsSqlDataInstaller(IOptions <ConnectionStringOptions> connectionOptions, ILogger <MsSqlDataInstaller> logger) { _columnNames = new Dictionary <string, string[]>(); ConnectionStrings = connectionOptions?.Value ?? new ConnectionStringOptions(); _logger = logger; }
public MsSqlBlobMetaDataProvider(IBlobProviderStore providers, IOptions <DataOptions> dataOptions, IOptions <BlobStorageOptions> blobStorageOptions, IOptions <ConnectionStringOptions> connectionOptions) { Providers = providers; DataOptions = dataOptions?.Value ?? new DataOptions(); BlobStorageOptions = blobStorageOptions?.Value ?? new BlobStorageOptions(); ConnectionStrings = connectionOptions?.Value ?? new ConnectionStringOptions(); }
public static IServiceCollection AddHealthCheck(this IServiceCollection services, IConfiguration configuration) { var connectionStringOptions = new ConnectionStringOptions(); configuration.GetSection("ConnectionStrings").Bind(connectionStringOptions); services.AddHealthChecks() .AddMySql(connectionStringOptions.MySQLDbConnection, "MySQL", HealthStatus.Unhealthy); return(services); }
internal static void EditConnectionString(ConnectionStringOptions connectionStrings, Dictionary <string, string> parameters, PackageParameter[] packageParameters) { string dataSource; if (!parameters.TryGetValue("@datasource", out dataSource)) { throw new PackagingException("Missing manifest parameter in system install: 'dataSource'"); } string initialCatalog; if (!parameters.TryGetValue("@initialcatalog", out initialCatalog)) { throw new PackagingException("Missing manifest parameter in system install: 'initialCatalog'"); } string userName; if (!parameters.TryGetValue("@username", out userName)) { throw new PackagingException("Missing manifest parameter in system install: 'userName'"); } string password; if (!parameters.TryGetValue("@password", out password)) { throw new PackagingException("Missing manifest parameter in system install: 'password'"); } var defaultCnInfo = new ConnectionInfo { DataSource = dataSource, InitialCatalogName = initialCatalog, UserName = userName, Password = password }; var inputCnInfo = new ConnectionInfo { DataSource = packageParameters.FirstOrDefault(x => string.Compare(x.PropertyName, "datasource", StringComparison.InvariantCultureIgnoreCase) == 0)?.Value, InitialCatalogName = packageParameters.FirstOrDefault(x => string.Compare(x.PropertyName, "initialcatalog", StringComparison.InvariantCultureIgnoreCase) == 0)?.Value, UserName = packageParameters.FirstOrDefault(x => string.Compare(x.PropertyName, "username", StringComparison.InvariantCultureIgnoreCase) == 0)?.Value, Password = packageParameters.FirstOrDefault(x => string.Compare(x.PropertyName, "password", StringComparison.InvariantCultureIgnoreCase) == 0)?.Value }; var origCnStr = connectionStrings.Repository; var newCnStr = EditConnectionString(origCnStr, inputCnInfo, defaultCnInfo); if (newCnStr != origCnStr) { connectionStrings.Repository = newCnStr; } }
private static async Task <bool> CheckConnection(ConnectionStringOptions option, StringBuilder errors) { var result = await option.CheckConnection(); if (!result) { errors.AppendLine($"Connection for options {option.GetType()} failed."); return(false); } return(true); }
public MsSqlTestingDataProvider(DataProvider mainProvider, IOptions <ConnectionStringOptions> connectionStrings) { if (mainProvider == null) { return; } if (!(mainProvider is RelationalDataProviderBase relationalDataProviderBase)) { throw new ArgumentException("The mainProvider need to be RelationalDataProviderBase."); } _mainProvider = relationalDataProviderBase; _connectionStrings = connectionStrings.Value; }
/// <summary> /// Creates a new connection and initializes it with random connection string generated from the factory's source /// Note: if rnd is null, create a connection with minimal string required to connect to the target database /// </summary> /// <param name="rnd">Randomizes Connection Pool enablement, the application Name to randomize connection pool</param> /// <param name="options"></param> /// <returns></returns> public DataStressConnection CreateConnection(Random rnd = null, ConnectionStringOptions options = ConnectionStringOptions.Default) { // Determine connection options (connection string, identity, etc) string connectionString = CreateBaseConnectionString(rnd, options); bool clearPoolBeforeClose = false; if (rnd != null) { // Connection string and/or identity are randomized // We implement this using the Application Name field in the connection string since this field // should not affect behaviour other than connection pooling, since all connections in a pool // must have the exact same connection string (including Application Name) if (rnd.NextBool(.1)) { // Disable pooling connectionString = connectionString + ";Pooling=false;"; } else if (rnd.NextBool(0.001)) { // Use a unique Application Name to get a new connection from a new pool. We do this in order to // stress the code that creates/deletes pools. connectionString = string.Format("{0}; Pooling=true; Application Name=\"{1}\";", connectionString, GetRandomApplicationName()); // Tell DataStressConnection to call SqlConnection.ClearPool when closing the connection. This ensures // we do not keep a large number of connections in the pool that we will never use again. clearPoolBeforeClose = true; } else { switch (CurrentPoolingStressMode) { case PoolingStressMode.RandomizeConnectionStrings: // Use one of the pre-generated Application Names in order to get a pooled connection with a randomized connection string connectionString = string.Format("{0}; Pooling=true; Application Name=\"{1}\";", connectionString, _applicationNames[rnd.Next(_applicationNames.Count)]); break; default: throw DataStressErrors.UnhandledCaseError(CurrentPoolingStressMode); } } } // All options have been determined, now create DbConnection con = DbFactory.CreateConnection(); con.ConnectionString = connectionString; return(new DataStressConnection(con, clearPoolBeforeClose)); }
public void CanHaveSqlAuthentication() { var args = new[] { "--server", "server", "--database", "database", "--username", "user", "--password", "pass" }; var options = new ConnectionStringOptions(); var passed = ParseArguments(args, options); Assert.IsTrue(passed, "failed to parse args"); var builder = options.ConnectionStringBuilder(); Assert.AreEqual(false, builder.IntegratedSecurity); Assert.AreEqual("user", builder.UserID); Assert.AreEqual("pass", builder.Password); }
public void CanHaveIntegratedSecurity() { var args = new[] { "--server", "server", "--database", "database", "--integrated" }; var options = new ConnectionStringOptions(); var passed = ParseArguments(args, options); Assert.IsTrue(passed, "failed to parse args"); var builder = options.ConnectionStringBuilder(); Assert.AreEqual("server", builder.DataSource); Assert.AreEqual("database", builder.InitialCatalog); Assert.AreEqual(true, builder.IntegratedSecurity); }
public void UseTrustServerCert() { var args = new[] { "--server", "server", "--database", "database", "--username", "user", "--password", "pass", "--trust-server-certificate" }; var options = new ConnectionStringOptions(); var passed = ParseArguments(args, options); Assert.IsTrue(passed, "failed to parse args"); var builder = options.ConnectionStringBuilder(); Assert.AreEqual(true, builder.TrustServerCertificate); }
public void MustHaveUsernameAndPassword(string argumentName, string value) { var args = new[] { "--server", "server", "--database", "database", argumentName, value }; var options = new ConnectionStringOptions(); var failed = false; try { ParseArguments(args, options); } catch (Exception) { failed = true; } Assert.IsTrue(failed, "expected parsing to fail"); }
public void DC_MSSQL_Construction_ConnectionInfo_Master() { var connectionInfo = new ConnectionInfo { DataSource = "DataSource1", InitialCatalog = InitialCatalog.Master, InitialCatalogName = "InitialCatalog1" }; // ACTION var connectionStrings = new ConnectionStringOptions { Repository = "Data Source=ds;Initial Catalog=ic;Integrated Security=True" }; var connectionString = MsSqlDataContext.GetConnectionString(connectionInfo, connectionStrings); // ASSERT var expected = "Data Source=DataSource1;Initial Catalog=master;Integrated Security=True"; Assert.AreEqual(expected, connectionString); }
internal static async Task DetectServerSupportedFeatures(ConnectionStringOptions connectionOptions) { using (var store = CreateDocumentStore(connectionOptions)) { var serverVersion = (await store.AsyncDatabaseCommands.GlobalAdmin.GetBuildNumberAsync().ConfigureAwait(false)).BuildVersion; if (string.IsNullOrEmpty(serverVersion)) { throw new SmugglerException("Server version is not available."); } var smugglerVersion = FileVersionInfo.GetVersionInfo(AssemblyHelper.GetAssemblyLocationFor <Program>()).ProductVersion; var subSmugglerVersion = smugglerVersion.Substring(0, 4); var intServerVersion = int.Parse(serverVersion); if (intServerVersion < 40) { throw new SmugglerException(string.Format("This smuggler version requires a v4.0 or higher server. Smuggler version: {0}.", subSmugglerVersion)); } } }
public void DC_MSSQL_Construction_ConnectionInfo_UserPassword() { var connectionInfo = new ConnectionInfo { DataSource = "DataSource1", InitialCatalog = InitialCatalog.Initial, InitialCatalogName = "InitialCatalog1", UserName = "******", Password = "******" }; // ACTION var connectionStrings = new ConnectionStringOptions { Repository = "Data Source=ds;Initial Catalog=ic;Persist Security Info=False;Integrated Security=True" }; var connectionString = MsSqlDataContext.GetConnectionString(connectionInfo, connectionStrings); // ASSERT var expected = "Data Source=DataSource1;Initial Catalog=InitialCatalog1;Integrated Security=False;Persist Security Info=False;User ID=User1;Password=123"; Assert.AreEqual(expected, connectionString); }
private static DocumentStore CreateDocumentStore(ConnectionStringOptions options) { var credentials = options.Credentials as NetworkCredential; if (credentials == null) { credentials = CredentialCache.DefaultNetworkCredentials; } else if ((string.IsNullOrWhiteSpace(credentials.UserName) || string.IsNullOrWhiteSpace(credentials.Password))) { credentials = CredentialCache.DefaultNetworkCredentials; } var store = new DocumentStore { Credentials = credentials, ApiKey = options.ApiKey, Url = options.Url, }; store.Initialize(); return(store); }
static void Main(string[] args) { args = new[] { TestType.Backup.ToString() }; if (args.Length == 0) { Console.WriteLine("Missing test type. Expected 'Backup', 'Restore', 'Validity' or 'Cancellation'."); return; } if (!Enum.TryParse <TestType>(args[0], true, out _testType)) { Console.WriteLine("Invalid test type. Expected 'Backup', 'Restore' or 'Validity'."); return; } _serviceIndexDirectory = Path.GetFullPath($"{Environment.CurrentDirectory}\\..\\..\\..\\..\\..\\" + //"SenseNet.Search.Lucene29.Centralized.Service\\" + "SenseNet.Search.Lucene29.Centralized.GrpcService\\" + "bin\\Debug\\netcoreapp3.1\\App_Data\\LocalIndex"); Console.WriteLine("IndexDirectory of the service: "); Console.WriteLine(_serviceIndexDirectory); _backupIndexDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "IndexBackup"); Console.WriteLine("Backup directory: "); Console.WriteLine(_backupIndexDirectory); IConfiguration configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", true, true) .AddEnvironmentVariables() .Build(); //var serviceBinding = new NetTcpBinding { Security = { Mode = SecurityMode.None } }; //var serviceEndpoint = new EndpointAddress(configuration["sensenet:search:service:address"]); //WaitForServiceStarted(serviceBinding, serviceEndpoint); var sender = new MessageSenderManager(); var builder = new RepositoryBuilder() .SetConsole(Console.Out) .UseLogger(new SnFileSystemEventLogger()) .UseTracer(new SnFileSystemTracer()) .UseConfiguration(configuration) .UseDataProvider(new MsSqlDataProvider(Options.Create(ConnectionStringOptions.GetLegacyConnectionStrings()))) .UseSecurityDataProvider(new EFCSecurityDataProvider(sender, Options.Create(new SenseNet.Security.EFCSecurityStore.Configuration.DataOptions() { ConnectionString = ConnectionStrings.ConnectionString }), NullLogger <EFCSecurityDataProvider> .Instance)) .UseSecurityMessageProvider(new RabbitMQMessageProvider(sender, Options.Create(new MessagingOptions()), Options.Create(new RabbitMqOptions()))) .UseLucene29CentralizedSearchEngineWithGrpc(configuration["sensenet:search:service:address"], options => { // trust the server in a development environment options.HttpClient = new HttpClient(new HttpClientHandler { ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true }); options.DisposeHttpClient = true; }) .StartWorkflowEngine(false) .DisableNodeObservers() .UseTraceCategories(SnTrace.Categories.Select(x => x.Name).ToArray()) as RepositoryBuilder; using (Repository.Start(builder)) { Console.WriteLine("CHECK SQL SERVER CONNECTIVITY (query top level nodes):"); var root = Node.LoadNode(Repository.RootPath); foreach (var node in NodeQuery.QueryChildren(Repository.RootPath).Nodes) { Console.WriteLine(node.Path); } Console.WriteLine(); Console.WriteLine("CHECK SEARCH SERVER CONNECTIVITY (query top level nodes):"); var queryContext = new SnQueryContext(QuerySettings.AdminSettings, User.Current.Id); var result = SnQuery.Query("InFolder:/Root", queryContext); foreach (var id in result.Hits) { Console.WriteLine(NodeHead.Get(id).Path); } Console.WriteLine(); SnTrace.EnableAll(); var engine = (ILuceneIndexingEngine)Providers.Instance.SearchEngine.IndexingEngine; switch (_testType) { case TestType.Backup: new ContinuousIndexTest(engine).RunAsync(CancellationToken.None) .ConfigureAwait(false).GetAwaiter().GetResult(); break; case TestType.Restore: new RestoreTest(engine).RunAsync(CancellationToken.None) .ConfigureAwait(false).GetAwaiter().GetResult(); break; case TestType.Validity: new ValidityTest(engine).RunAsync(CancellationToken.None) .ConfigureAwait(false).GetAwaiter().GetResult(); break; case TestType.Cancellation: new CancellationTest(engine).RunAsync(CancellationToken.None) .ConfigureAwait(false).GetAwaiter().GetResult(); break; default: throw new ArgumentOutOfRangeException(); } // Shut down the service to leave the index. IndexManager.IndexingEngine.ShutDownAsync(CancellationToken.None) .ConfigureAwait(false).GetAwaiter().GetResult(); } }
public ReindexBinariesTask(IOptions <ConnectionStringOptions> connectionOptions) { _connectionStrings = connectionOptions.Value; }
/// <summary> /// Creates a new connection and initializes it with random connection string generated from the factory's source /// Note: if rnd is null, create a connection with minimal string required to connect to the target database /// </summary> /// <param name="rnd">Randomizes Connection Pool enablement, the application Name to randomize connection pool</param> /// <param name="options"></param> /// <returns></returns> public DataStressConnection CreateConnection(Random rnd = null, ConnectionStringOptions options = ConnectionStringOptions.Default) { // Determine connection options (connection string, identity, etc) string connectionString = CreateBaseConnectionString(rnd, options); bool clearPoolBeforeClose = false; if (rnd != null) { // Connection string and/or identity are randomized // We implement this using the Application Name field in the connection string since this field // should not affect behaviour other than connection pooling, since all connections in a pool // must have the exact same connection string (including Application Name) if (rnd.NextBool(.1)) { // Disable pooling connectionString = connectionString + ";Pooling=false;"; } else if (rnd.NextBool(0.001)) { // Use a unique Application Name to get a new connection from a new pool. We do this in order to // stress the code that creates/deletes pools. connectionString = string.Format("{0}; Pooling=true; Application Name=\"{1}\";", connectionString, GetRandomApplicationName()); // Tell DataStressConnection to call SqlConnection.ClearPool when closing the connection. This ensures // we do not keep a large number of connections in the pool that we will never use again. clearPoolBeforeClose = true; } else { switch (CurrentPoolingStressMode) { case PoolingStressMode.RandomizeConnectionStrings: // Use one of the pre-generated Application Names in order to get a pooled connection with a randomized connection string connectionString = string.Format("{0}; Pooling=true; Application Name=\"{1}\";", connectionString, _applicationNames[rnd.Next(_applicationNames.Count)]); break; default: throw DataStressErrors.UnhandledCaseError(CurrentPoolingStressMode); } } } // All options have been determined, now create DbConnection con = DbFactory.CreateConnection(); con.ConnectionString = connectionString; return new DataStressConnection(con, clearPoolBeforeClose); }
/// <summary> /// Creates a new connection string. /// Note: if rnd is null, create minimal connection string required to connect to the target database (used during setup) /// Otherwise, string is randomized to enable multiple pools. /// </summary> public abstract string CreateBaseConnectionString(Random rnd, ConnectionStringOptions options);
public override string CreateBaseConnectionString(Random rnd, ConnectionStringOptions options) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); switch (_scenario) { case SqlClientScenario.Sql: builder.DataSource = _source.DataSource; builder.InitialCatalog = _source.Database; break; default: throw new InvalidOperationException("missing case for " + _scenario); } // Randomize between Windows Authentication and SQL Authentication // Note that having 2 options here doubles the number of connection pools bool integratedSecurity = false; if (_source.SupportsWindowsAuthentication) { if (string.IsNullOrEmpty(_source.User)) // if sql login is not provided integratedSecurity = true; else integratedSecurity = (rnd != null) ? (rnd.Next(2) == 0) : true; } if (integratedSecurity) { builder.IntegratedSecurity = true; } else { builder.UserID = _source.User; builder.Password = _source.Password; } if (CurrentPoolingStressMode == PoolingStressMode.RandomizeConnectionStrings && rnd != null) { // Randomize connection string // Randomize packetsize // Note that having 2 options here doubles the number of connection pools if (rnd.NextBool()) { builder.PacketSize = 8192; } else { builder.PacketSize = 512; } // If test case allows randomization and doesn't disallow MultiSubnetFailover, then enable MultiSubnetFailover 20% of the time // Note that having 2 options here doubles the number of connection pools if (!_source.DisableMultiSubnetFailoverSetup && !options.HasFlag(ConnectionStringOptions.DisableMultiSubnetFailover) && rnd != null && rnd.Next(5) == 0) { string msfHostName; if (integratedSecurity) { msfHostName = _multiSubnetSetupHelper.MultiSubnetFailoverHostNameForIntegratedSecurity; } else { msfHostName = _multiSubnetSetupHelper.GetMultiSubnetFailoverHostName(rnd); } string serverName; // replace with build which has host name with multiple IP addresses builder = NetUtils.GetMultiSubnetFailoverConnectionString(builder.ConnectionString, msfHostName, out serverName); } // Randomize between using Named Pipes and TCP providers // Note that having 2 options here doubles the number of connection pools if (rnd != null) { if (rnd.Next(2) == 0) { builder.DataSource = "tcp:" + builder.DataSource; } else if (!_source.DisableNamedPipes) { // Named Pipes if (builder.DataSource.Equals("(local)")) builder.DataSource = "np:" + builder.DataSource; else builder.DataSource = @"np:\\" + builder.DataSource.Split(',')[0] + @"\pipe\sql\query"; } } // Set MARS if it is requested by the test case if (options.HasFlag(ConnectionStringOptions.EnableMars)) { builder.MultipleActiveResultSets = true; } // Disable connection resiliency, which is on by default, 20% of the time. if (rnd != null && rnd.NextBool(.2)) { builder.ConnectRetryCount = 0; } } else { // Minimal randomization of connection string // Enable MARS for all scenarios builder.MultipleActiveResultSets = true; } builder.MaxPoolSize = 1000; return builder.ToString(); }
/// <summary> /// Creates a new connection string. /// Note: if rnd is null, create minimal connection string required to connect to the target database (used during setup) /// Otherwise, string is randomized to enable multiple pools. /// </summary> public abstract string CreateBaseConnectionString(Random rnd, ConnectionStringOptions options);
public BaseSPDataAccess(ConnectionStringOptions connectionString, bool isTransaction = false) { Connection = new DoubleASqlConnection(); Connection.ConnectionString = ConfigurationManager.ConnectionStrings[connectionString.ToString()].ConnectionString; }
public StockLoaderAlphaVantage(ConnectionStringOptions connectionStrings) { _stockConnectionString = connectionStrings.StockQuoteKey; }
public ReindexBinariesDataHandler(DataOptions dataOptions, ConnectionStringOptions connectionStrings) { _dataOptions = dataOptions; _connectionStrings = connectionStrings; }
public AnalyzerDbContext(ConnectionStringOptions connectionStringOptions) : base(connectionStringOptions.DefaultConnection) { }
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(); } }
public AppSettingsFormat() { Data = new ConnectionStringOptions(); }