Example #1
0
        public virtual void Insert_and_read_Guid_value(MySqlGuidFormat guidFormat, string sqlEquivalent, string supportedServerVersion)
        {
            if (supportedServerVersion != null &&
                !AppConfig.ServerVersion.Supports.Version(ServerVersion.Parse(supportedServerVersion)))
            {
                return;
            }

            using var context = CreateContext(guidFormat);

            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            context.SimpleGuidEntities.Add(new SimpleGuidEntity {
                GuidValue = new Guid("850368D8-93EA-4023-ACC7-6FA6E4C3B27F")
            });
            context.SaveChanges();

            var result = context.SimpleGuidEntities
                         .Where(e => e.GuidValue == new Guid("850368D8-93EA-4023-ACC7-6FA6E4C3B27F"))
                         .ToList();

            var sqlResult = context.SimpleGuidEntities
                            .FromSqlRaw(@"select * from `SimpleGuidEntities` where `GuidValue` = " + string.Format(sqlEquivalent, new Guid("850368D8-93EA-4023-ACC7-6FA6E4C3B27F")))
                            .ToList();

            Assert.Single(result);
            Assert.Equal(new Guid("850368D8-93EA-4023-ACC7-6FA6E4C3B27F"), result[0].GuidValue);
            Assert.Single(sqlResult);
        }
Example #2
0
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
     if (!optionsBuilder.IsConfigured)
     {
         optionsBuilder.UseMySql(_connectionString, ServerVersion.Parse("5.7.33-mysql"));
     }
 }
Example #3
0
        public void Bug_exists_in_MySql57_or_higher_parameter()
        {
            // Parameters are an issue as well, because the get inlined by MySqlConnector and
            // just become constant values as well.

            using var command   = Connection.CreateCommand();
            command.CommandText = @"
SELECT `od1`.`Constant`, `od1`.`OrderID`
FROM `Orders` AS `o`
LEFT JOIN (
    SELECT @p0 AS `Constant`, `od`.`OrderID`
    FROM `Order Details` AS `od`
) AS `od1` ON `o`.`OrderID` = `od1`.`OrderID`
ORDER BY `od1`.`OrderID`;";
            command.Parameters.AddWithValue("@p0", "MyParameterValue");

            using var reader = command.ExecuteReader();
            while (reader.Read())
            {
                var constant = reader["Constant"];
                var expected = ServerVersion.Parse(Connection.ServerVersion).Supports.MySqlBug96947Workaround
                    ? (object)DBNull.Value
                    : "MyParameterValue";

                Assert.Equal(expected, constant);
            }
        }
Example #4
0
 protected override void OnConfiguring(DbContextOptionsBuilder options)
 {
     if (!string.IsNullOrWhiteSpace(this.ConnectionString))
     {
         options.UseMySql(this.ConnectionString, ServerVersion.Parse("8.0.27")).AddInterceptors(new MySqlIgnoreDuplicatesOnInsertInterceptor());
     }
 }
