Пример #1
0
        public void CheckIfBuiltTypeIsClass()
        {
            DbContextBuilder contextBuilder = new DbContextBuilder();
            Type             dbContextType  = contextBuilder.Build();

            Assert.True(dbContextType.IsClass);
        }
Пример #2
0
    public void ConfigureServices(IServiceCollection services)
    {
        GraphTypeTypeRegistry.Register <Employee, EmployeeGraph>();
        GraphTypeTypeRegistry.Register <EmployeeSummary, EmployeeSummaryGraph>();
        GraphTypeTypeRegistry.Register <Company, CompanyGraph>();

        services.AddScoped(provider => DbContextBuilder.BuildDbContext());

        EfGraphQLConventions.RegisterInContainer(
            services,
            DbContextBuilder.BuildDbContext(),
            userContext => (GraphQlEfSampleDbContext)userContext);

        foreach (var type in GetGraphQlTypes())
        {
            services.AddSingleton(type);
        }

        services.AddGraphQL(options => options.ExposeExceptions = true).AddWebSockets();
        services.AddSingleton <ContextFactory>();
        services.AddSingleton <IDocumentExecuter, EfDocumentExecuter>();
        services.AddSingleton <IDependencyResolver>(
            provider => new FuncDependencyResolver(provider.GetRequiredService));
        services.AddSingleton <ISchema, Schema>();
        var mvc = services.AddMvc();

        mvc.SetCompatibilityVersion(CompatibilityVersion.Latest);
    }
Пример #3
0
        public static DbContextBuilder <TDbContext> AddNpgsqlDbOperationLogChangeTracking <TDbContext>(
            this DbContextBuilder <TDbContext> dbContextBuilder,
            Action <IServiceProvider, NpgsqlDbOperationLogChangeTrackingOptions <TDbContext> >?configureOptions = null)
            where TDbContext : DbContext
        {
            var services = dbContextBuilder.Services;

            services.TryAddSingleton(c => {
                var options = new NpgsqlDbOperationLogChangeTrackingOptions <TDbContext>();
                configureOptions?.Invoke(c, options);
                return(options);
            });

            // NpgsqlDbOperationLogChangeTracker<TDbContext>
            services.TryAddSingleton <NpgsqlDbOperationLogChangeTracker <TDbContext> >();
            services.AddHostedService(c =>
                                      c.GetRequiredService <NpgsqlDbOperationLogChangeTracker <TDbContext> >());
            services.TryAddSingleton <IDbOperationLogChangeTracker <TDbContext> >(c =>
                                                                                  c.GetRequiredService <NpgsqlDbOperationLogChangeTracker <TDbContext> >());

            // NpgsqlDbOperationLogChangeNotifier<TDbContext>
            services.TryAddEnumerable(
                ServiceDescriptor.Singleton <
                    IOperationCompletionListener,
                    NpgsqlDbOperationLogChangeNotifier <TDbContext> >());
            return(dbContextBuilder);
        }
Пример #4
0
 public RatelimitService(DbContextBuilder dbb, LoggingService ls, SchedulingService ss, GuildConfigService gcs)
     : base(dbb, ls, ss, gcs, "_gf: Ratelimit hit")
 {
     this.guildExempts       = new ConcurrentDictionary <ulong, ConcurrentHashSet <ExemptedEntity> >();
     this.guildRatelimitInfo = new ConcurrentDictionary <ulong, ConcurrentDictionary <ulong, UserRatelimitInfo> >();
     this.refreshTimer       = new Timer(RefreshCallback, this, TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(20));
 }
Пример #5
0
        public void GetContextFileText_passed_normal_entity_creates_expected_text()
        {
            var classNamespace = "Infrastructure.Persistence.Contexts";
            var template       = CannedGenerator.FakeBasicApiTemplate();

            var fileText = DbContextBuilder.GetContextFileText(classNamespace, template);

            var expectedText = @"namespace Infrastructure.Persistence.Contexts
{
    using Application.Interfaces;
    using Domain.Entities;
    using Domain.Common;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.ChangeTracking;
    using System.Threading;
    using System.Threading.Tasks;

    public class BespokedBikesDbContext : DbContext
    {
        public BespokedBikesDbContext(
            DbContextOptions<BespokedBikesDbContext> options) : base(options) 
        {
        }

        #region DbSet Region - Do Not Delete
        public DbSet<Product> Products { get; set; }
        #endregion
    }
}";

            fileText.Should().Be(expectedText);
        }
