public static async Task <ChessGamesDbContext> InitDbAsync(string[] args = null, ILoggerFactory loggerFactory = null) { var config = ConfigurationExtensions.Configuration(args); var dbType = config.ServerType(); var dbContext = config.CreateDbContext(dbType, loggerFactory: loggerFactory); Reporter($"Connecting to {dbType} chess database..."); Reporter(" Checking for pending migrations..."); var pendingMigrations = (await RelationalDatabaseFacadeExtensions.GetPendingMigrationsAsync(dbContext.Database)).ToList(); if (pendingMigrations.Any()) { Reporter($" Applying {pendingMigrations.Count} pending migration(s)..."); await dbContext.Database.MigrateAsync(); Reporter(" ... database successfully updated."); } else { Reporter(" No pending migrations"); } return(dbContext); }
public override void Dispose() { switch (Enum.Parse <MixEnums.DatabaseProvider>(MixService.GetConfig <string>("DatabaseProvider"))) { case 0: { SqlConnection.ClearPool((SqlConnection)RelationalDatabaseFacadeExtensions.GetDbConnection(this.get_Database())); break; } case 1: { MySqlConnection.ClearPool((MySqlConnection)RelationalDatabaseFacadeExtensions.GetDbConnection(this.get_Database())); break; } case 2: { NpgsqlConnection.ClearPool((NpgsqlConnection)RelationalDatabaseFacadeExtensions.GetDbConnection(this.get_Database())); break; } } this.Dispose(); return; }
public InventoryIntegrationEventService(IEventBus eventBus, InventoryContext inventoryContext, Func <DbConnection, IIntegrationEventLogService> integrationEventLogServiceFactory) { _inventoryContext = inventoryContext ?? throw new ArgumentNullException(nameof(inventoryContext)); _integrationEventLogServiceFactory = integrationEventLogServiceFactory ?? throw new ArgumentNullException(nameof(integrationEventLogServiceFactory)); _eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus)); _eventLogService = _integrationEventLogServiceFactory(RelationalDatabaseFacadeExtensions.GetDbConnection(_inventoryContext.Database)); }
private List <string> GetListFromStoredProcedure(string spName, [CallerMemberName] string memberName = "", params ValueTuple <string, object>[] args) { try { if (spName != GetFoundDefectsProc && spName != InsertQ4LProc && spName != GetFoundDefectsBySerialProc && spName != GetFoundDefectsBySerialAndFovProc) { throw new SecurityException(); } var jsonList = new List <string>(); using (var connection = (SqlConnection)RelationalDatabaseFacadeExtensions.GetDbConnection(this.Database)) { using (var command = connection.CreateCommand()) { command.CommandType = CommandType.StoredProcedure; command.CommandText = spName; foreach (var arg in args) { command.Parameters.AddWithValue(arg.Item1, arg.Item2); } connection.Open(); var reader = command.ExecuteReader(); while (reader.Read()) { var row = ((IDataRecord)reader)[0].ToString(); if (!string.IsNullOrWhiteSpace(row)) { jsonList.Add(row); } } } } return(jsonList); } catch (SecurityException e) { Log.Error(e, "{0} in call to {1}: ", e.GetType().Name, memberName); throw; } catch (SqlException e) { Log.Error(e, "{0} in call to {1}: ", e.GetType().Name, memberName); throw; } catch (Exception e) { Log.Error(e, "{0} in call to {1}: ", e.GetType().Name, memberName); throw; } }
/// <summary> /// Handle /// </summary> /// <returns></returns> public Response Handle() { _query.Query(_dbContext).All().ForEach((connection) => { var optionBuilder = new DbContextOptionsBuilder <TenantDbContext>(); optionBuilder.UseSqlServer(connection.ConnectionString); var dbContext = new TenantDbContext(optionBuilder.Options); RelationalDatabaseFacadeExtensions.Migrate(dbContext.Database); }); return(new Response()); }
public void Foo(DbContext context, string query, int x, Guid guid, params object[] parameters) { context.Database.ExecuteSqlCommand($""); // Compliant, FormattableString is sanitized context.Database.ExecuteSqlCommand(""); // Compliant, constants are safe context.Database.ExecuteSqlCommand(ConstQuery); // Compliant, constants are safe context.Database.ExecuteSqlCommand("" + ""); // Compliant, constants are safe context.Database.ExecuteSqlCommand(query); // Compliant, not concat or format context.Database.ExecuteSqlCommand("" + query); // Noncompliant context.Database.ExecuteSqlCommand($"", parameters); // Noncompliant FP, interpolated string with argument tranformed in RawQuery context.Database.ExecuteSqlCommand(query, parameters); // Compliant, not concat or format context.Database.ExecuteSqlCommand("" + query, parameters); // Noncompliant context.Database.ExecuteSqlCommand($"SELECT * FROM mytable WHERE mycol={query} AND mycol2={0}", parameters[0]); // Noncompliant, string interpolation it is RawSqlString context.Database.ExecuteSqlCommand($"SELECT * FROM mytable WHERE mycol={query}{query}", x, guid); // Noncompliant, RawSqlQuery context.Database.ExecuteSqlCommand(@$ "SELECT * FROM mytable WHERE mycol={query}{query}", x, guid); // Noncompliant, RawSqlQuery context.Database.ExecuteSqlCommand($@"SELECT * FROM mytable WHERE mycol={query}{query}", x, guid); // Noncompliant, RawSqlQuery context.Database.ExecuteSqlCommand($"SELECT * FROM mytable WHERE mycol={query}"); // Compliant, FormattableString is sanitized RelationalDatabaseFacadeExtensions.ExecuteSqlCommand(context.Database, query); // Compliant RelationalDatabaseFacadeExtensions.ExecuteSqlCommand(context.Database, $"SELECT * FROM mytable WHERE mycol={query}{query}", x, guid); // Noncompliant context.Database.ExecuteSqlCommandAsync($""); // Compliant, FormattableString is sanitized context.Database.ExecuteSqlCommandAsync(""); // Compliant, constants are safe context.Database.ExecuteSqlCommandAsync(ConstQuery); // Compliant, constants are safe context.Database.ExecuteSqlCommandAsync("" + ""); // Compliant, constants are safe context.Database.ExecuteSqlCommandAsync(query); // Compliant, not concat context.Database.ExecuteSqlCommandAsync("" + query); // Noncompliant context.Database.ExecuteSqlCommandAsync(query + ""); // Noncompliant context.Database.ExecuteSqlCommandAsync("" + query + ""); // Noncompliant context.Database.ExecuteSqlCommandAsync($"", parameters); // Noncompliant FP, interpolated string with argument tranformed in RawQuery context.Database.ExecuteSqlCommandAsync(query, parameters); // Compliant, not concat or format context.Database.ExecuteSqlCommandAsync("" + query, parameters); // Noncompliant RelationalDatabaseFacadeExtensions.ExecuteSqlCommandAsync(context.Database, "" + query, parameters); // Noncompliant context.Query <User>().FromSql($""); // Compliant, FormattableString is sanitized context.Query <User>().FromSql(""); // Compliant, constants are safe context.Query <User>().FromSql(ConstQuery); // Compliant, constants are safe context.Query <User>().FromSql(query); // Compliant, not concat/format context.Query <User>().FromSql("" + ""); // Compliant context.Query <User>().FromSql($"", parameters); // Noncompliant FP, interpolated string with argument tranformed in RawQuery context.Query <User>().FromSql("", parameters); // Compliant, the parameters are sanitized context.Query <User>().FromSql(query, parameters); // Compliant context.Query <User>().FromSql("" + query, parameters); // Noncompliant RelationalQueryableExtensions.FromSql(context.Query <User>(), "" + query, parameters); // Noncompliant }
private void ExecuteStoredProcedure(string spName, [CallerMemberName] string memberName = "", params ValueTuple <string, object>[] args) { try { if (spName != GetFoundDefectsProc && spName != InsertQ4LProc && spName != GetFoundDefectsBySerialProc) { throw new SecurityException(); } using (var connection = (SqlConnection)RelationalDatabaseFacadeExtensions.GetDbConnection(this.Database)) { using (var command = connection.CreateCommand()) { command.CommandType = CommandType.StoredProcedure; command.CommandText = spName; foreach (var arg in args) { command.Parameters.AddWithValue(arg.Item1, arg.Item2); } connection.Open(); command.ExecuteNonQuery(); } } } catch (SecurityException e) { Log.Error(e, "{0} in call to {1}: ", e.GetType().Name, memberName); throw; } catch (SqlException e) { Log.Error(e, "{0} in call to {1}: ", e.GetType().Name, memberName); throw; } catch (Exception e) { Log.Error(e, "{0} in call to {1}: ", e.GetType().Name, memberName); throw; } }
public void SetStartupDatabase(string connectionString) { if (!Once) { Once = true; // initialization done var options = new DbContextOptionsBuilder().UseMySql(connectionString).Options; using (DbContext context = new DbContext(options)) { RelationalDatabaseFacadeExtensions.BeginTransaction( context.Database, IsolationLevel.ReadUncommitted ); context.Database.ExecuteSqlRaw(UNLINK_SCRIPT); context.Database.ExecuteSqlRaw(DROP_SCRIPT); context.Database.ExecuteSqlRaw(INSERT_ALL_DISTINGUISHING_TYPES); context.Database.CommitTransaction(); } } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); // Run migrations Console.WriteLine("Running migrations"); using (var db = new PsContext()) { RelationalDatabaseFacadeExtensions.Migrate(db.Database); } }
public RepositoryResponse<string> ProcessSelectedExportDataAsync() { UnitOfWorkHelper<MixCmsContext>.InitTransaction(null, null, ref V_0, ref V_1, ref V_2); stackVariable5 = new RepositoryResponse<string>(); stackVariable5.set_IsSucceed(true); V_3 = stackVariable5; try { try { this.ProcessPages(V_0, V_1); this.ProcessModules(V_0, V_1); this.ProcessAttributeSetsAsync(V_0, V_1); this.ProcessAttributeSetData(V_0, V_1); this.ProcessDatas(V_0, V_1); V_4 = V_3; } catch (Exception exception_0) { V_5 = exception_0; V_6 = UnitOfWorkHelper<MixCmsContext>.HandleException<Mix.Cms.Lib.ViewModels.MixPages.ImportViewModel>(V_5, V_2, V_1); V_3.set_IsSucceed(false); V_3.set_Errors(V_6.get_Errors()); V_3.set_Exception(V_5); V_4 = V_3; } } finally { if (V_2) { RelationalDatabaseFacadeExtensions.CloseConnection(V_0.get_Database()); V_1.Dispose(); V_0.Dispose(); } } return V_4; }
// TODO: Refactor this to work like the unit tests now that I know more about // how to make the DI work. public void Run() { Console.WriteLine("Welcome to Gthx"); // Just to get some output from Azure Trace.TraceError("Gthx running"); _logger.LogInformation($"irc client is {_ircClient}"); var context = _services.GetRequiredService <GthxDataContext>(); RelationalDatabaseFacadeExtensions.Migrate(context.Database); var gthx = _services.GetRequiredService <GthxBot>(); var done = false; while (!done) { #if false //DEBUG Console.Write("command> "); try { var input = Console.ReadLine(); if (input == null || input == "quit") { done = true; } } catch (Exception ex) { _logger.LogError(ex, "Exception in IrcBot program"); done = true; } #else Thread.Sleep(5000); #endif } }
public void RegisterUser(User user, string OUTPUT) { SqlCommand command = new SqlCommand(); SqlParameter parameter = new SqlParameter(); parameter.ParameterName = @"ResponseMessage"; parameter.IsNullable = true; parameter.SqlDbType = System.Data.SqlDbType.VarChar; parameter.Direction = System.Data.ParameterDirection.Output; parameter.Size = 50; command.Parameters.Add(parameter); RelationalDatabaseFacadeExtensions.ExecuteSqlRaw("EXEC RegisterUser @UserId, @FirstName, @LastName, @Email, @UserPassword", new SqlParameter("@UserId", user.UserId), new SqlParameter("@FirstName", user.FirstName), new SqlParameter("@LastName", user.LastName), new SqlParameter("@Email", user.Email), new SqlParameter("@UserPassword", user.UserPassword.ToString()), parameter); //return StatusCode(180); }
public static void LoadFromDatabase(MixCmsContext _context = null, IDbContextTransaction _transaction = null) { UnitOfWorkHelper <MixCmsContext> .InitTransaction(_context, _transaction, ref V_0, ref V_1, ref V_2); try { try { MixService.get_Instance().set_Translator(new JObject()); V_3 = V_0.get_MixLanguage().ToList <MixLanguage>(); V_4 = V_0.get_MixCulture().ToList <MixCulture>(); V_6 = V_4.GetEnumerator(); try { while (V_6.MoveNext()) { V_7 = new MixService.u003cu003ec__DisplayClass63_0(); V_7.culture = V_6.get_Current(); V_8 = new JObject(); stackVariable22 = V_3; stackVariable24 = V_7.u003cu003e9__0; if (stackVariable24 == null) { dummyVar0 = stackVariable24; stackVariable50 = new Func <MixLanguage, bool>(V_7.u003cLoadFromDatabaseu003eb__0); V_10 = stackVariable50; V_7.u003cu003e9__0 = stackVariable50; stackVariable24 = V_10; } V_9 = stackVariable22.Where <MixLanguage>(stackVariable24).ToList <MixLanguage>().GetEnumerator(); try { while (V_9.MoveNext()) { V_11 = V_9.get_Current(); stackVariable33 = V_11.get_Keyword(); stackVariable35 = V_11.get_Value(); if (stackVariable35 == null) { dummyVar1 = stackVariable35; stackVariable35 = V_11.get_DefaultValue(); } V_8.Add(new JProperty(stackVariable33, stackVariable35)); } } finally { ((IDisposable)V_9).Dispose(); } MixService.get_Instance().get_Translator().Add(new JProperty(V_7.culture.get_Specificulture(), V_8)); } } finally { ((IDisposable)V_6).Dispose(); } MixService.get_Instance().set_LocalSettings(new JObject()); V_5 = V_0.get_MixConfiguration().ToList <MixConfiguration>(); V_6 = V_4.GetEnumerator(); try { while (V_6.MoveNext()) { V_13 = new MixService.u003cu003ec__DisplayClass63_1(); V_13.culture = V_6.get_Current(); V_14 = new JObject(); stackVariable65 = V_5; stackVariable67 = V_13.u003cu003e9__1; if (stackVariable67 == null) { dummyVar2 = stackVariable67; stackVariable92 = new Func <MixConfiguration, bool>(V_13.u003cLoadFromDatabaseu003eb__1); V_16 = stackVariable92; V_13.u003cu003e9__1 = stackVariable92; stackVariable67 = V_16; } V_15 = stackVariable65.Where <MixConfiguration>(stackVariable67).ToList <MixConfiguration>().GetEnumerator(); try { while (V_15.MoveNext()) { V_17 = V_15.get_Current(); V_18 = new JProperty(V_17.get_Keyword(), V_17.get_Value()); V_14.Add(V_18); } } finally { ((IDisposable)V_15).Dispose(); } MixService.get_Instance().get_LocalSettings().Add(new JProperty(V_13.culture.get_Specificulture(), V_14)); } } finally { ((IDisposable)V_6).Dispose(); } UnitOfWorkHelper <MixCmsContext> .HandleTransaction(true, V_2, V_1); } catch (Exception exception_0) { dummyVar3 = UnitOfWorkHelper <MixCmsContext> .HandleException <MixLanguage>(exception_0, V_2, V_1); } } finally { if (V_2) { RelationalDatabaseFacadeExtensions.CloseConnection(V_0.get_Database()); V_1.Dispose(); V_0.Dispose(); } } return; }
public BlogDataContext(DbContextOptions <BlogDataContext> options) : base(options) { RelationalDatabaseFacadeExtensions.EnsureCreated(); }
public UserContext(DbContextOptions <UserContext> options) : base((DbContextOptions)options) { RelationalDatabaseFacadeExtensions.Migrate(Database); }
/// <summary> /// Executes the SQL command. /// </summary> /// <param name="sql">The SQL.</param> /// <param name="parameters">The parameters.</param> /// <returns> /// int. /// </returns> public int ExecuteSqlCommand(string sql, params object[] parameters) => RelationalDatabaseFacadeExtensions.ExecuteSqlRaw(this.DbContext.Database, sql, parameters);