Example #5
0
        public void TestValidVersion(string input, ServerType serverType, string actualVersion, bool supportsRenameIndex)
        {
            var serverVersion = ServerVersion.Parse(input);

            Assert.Equal(serverVersion.Type, serverType);
            Assert.Equal(serverVersion.Version, new Version(actualVersion));
            Assert.Equal(serverVersion.Supports.RenameIndex, supportsRenameIndex);
        }
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
     if (!optionsBuilder.IsConfigured)
     {
         optionsBuilder.UseMySql(Environment.GetEnvironmentVariable("Xfs_ConnectionString"),
                                 ServerVersion.Parse("5.7.34-mysql"),
                                 options => options.EnableRetryOnFailure());
     }
 }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <NewbieContext>(
                optionsBuilder =>
                optionsBuilder.UseMySql(
                    Configuration.GetConnectionString("NewbieDatabase"),
                    ServerVersion.Parse("5.7.36-mysql"),
                    options => options.EnableRetryOnFailure())
                .ConfigureWarnings(c => c.Log((RelationalEventId.CommandExecuting, LogLevel.Debug)))
                .ConfigureWarnings(c => c.Log((RelationalEventId.CommandExecuted, LogLevel.Debug))),
                ServiceLifetime.Transient);
            services.AddDbContextFactory <NewbieContext>(
                optionsBuilder =>
                optionsBuilder.UseMySql(
                    Configuration.GetConnectionString("NewbieDatabase"),
                    ServerVersion.Parse("5.7.36-mysql"),
                    options => options.EnableRetryOnFailure())
                .ConfigureWarnings(c => c.Log((RelationalEventId.CommandExecuting, LogLevel.Debug)))
                .ConfigureWarnings(c => c.Log((RelationalEventId.CommandExecuted, LogLevel.Debug))));
            services.AddLogging(b =>
            {
                b.ClearProviders();
                b.SetMinimumLevel(LogLevel.Trace);
                b.AddNLog(); // uses NLog.config?
            });

            var factory = OsuApiClientFactory.CreateFactory(Configuration.GetSection("Hydrant")["ApiKey"]);

            services.AddSingleton <IHttpApiFactory <IOsuApiClient> >(factory);
            services.AddScoped <IOsuApiClient>(c => c.GetService <IHttpApiFactory <IOsuApiClient> >().CreateHttpApi());

            services.AddTransient <QueryHelper>();

            services.AddTransient(typeof(Lazy <>), typeof(LazyService <>));

            services.AddSingleton(RandomNumberGenerator.Create());

            services.AddMemoryCache();

            services.AddTransient <IDataProvider, DataProvider>();
            services.AddTransient <DataMaintainer>();

            // Legacy
            services.AddTransient <INewbieDatabase, NewbieDatabase>();
            services.AddTransient <ILegacyDataProvider, DataProvider>(sp =>
            {
                var logger                = sp.GetService <ILogger <ILegacyDataProvider> >();
                var dbContext             = sp.GetService <NewbieContext>();
                var osuApiClient          = sp.GetService <IOsuApiClient>();
                var dataProvider          = new DataProvider(dbContext, osuApiClient);
                dataProvider.OnException += e => logger.LogError(e, "{message}", e.Message);
                return(dataProvider);
            });
            services.AddSingleton(OsuMixedApi.OsuApiClient.ClientUsingKey(Configuration.GetSection("Hydrant")["ApiKey"]));
        }
Example #8
0
    /// <summary>
    /// Configures and registers the DB context with the service provider.
    /// </summary>
    /// <param name="services">The <see cref="IServiceCollection"/>.</param>
    /// <returns>The <see cref="IServiceCollection"/>.</returns>
    public static IServiceCollection AddBotDatabaseContext(this IServiceCollection services) =>
    services.AddDbContext <BotContext>((provider, options) =>
    {
        var dbConfig      = provider.GetRequiredService <MySqlSettings>();
        var connString    = dbConfig.ConnectionString;
        var serverVersion = ServerVersion.Parse(dbConfig.MySqlVersionString);
        var retryAmount   = dbConfig.RetryAmount;

        options.UseMySql(connString, serverVersion,
                         contextOptions => contextOptions.EnableRetryOnFailure(retryAmount));
    });
        public WebhookContext CreateDbContext(string[] args)
        {
            var builder          = new DbContextOptionsBuilder <WebhookContext>();
            var connectionString = args.Any() ? args[0] : throw new InvalidOperationException("Please specify a connection string. E.g. dotnet ef database update -- \"Server=localhost;Port=3306;Database=elsa;User=root;Password=password\"");
            var serverVersion    = args.Length >= 2 ? args[1] : null;

            builder.UseMySql(
                connectionString,
                serverVersion != null ? ServerVersion.Parse(serverVersion) : ServerVersion.AutoDetect(connectionString),
                db => db
                .MigrationsAssembly(typeof(WebhookMySqlElsaContextFactory).Assembly.GetName().Name)
                .MigrationsHistoryTable(WebhookContext.MigrationsHistoryTable, WebhookContext.ElsaSchema));

            return(new WebhookContext(builder.Options));
        }