Пример #6
0
        internal static async Task Main(string[] _)
        {
            PrintBuildInformation();

            try {
                BotConfigService cfg = await LoadBotConfigAsync();

                Log.Logger = LogExt.CreateLogger(cfg.CurrentConfiguration);
                Log.Information("Logger created.");

                DbContextBuilder dbb = await InitializeDatabaseAsync(cfg);

                await StartAsync(cfg, dbb);

                Log.Information("Booting complete!");

                CancellationToken token = Bot?.Services.GetRequiredService <BotActivityService>().MainLoopCts.Token
                                          ?? throw new InvalidOperationException("Bot not initialized");
                await Task.Delay(Timeout.Infinite, token);
            } catch (TaskCanceledException) {
                Log.Information("Shutdown signal received!");
            } catch (Exception e) {
                Log.Fatal(e, "Critical exception occurred");
                Environment.ExitCode = 1;
            } finally {
                await DisposeAsync();
            }

            Log.Information("Powering off");
            Log.CloseAndFlush();
            Environment.Exit(Environment.ExitCode);
        }
Пример #7
0
        public void AddModel <TModelConfig>() where TModelConfig : IModelConfig, new()
        {
            var config = new TModelConfig();

            DbContextBuilder.Config(config.BuildModel);
            DbContextBuilder.Seed(config.BuildSeedData);
        }
        public static async Task InitializeAsync <T>(
            IConfigurationRoot config,
            string migrationPath,
            string connectionKey = AzureSqlConstants.AzureSqlConnectionKey)
            where T : DbContext
        {
            Console.WriteLine("Start migration...");

            try
            {
                using (T context = DbContextBuilder.Build <T>(config, migrationPath, connectionKey))
                {
                    await context.Database.MigrateAsync();

                    await context.Database.ExecuteSqlRawAsync(File.ReadAllText(AzureSqlConstants.PrivateChatView));

                    await context.Database.EnsureCreatedAsync();
                }

                Console.WriteLine("End migration...");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
                throw;
            }
        }
Пример #9
0
 public FilteringService(DbContextBuilder dbb, bool loadData = true)
 {
     this.dbb = dbb;
     this.filters = new ConcurrentDictionary<ulong, ConcurrentHashSet<Filter>>();
     if (loadData)
         this.LoadData();
 }
Пример #10
0
 public AntiMentionService(DbContextBuilder dbb, LoggingService ls, SchedulingService ss, GuildConfigService gcs)
     : base(dbb, ls, ss, gcs, "_gf: Anti-mention")
 {
     this.guildExempts     = new ConcurrentDictionary <ulong, ConcurrentHashSet <ExemptedEntity> >();
     this.guildMentionInfo = new ConcurrentDictionary <ulong, ConcurrentDictionary <ulong, UserMentionInfo> >();
     this.refreshTimer     = new Timer(RefreshCallback, this, TimeSpan.FromMinutes(3), TimeSpan.FromMinutes(3));
 }
Пример #11
0
    public void ConfigureServices(IServiceCollection services)
    {
        GraphTypeTypeRegistry.Register <Employee, EmployeeGraph>();
        GraphTypeTypeRegistry.Register <EmployeeSummary, EmployeeSummaryGraph>();
        GraphTypeTypeRegistry.Register <Company, CompanyGraph>();
        EfGraphQLConventions.RegisterInContainer <SampleDbContext>(
            services,
            model: SampleDbContext.StaticModel);
        EfGraphQLConventions.RegisterConnectionTypesInContainer(services);

        foreach (var type in GetGraphQlTypes())
        {
            services.AddSingleton(type);
        }
        //TODO: re add for subscriptions
        //var graphQl = services.AddGraphQL(
        //    options => options.ExposeExceptions = true);
        //graphQl.AddWebSockets();

        var dbContextBuilder = new DbContextBuilder();

        services.AddSingleton <IHostedService>(dbContextBuilder);
        services.AddSingleton <Func <SampleDbContext> >(_ => dbContextBuilder.BuildDbContext);
        services.AddScoped(_ => dbContextBuilder.BuildDbContext());
        services.AddSingleton <IDocumentExecuter, EfDocumentExecuter>();
        services.AddSingleton <ISchema, Schema>();
        var mvc = services.AddMvc(option => option.EnableEndpointRouting = false);

        mvc.SetCompatibilityVersion(CompatibilityVersion.Latest);
        mvc.AddNewtonsoftJson();
    }