Example #10
0
        public void UseMySql_with_ServerVersion_FromString()
        {
            var builder       = new DbContextOptionsBuilder();
            var serverVersion = ServerVersion.Parse("8.0.21-mysql");

            builder.UseMySql(
                "Server=foo",
                serverVersion);

            var mySqlOptions = new MySqlOptions();

            mySqlOptions.Initialize(builder.Options);

            Assert.Equal(new Version(8, 0, 21), mySqlOptions.ServerVersion.Version);
            Assert.Equal(ServerType.MySql, mySqlOptions.ServerVersion.Type);
            Assert.Equal("mysql", mySqlOptions.ServerVersion.TypeIdentifier);
        }
Example #11
0
        /// <summary>
        /// DBオプションビルダーにDB設定値を適用する。
        /// </summary>
        /// <param name="builder">ビルダー。</param>
        /// <param name="dbconf">DB設定値。</param>
        /// <returns>メソッドチェーン用のビルダー。</returns>
        public DbContextOptionsBuilder ApplyDbConfig(DbContextOptionsBuilder builder, IConfigurationSection dbconf)
        {
            // DB接続設定
            switch (dbconf.GetValue <string>("Type")?.ToLower())
            {
            case "mysql":
                builder.UseMySql(dbconf.GetValue <string>("ConnectionString"), ServerVersion.Parse("8.0.28-mysql"));
                break;

            default:
                builder.UseInMemoryDatabase("AppDB");
                builder.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning));
                break;
            }

            return(builder);
        }
Example #12
0
        /// <summary>
        /// Read in any values previously saved to permanent storage.
        /// </summary>
        public static void ReadFromCache()
        {
            ExceptionUtility.Try(() =>
            {
                if (FileUtility.FileExists(_filePath))
                {
                    LogUtility.LogMessage("Cache: restoring from file.");

                    string json    = FileUtility.ReadAllText(_filePath);
                    var cachedData = JsonUtility.Deserialize <JsonCacheObject>(json);

                    _cachedDevices.Clear();

                    if (cachedData != null)
                    {
                        ApplicationMetadata = cachedData.Metadata;
                        if (cachedData.ServerVersion != null)
                        {
                            _serverVersion = ServerVersion.Parse(cachedData.ServerVersion);
                        }

                        if (cachedData.Devices != null)
                        {
                            foreach (var device in cachedData.Devices)
                            {
                                AddOrUpdateInternal(device);
                            }
                        }

                        //get the command progresses
                        if (cachedData.Commands != null)
                        {
                            foreach (var command in cachedData.Commands)
                            {
                                _commandProgresses.AddOrUpdate(command.CommandId, (arg) => command, (arg1, arg2) => command);
                            }
                        }
                    }
                }
                else
                {
                    LogUtility.LogMessage("Cache: file not found.");
                }
            });
        }
Example #13
0
    /// <inheritdoc />
    public BotContext CreateDbContext(string[] args)
    {
        var config = new ConfigurationBuilder()
                     .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../Mmcc.Bot"))
                     .AddJsonFile("appsettings.Development.json")
                     .Build();

        // get connection string;
        var optionsBuilder = new DbContextOptionsBuilder <BotContext>();
        var boundConfig    = config.GetSection("MySql").Get <MySqlSettings>();
        var connString     =
            $"Server={boundConfig.ServerIp};Port={boundConfig.Port};Database={boundConfig.DatabaseName};Uid={boundConfig.Username};Pwd={boundConfig.Password};Allow User Variables=True";

        optionsBuilder.UseMySql(
            connString,
            ServerVersion.Parse("10.4.11-mariadb"),
            b => b.MigrationsAssembly("Mmcc.Bot.Database"));

        return(new BotContext(optionsBuilder.Options));
    }
Example #14
0
        public void Bug_exists_in_MySql57_or_higher_constant()
        {
            using var command   = Connection.CreateCommand();
            command.CommandText = @"
SELECT `od1`.`Constant`, `od1`.`OrderID`
FROM `Orders` AS `o`
LEFT JOIN (
    SELECT 'MyConstantValue' AS `Constant`, `od`.`OrderID`
    FROM `Order Details` AS `od`
) AS `od1` ON `o`.`OrderID` = `od1`.`OrderID`
ORDER BY `od1`.`OrderID`;";

            using var reader = command.ExecuteReader();
            while (reader.Read())
            {
                var constant = reader["Constant"];
                var expected = ServerVersion.Parse(Connection.ServerVersion).Supports.MySqlBug96947Workaround
                    ? (object)DBNull.Value
                    : "MyConstantValue";

                Assert.Equal(expected, constant);
            }
        }
Example #15
0
        public BlogDbContext CreateDbContext(string[] args)
        {
            var configuration = BuildConfiguration();

            var blogOptions      = new BlogOptions();
            var connectionString = configuration.GetConnectionString("Blog");

            configuration.GetSection("Blog").Bind(blogOptions);
            var builder = blogOptions.DbType switch
            {
                DbType.SqlServer => new DbContextOptionsBuilder <BlogDbContext>()
                .UseSqlServer(connectionString),
                DbType.MySQL => new DbContextOptionsBuilder <BlogDbContext>()
                .UseMySql(connectionString, ServerVersion.Parse(blogOptions.ServerVersion)),
                DbType.PostgreSql => new DbContextOptionsBuilder <BlogDbContext>()
                .UseNpgsql(connectionString),
                DbType.Oracle => new DbContextOptionsBuilder <BlogDbContext>()
                .UseOracle(connectionString),
                _ => new DbContextOptionsBuilder <BlogDbContext>()
                .UseSqlite(connectionString),
            };

            return(new BlogDbContext(builder.Options));
        }
Example #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <MedicalDBContext>(context =>
                                                     context.UseMySql("user id=MedicalDBAdmin;password=rabinovich490;host=192.168.1.48;database=MedicalDB;character set=utf8; ConvertZeroDatetime=True",
                                                                      ServerVersion.Parse("10.0.38-mariadb")));
            //"10.0.38-mariadb"
            services.AddControllers()
            .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
            .AddNewtonsoftJson(settings => settings.SerializerSettings.ContractResolver    = new CamelCasePropertyNamesContractResolver());
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddScoped <IUserRepo, SqlUserRepo>();
            services.AddScoped <ILogRepo, SqlLogRepo>();
            services.AddScoped <IAppointmentRepo, SqlAppointmentRepo>();
            services.AddScoped <IMedicationRepo, SqlMedicationRepo>();
            services.AddScoped <IConnectionRepo, SqlConnectionRepo>();
            services.AddScoped <IConnectionRequestRepo, SqlConnectionRequestRepo>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "MedicalAidAppWebApi", Version = "v1"
                });
            });
        }