Пример #12
0
        public void CheckIfBuiltTypeHasValidParent()
        {
            DbContextBuilder contextBuilder = new DbContextBuilder();
            Type             dbContextType  = contextBuilder.Build();

            Assert.Equal(typeof(ConfigurableDbContext), dbContextType.BaseType);
        }
Пример #13
0
    public void ConfigureServices(IServiceCollection services)
    {
        GraphTypeTypeRegistry.Register <Employee, EmployeeGraph>();
        GraphTypeTypeRegistry.Register <EmployeeSummary, EmployeeSummaryGraph>();
        GraphTypeTypeRegistry.Register <Company, CompanyGraph>();
        services.AddScoped(_ => DbContextBuilder.BuildDbContext());
        EfGraphQLConventions.RegisterInContainer <GraphQlEfSampleDbContext>(
            services,
            model: GraphQlEfSampleDbContext.StaticModel);
        EfGraphQLConventions.RegisterConnectionTypesInContainer(services);

        foreach (var type in GetGraphQlTypes())
        {
            services.AddSingleton(type);
        }

        var graphQl = services.AddGraphQL(
            options => options.ExposeExceptions = true);

        graphQl.AddWebSockets();
        services.AddSingleton <ContextFactory>();
        services.AddSingleton <IDocumentExecuter, EfDocumentExecuter>();
        services.AddSingleton <IDependencyResolver>(
            provider => new FuncDependencyResolver(provider.GetRequiredService));
        services.AddSingleton <ISchema, Schema>();
        var mvc = services.AddMvc(option => option.EnableEndpointRouting = false);

        mvc.SetCompatibilityVersion(CompatibilityVersion.Latest);
        mvc.AddNewtonsoftJson();
    }
Пример #14
0
 public BackupService(DbContextBuilder dbb, GuildConfigService gcs)
 {
     this.dbb     = dbb;
     this.gcs     = gcs;
     this.streams = new();
     this.LoadData();
 }