Example #17
0
    public void ConfigureServices(IServiceCollection services)
    {
        // Configuration
        services.AddOptions <MoodleLtiOptions>().Bind(_configuration.GetSection(nameof(MoodleLtiOptions)));
        _mainOptions = _configuration.GetSection(nameof(MainOptions)).Get <MainOptions>();
        services.AddOptions <MainOptions>().Bind(_configuration.GetSection(nameof(MainOptions)));
        var dbOptions = _configuration.GetSection(nameof(CtfDbOptions)).Get <CtfDbOptions>();

        // Key persistence
        if (_mainOptions.SecretsDirectory != null)
        {
            services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo(_mainOptions.SecretsDirectory));
        }

        // Moodle connection
        services.AddHttpClient();
        services.AddMoodleLtiApi();
        services.AddMoodleGradebook();

        // Database
        services.AddDbContextPool <CtfDbContext>(options =>
        {
            options.UseMySql($"Server={dbOptions.Server};Database={dbOptions.Database};User={dbOptions.User};Password={dbOptions.Password};",
                             ServerVersion.Parse("10.5.8-mariadb"), mysqlOptions => mysqlOptions.EnableRetryOnFailure(3));
            if (_environment.IsDevelopment())
            {
                options.UseLoggerFactory(_debugLoggerFactory)
                .EnableSensitiveDataLogging();
            }
        });

        // Localization
        services.AddLocalization(options => options.ResourcesPath = "Resources");

        // Entity/Model mapping
        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

        // Memory cache
        services.AddMemoryCache();

        // Model/database services
        services.AddScoped <IUserService, UserService>();
        services.AddScoped <ISlotService, SlotService>();
        services.AddScoped <ILabService, LabService>();
        services.AddScoped <IExerciseService, ExerciseService>();
        services.AddScoped <IFlagService, FlagService>();
        services.AddScoped <ILabExecutionService, LabExecutionService>();
        services.AddScoped <IScoreboardService, ScoreboardService>();

        // Markdown parser
        services.AddSingleton <IMarkdownService, MarkdownService>();

        // Configuration service
        services.AddScoped <IConfigurationService, ConfigurationService>();

        // Export/sync services
        services.AddScoped <IMoodleService, MoodleService>();
        services.AddScoped <ICsvService, CsvService>();
        services.AddScoped <IDumpService, DumpService>();

        // Rate limiting
        services.AddSingleton <ILoginRateLimiter, LoginRateLimiter>();

        // Forward headers when used behind a proxy
        services.Configure <ForwardedHeadersOptions>(options =>
        {
            options.ForwardedHeaders = ForwardedHeaders.XForwardedProto;
        });

        // Change name of antiforgery cookie
        services.AddAntiforgery(options =>
        {
            options.Cookie.Name     = "ctf4e.antiforgery";
            options.Cookie.SameSite = SameSiteMode.Lax;
        });

        // Authentication
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(options =>
        {
            options.Cookie.Name      = "ctf4e.session";
            options.LoginPath        = "/auth";
            options.LogoutPath       = "/auth/logout";
            options.AccessDeniedPath = "/auth";
        });

        // Authorization
        services.AddSingleton <IAuthorizationHandler, UserPrivilegeHandler>();
        services.AddSingleton <IAuthorizationPolicyProvider, UserPrivilegePolicyProvider>();

        // Use MVC
        var mvcBuilder = services.AddControllersWithViews(_ =>
        {
        }).AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);

        // Development tools
        if (_mainOptions.DevelopmentMode)
        {
            // Add MiniProfiler
            services.AddMiniProfiler(options =>
            {
                // Put profiler results to dev route
                options.RouteBasePath = "/dev/profiler";
Example #18
0
 protected override void OnConfiguring(DbContextOptionsBuilder options)
 {
     options.UseMySql(ConnectionString, ServerVersion.Parse("8.0.20-mysql"), options => {
         options.EnableRetryOnFailure();
     });
 }
Example #19
0
 public void TestInvalidVersion(string input)
 {
     Assert.Throws <InvalidOperationException>(() => ServerVersion.Parse("unknown"));
 }
Example #20
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllers();
     services.AddDbContext <TapanyagContext>(options =>
                                             options.UseMySql(Configuration.GetConnectionString("TapanyagDB"), ServerVersion.Parse("10.4.21-mariadb")));
     //services.AddCors(c =>
     //{
     //    c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
     //});
 }
Example #21
0
        public static void ConfigureServices(WebApplicationBuilder builder)
        {
            var services = builder.Services;

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", builder =>
                {
                    builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .SetIsOriginAllowed(_ => true)
                    .AllowCredentials()
                    .WithOrigins(
                        "https://www.valour.gg",
                        "http://www.valour.gg",
                        "https://valour.gg",
                        "http://valour.gg",
                        "https://api.valour.gg",
                        "http://api.valour.gg",
                        "http://localhost:3000",
                        "https://localhost:3000",
                        "http://localhost:3001",
                        "https://localhost:3001");
                });
            });

            services.AddSignalR();

            var mapConfig = new MapperConfiguration(x =>
            {
                x.AddProfile(new MappingProfile());
            });

            IMapper mapper = mapConfig.CreateMapper();

            services.AddSingleton(mapper);

            services.AddHttpClient();

            MappingManager.Mapper = mapper;

            services.AddDbContextPool <ValourDB>(options =>
            {
                options.UseMySql(ValourDB.ConnectionString, ServerVersion.Parse("8.0.20-mysql"), options => options.EnableRetryOnFailure());
            });

            // This probably needs to be customized further but the documentation changed
            services.AddAuthentication().AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);

            // Adds user manager to dependency injection
            services.AddScoped <UserManager>();
            IdManager idManager = new();

            services.AddSingleton(idManager);
            services.AddSingleton <WebPushClient>();
            services.AddControllersWithViews().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
                //options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
                options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;

                options.JsonSerializerOptions.PropertyNamingPolicy = null;
            }
                                                              );
            services.AddRazorPages();
            services.AddHostedService <MessageCacheWorker>();
            services.AddHostedService <PlanetMessageWorker>();
            services.AddHostedService <StatWorker>();

            services.AddEndpointsApiExplorer();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Valour API", Description = "The official Valour API", Version = "v1.0"
                });
                c.AddSecurityDefinition("Token", new OpenApiSecurityScheme()
                {
                    Description = "The token used for authorizing your account.",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey,
                    Scheme      = "Token"
                });
            });
        }
Example #22
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddDbContext <Database.DB>(opt => opt.UseMySql(GetConnectionString(), ServerVersion.Parse("10.3.0-mariadb")));
     services.AddMvc();
 }
Example #23
0
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
     optionsBuilder.UseMySql($"server={Server};port={Port};database={ServerInfo.Database};user={User};pwd={Password};SslMode=VerifyCA;",
                             ServerVersion.Parse("5.7.34-mysql"),
                             options => options.EnableRetryOnFailure());
 }
Example #24
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureLogging((context, builder) =>
        {
            if (context.HostingEnvironment.IsDevelopment())
            {
                builder.AddDebug();
            }
        })
        .ConfigureServices((hostContext, services) =>
        {
            // add config;
            services.AddConfigWithValidation <MySqlSettings, MySqlSettingsValidator>(
                hostContext.Configuration.GetSection("MySql"));
            services.AddConfigWithValidation <DiscordSettings, DiscordSettingsValidator>(
                hostContext.Configuration.GetSection("Discord"));
            services.AddConfigWithValidation <PolychatSettings, PolychatSettingsValidator>(
                hostContext.Configuration.GetSection("Polychat"));

            services.Configure <DiscordGatewayClientOptions>(options =>
            {
                options.Intents =
                    GatewayIntents.Guilds
                    | GatewayIntents.DirectMessages
                    | GatewayIntents.GuildMembers
                    | GatewayIntents.GuildBans
                    | GatewayIntents.GuildMessages
                    | GatewayIntents.GuildMessageReactions;
            });

            services.AddDbContext <BotContext>((provider, options) =>
            {
                var dbConfig      = provider.GetRequiredService <MySqlSettings>();
                var connString    = dbConfig.ConnectionString;
                var serverVersion = ServerVersion.Parse(dbConfig.MySqlVersionString);
                var retryAmount   = dbConfig.RetryAmount;

                options.UseMySql(connString, serverVersion,
                                 contextOptions => contextOptions.EnableRetryOnFailure(retryAmount));
            });

            services.AddSingleton <IColourPalette, TailwindColourPalette>();
            services.AddSingleton <IButtonHandlerRepository, ButtonHandlerRepository>();

            services.AddScoped <IDiscordSanitiserService, DiscordSanitiserService>();
            services.AddScoped <IHelpService, HelpService>();
            services.AddScoped <IDmSender, DmSender>();
            services.AddScoped <IDiscordPermissionsService, DiscordPermissionsService>();
            services.AddScoped <IExecutionEventService, ErrorNotificationMiddleware>();
            services.AddScoped <IMojangApiService, MojangApiService>();
            services.AddScoped <ICommandResponder, CommandResponder>();
            services.AddScoped <IInteractionResponder, InteractionResponder>();

            services.AddValidatorsFromAssemblyContaining <Program>();
            services.AddValidatorsFromAssemblyContaining <DiscordSettings>();
            services.AddValidatorsFromAssemblyContaining <PolychatSettings>();
            services.AddValidatorsFromAssemblyContaining <MySqlSettingsValidator>();

            services.AddMediatR(typeof(CreateFromDiscordMessage), typeof(TcpRequest <>));
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(ValidationBehaviour <,>));

            services.AddDiscordCommands();

            services.AddCondition <RequireGuildCondition>();
            services.AddCondition <RequireUserGuildPermissionCondition>();

            services.AddParser <TimeSpan, TimeSpanParser>();
            services.AddParser <ExpiryDate, ExpiryDateParser>();

            // core commands;
            services.AddCommandGroup <HelpCommands>();
            services.AddCommandGroup <GuildCommands>();
            services.AddCommandGroup <MmccInfoCommands>();

            // tags;
            services.AddCommandGroup <TagsManagementCommands>();
            services.AddCommandGroup <TagsUsageCommands>();

            // diagnostics;
            services.AddCommandGroup <DiagnosticsCommands>();

            // in game;
            services.AddCommandGroup <MinecraftServersCommands>();

            // member apps;
            services.AddCommandGroup <MemberApplicationsCommands>();

            // moderation;
            services.AddCommandGroup <GeneralModerationCommands>();
            services.AddCommandGroup <PlayerInfoCommands>();
            services.AddCommandGroup <BanCommands>();
            services.AddCommandGroup <WarnCommands>();

            services.AddResponder <GuildCreatedResponder>();
            services.AddResponder <UserJoinedResponder>();
            services.AddResponder <UserLeftResponder>();
            services.AddResponder <FeedbackPostedResponder>();
            services.AddResponder <FeedbackAddressedResponder>();
            services.AddResponder <MemberApplicationCreatedResponder>();
            services.AddResponder <MemberApplicationUpdatedResponder>();
            services.AddResponder <DiscordChatMessageForwarder>();

            services.AddDiscordGateway(provider =>
            {
                var discordConfig = provider.GetRequiredService <DiscordSettings>();
                return(discordConfig.Token);
            });
            services.AddDiscordCaching();

            // set up Ssmp central server;
            var ssmpConfig = hostContext.Configuration.GetSection("Ssmp");
            services.AddSsmp <SsmpHandler>(ssmpConfig);

            // set up Polychat2;
            services.AddSingleton <IPolychatService, PolychatService>();
            services.AddHostedService <BroadcastsHostedService>();

            services.AddHostedService <DiscordService>();
            services.AddHostedService <ModerationBackgroundService>();

            services.AddResponder <ButtonInteractionCreateResponder>();
        })
        .UseDefaultServiceProvider(options => options.ValidateScopes = true)
        .UseSerilog();
Example #25
0
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
                optionsBuilder.UseMySql("user id=MedicalDBAdmin;password=rabinovich490;host=192.168.1.48;database=MedicalDB;character set=utf8", ServerVersion.Parse("10.0.38-mariadb"));
            }
        }