Пример #15
0
        public void TestInsertAsync()
        {
            var builder = new DbContextBuilder
            {
                Connection = new MySqlConnection("server=127.0.0.1;user id=root;password=1024;database=test;"),
            };

            GlobalSettings.XmlCommandsProvider.Load(@"D:\SqlBatis\src\SqlBatis.Test\Student.xml");
            try
            {
                var sql       = "insert into advert_banners(banner_img,banner_sort,banner_group) values(@img,@sort,@group)";
                var list      = new List <int>();
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                for (int i = 0; i < 30; i++)
                {
                    Regex.IsMatch(sql, $@"([\@,\:,\?]+{"fff"})");
                }
                stopwatch.Stop();
                list = list.Distinct().ToList();
                Debug.Write("ºÄʱ£º" + stopwatch.ElapsedMilliseconds);
                using (var db = new DbContext(builder))
                {
                    var ff = db.Execute("insert into advert_banners(banner_img,banner_sort,banner_group) values(@img,@sort,@group)", new { img = (string)null, sort = 20, group = 1 });
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
Пример #16
0
        public void SetUp()
        {
            DbContextBuilder<DbContext> builder = new DbContextBuilder<DbContext>("DefaultDb", new[] { "Infrastructure.Tests" }, true, true);
            var context = ((IEFContextFactory<DbContext>)builder).Create();

            customerRepository = new CustomerRepository(context);
            genericRepository = new GenericRepository(context);
        }
Пример #17
0
        public void SetUp()
        {
            DbContextBuilder<DbContext> builder = new DbContextBuilder<DbContext>("DefaultDb", new[] { "QV.Tests" }, true, true);
            context = builder.BuildDbContext();

            customerRepository = new QV.Tests.Data.Lab.CustomerRepository(context);
            repository = new QV.Data.EntityFramework.Lab.GenericRepository(context);
        }
Пример #18
0
        public void SetUp()
        {
            DbContextBuilder <DbContext> builder = new DbContextBuilder <DbContext>("DefaultDb", new[] { "Infrastructure.Tests" }, true, true);
            var context = ((IEFContextFactory <DbContext>)builder).Create();

            customerRepository = new CustomerRepository(context);
            genericRepository  = new GenericRepository(context);
        }
Пример #19
0
        public void CheckIfEntityTypeIncluded()
        {
            Type             includedEntityType = typeof(object);
            DbContextBuilder contextBuilder     = new DbContextBuilder()
                                                  .WithEntity(includedEntityType);

            Assert.Contains(includedEntityType, contextBuilder.RegisteredEntities);
        }
Пример #20
0
 protected ProtectionService(DbContextBuilder dbb, LoggingService ls, SchedulingService ss, GuildConfigService gcs, string reason)
 {
     this.dbb    = dbb;
     this.ss     = ss;
     this.ls     = ls;
     this.gcs    = gcs;
     this.reason = reason;
 }
Пример #21
0
        public void SetUp()
        {
            var builder = new DbContextBuilder<DbContext>("DefaultDb", new[] { "Infrastructure.Tests" }, true, true);
            this.context = builder.BuildDbContext();

            this.customerRepository = new CustomerRepository(this.context);
            this.repository = new GenericRepository(this.context);
        }
        public static RestOptionsBuilder AddRest(this IServiceCollection services, DbContextBuilder contextBuilder)
        {
            services.AddDbContext(contextBuilder);
            IEnumerable <Type> restModelTypes = contextBuilder.RegisteredEntities
                                                .Where(t => t.IsRestModel());

            return(services.RegisterRestModelTypes(restModelTypes));
        }
Пример #23
0
        public void SetUp()
        {
            DbContextBuilder <DbContext> builder = new DbContextBuilder <DbContext>("DefaultDb", new[] { "Infrastructure.Tests" }, true, true);

            context = builder.BuildDbContext();

            customerRepository = new CustomerRepository(context);
            repository         = new GenericRepository(context);
        }
Пример #24
0
        public void SetUp()
        {
            DbContextBuilder <DbContext> builder = new DbContextBuilder <DbContext>("DefaultDb", new[] { "Infrastructure.Tests" }, true, true);

            context = builder.BuildDbContext();

            customerRepository = new Infrastructure.Tests.Data.Lab.CustomerRepository(context);
            repository         = new Infrastructure.Data.EntityFramework.Lab.GenericRepository(context);
        }
Пример #25
0
        private static void RunTemplateBuilders(string solutionDirectory, ApiTemplate template, IFileSystem fileSystem)
        {
            // dbcontext
            DbContextBuilder.CreateDbContext(solutionDirectory, template.Entities, template.DbContext.ContextName, template.DbContext.Provider, template.DbContext.DatabaseName);

            //entities
            foreach (var entity in template.Entities)
            {
                EntityBuilder.CreateEntity(solutionDirectory, entity, fileSystem);
                DtoBuilder.CreateDtos(solutionDirectory, entity);

                RepositoryBuilder.AddRepository(solutionDirectory, entity, template.DbContext);
                ValidatorBuilder.CreateValidators(solutionDirectory, entity);
                ProfileBuilder.CreateProfile(solutionDirectory, entity);

                ControllerBuilder.CreateController(solutionDirectory, entity, template.SwaggerConfig.AddSwaggerComments, template.AuthorizationSettings.Policies);

                FakesBuilder.CreateFakes(solutionDirectory, template.SolutionName, entity);
                ReadTestBuilder.CreateEntityReadTests(solutionDirectory, template.SolutionName, entity, template.DbContext.ContextName);
                GetTestBuilder.CreateEntityGetTests(solutionDirectory, template.SolutionName, entity, template.DbContext.ContextName, template.AuthorizationSettings.Policies);
                PostTestBuilder.CreateEntityWriteTests(solutionDirectory, entity, template.SolutionName, template.AuthorizationSettings.Policies);
                UpdateTestBuilder.CreateEntityUpdateTests(solutionDirectory, entity, template.SolutionName, template.DbContext.ContextName, template.AuthorizationSettings.Policies);
                DeleteIntegrationTestBuilder.CreateEntityDeleteTests(solutionDirectory, entity, template.SolutionName, template.DbContext.ContextName, template.AuthorizationSettings.Policies);
                DeleteTestBuilder.DeleteEntityWriteTests(solutionDirectory, entity, template.SolutionName, template.DbContext.ContextName);
                WebAppFactoryBuilder.CreateWebAppFactory(solutionDirectory, template.SolutionName, template.DbContext.ContextName, template.AddJwtAuthentication);
            }

            // environments
            Utilities.AddStartupEnvironmentsWithServices(
                solutionDirectory,
                template.SolutionName,
                template.DbContext.DatabaseName,
                template.Environments,
                template.SwaggerConfig,
                template.Port,
                template.AddJwtAuthentication
                );

            //seeders
            SeederBuilder.AddSeeders(solutionDirectory, template.Entities, template.DbContext.ContextName);

            //services
            SwaggerBuilder.AddSwagger(solutionDirectory, template.SwaggerConfig, template.SolutionName, template.AddJwtAuthentication, template.AuthorizationSettings.Policies);

            if (template.AddJwtAuthentication)
            {
                InfrastructureIdentityServiceRegistrationBuilder.CreateInfrastructureIdentityServiceExtension(solutionDirectory, template.AuthorizationSettings.Policies, fileSystem);
            }

            //final
            ReadmeBuilder.CreateReadme(solutionDirectory, template.SolutionName, fileSystem);

            if (template.AddGit)
            {
                GitSetup(solutionDirectory);
            }
        }
Пример #26
0
    public static async Task Main()
    {
        await DbContextBuilder.Start();

        var webHostBuilder = WebHost.CreateDefaultBuilder();
        var hostBuilder    = webHostBuilder.UseStartup <Startup>();

        hostBuilder.Build().Run();
    }
Пример #27
0
        public static IServiceCollection AddDbContexts(this IServiceCollection services, Action <DbContextBuilder> builder)
        {
            InitDbContextDir();
            var dbContextBuilder = new DbContextBuilder();

            builder?.Invoke(dbContextBuilder);
            services.AddScoped <DBContextFactory>();
            return(services);
        }
Пример #28
0
        public OnlineChatServiceDbContext CreateDbContext(string[] args)
        {
            IConfigurationRoot config = ConfigurationBuilderHelper.Create(Directory.GetCurrentDirectory());

            return(DbContextBuilder.Build <OnlineChatServiceDbContext>(
                       config,
                       "OCS.DAL.EF.Migrations",
                       AzureSqlConstants.AzureSqlConnectionKey));
        }
Пример #29
0
        public void CheckIfExceptionThrownOnNullEntityType()
        {
            DbContextBuilder contextBuilder = new DbContextBuilder();

            Assert.Throws <ArgumentNullException>(() =>
            {
                contextBuilder.WithEntity(null);
            });
        }
Пример #30
0
        public void CheckIfExceptionThrownOnNonClassEntityType()
        {
            DbContextBuilder contextBuilder = new DbContextBuilder();

            Assert.Throws <ArgumentException>(() =>
            {
                contextBuilder.WithEntity(typeof(int));
            });
        }
Пример #31
0
        public void CheckIfExceptionThrownOnNullModelCreator()
        {
            DbContextBuilder contextBuilder = new DbContextBuilder();

            Assert.Throws <ArgumentNullException>(() =>
            {
                contextBuilder.WithOnModelCreating((IDbContextModelCreator)null);
            });
        }
Пример #32
0
        public PaymentDbContext CreateDbContext(string[] args)
        {
            IConfigurationRoot config = Shared.Utils.Initialization.ConfigurationBuilder
                                        .Create(Directory.GetCurrentDirectory());

            return(DbContextBuilder.Build <PaymentDbContext>(
                       config,
                       "GSP.Payment.Data.Migrations",
                       SettingKeyConstants.AzureSqlConnectionKey));
        }
Пример #33
0
 public ReactionsService(DbContextBuilder dbb, bool loadData = true)
 {
     this.dbb        = dbb;
     this.ereactions = new ConcurrentDictionary <ulong, ConcurrentHashSet <EmojiReaction> >();
     this.treactions = new ConcurrentDictionary <ulong, ConcurrentHashSet <TextReaction> >();
     if (loadData)
     {
         this.LoadData();
     }
 }
Пример #34
0
        public static void Init(string connectionStringName)
        {
            DbContextBuilders = new Dictionary<string, IDbContextBuilder<IDbContext>>();

            lock (SyncLock)
            {
                if (DbContextBuilders.ContainsKey(connectionStringName))
                {
                    DbContextBuilders[connectionStringName] = new DbContextBuilder<IDbContext>(connectionStringName);
                }
                else
                {
                    DbContextBuilders.Add(connectionStringName,
                        new DbContextBuilder<IDbContext>(connectionStringName));
                }
            }
        }
 private DbContext()
 {
     this.builder = new DbContextBuilder(this);
 }