public static void DefaultFactoryCreatesSqlConnections() { var factory = new DbConnectionFactory(LocalDbConnection); var connection = factory.CreateConnection(); Assert.IsType<SqlConnection>(connection); }
public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint) { IServiceCollection tenantServiceCollection = _serviceProvider.CreateChildContainer(_applicationServices); tenantServiceCollection.AddSingleton(settings); tenantServiceCollection.AddSingleton(blueprint.Descriptor); tenantServiceCollection.AddSingleton(blueprint); // Sure this is right? tenantServiceCollection.AddSingleton(_loggerFactory); foreach (var dependency in blueprint.Dependencies .Where(t => !typeof(IModule).IsAssignableFrom(t.Type))) { foreach (var interfaceType in dependency.Type.GetInterfaces()) { // GetInterfaces returns the full hierarchy of interfaces if (interfaceType == typeof(ISingletonDependency) || interfaceType == typeof(ITransientDependency) || interfaceType == typeof(IDependency) || !typeof(IDependency).IsAssignableFrom(interfaceType)) { continue; } if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType); } if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) { tenantServiceCollection.AddSingleton(interfaceType, dependency.Type); } else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType)) { tenantServiceCollection.AddTransient(interfaceType, dependency.Type); } else if (typeof(IDependency).IsAssignableFrom(interfaceType)) { tenantServiceCollection.AddScoped(interfaceType, dependency.Type); } } } // Register components foreach (var dependency in blueprint.Dependencies) { var serviceComponentAttribute = dependency.Type.GetTypeInfo().GetCustomAttribute <ServiceScopeAttribute>(); if (serviceComponentAttribute != null) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, serviceComponentAttribute.ServiceType); } serviceComponentAttribute.Register(tenantServiceCollection, dependency.Type); } } // Configure event handlers, they are not part of the blueprint, so they have // to be added manually. Or need to create a module for this. tenantServiceCollection.AddScoped <IEventBus, DefaultOrchardEventBus>(); tenantServiceCollection.AddSingleton <IEventBusState, EventBusState>(); //// Apply custom options for the tenant //var options = blueprint //.Dependencies //.Where(x => typeof(IConfigure).IsAssignableFrom(x.Type)) //.Select(x => x.Type).ToArray(); //// TODO: Group all options by type and reuse the same configuration object //// such that multiple feature can update the same configuration object. //foreach (var type in options) //{ // var optionType = type // .GetInterfaces() // .Where(x => typeof(IConfigure).IsAssignableFrom(x)) // .FirstOrDefault() // .GetGenericArguments() // .FirstOrDefault(); // if(optionType == null) // { // // Ignore non-generic implementation // continue; // } // var optionObject = Activator.CreateInstance(optionType); // var configureMethod = type.GetMethod("Configure"); // var optionHost = Activator.CreateInstance(type); // configureMethod.Invoke(optionHost, new[] { optionObject }); // tenantServiceCollection.ConfigureOptions(optionObject); //} // Configuring data access var indexes = blueprint .Dependencies .Where(x => typeof(IIndexProvider).IsAssignableFrom(x.Type)) .Select(x => x.Type).ToArray(); if (settings.DatabaseProvider != null) { var store = new Store(cfg => { // @"Data Source =.; Initial Catalog = test1; User Id=sa;Password=demo123!" IConnectionFactory connectionFactory = null; switch (settings.DatabaseProvider) { case "SqlConnection": connectionFactory = new DbConnectionFactory <SqlConnection>(settings.ConnectionString); break; //case "SqliteConnection": // connectionFactory = new DbConnectionFactory<SqliteConnection>(settings.ConnectionString); // break; default: throw new ArgumentException("Unknown database provider: " + settings.DatabaseProvider); } cfg.ConnectionFactory = connectionFactory; cfg.IsolationLevel = IsolationLevel.ReadUncommitted; if (!String.IsNullOrWhiteSpace(settings.TablePrefix)) { cfg.TablePrefix = settings.TablePrefix + "_"; } #if SQL var sqlFactory = new SqlDocumentStorageFactory(connectionFactory); sqlFactory.IsolationLevel = IsolationLevel.ReadUncommitted; sqlFactory.ConnectionFactory = connectionFactory; if (!String.IsNullOrWhiteSpace(settings.TablePrefix)) { sqlFactory.TablePrefix = settings.TablePrefix + "_"; } cfg.DocumentStorageFactory = sqlFactory; #else var storageFactory = new LightningDocumentStorageFactory(Path.Combine(_appDataFolderRoot.RootFolder, "Sites", settings.Name, "Documents")); cfg.DocumentStorageFactory = storageFactory; #endif //cfg.RunDefaultMigration(); } ); var idGenerator = new LinearBlockIdGenerator(store.Configuration.ConnectionFactory, 20, "contentitem", store.Configuration.TablePrefix); store.RegisterIndexes(indexes); tenantServiceCollection.AddSingleton <IStore>(store); tenantServiceCollection.AddSingleton <LinearBlockIdGenerator>(idGenerator); tenantServiceCollection.AddScoped <ISession>(serviceProvider => store.CreateSession() ); } IServiceCollection moduleServiceCollection = _serviceProvider.CreateChildContainer(_applicationServices); foreach (var dependency in blueprint.Dependencies .Where(t => typeof(IModule).IsAssignableFrom(t.Type))) { moduleServiceCollection.AddSingleton(typeof(IModule), dependency.Type); } var moduleServiceProvider = moduleServiceCollection.BuildServiceProvider(); // Let any module add custom service descriptors to the tenant foreach (var service in moduleServiceProvider.GetServices <IModule>()) { service.Configure(tenantServiceCollection); } // Register event handlers on the event bus var eventHandlers = tenantServiceCollection .Select(x => x.ImplementationType) .Distinct() .Where(t => t != null && typeof(IEventHandler).IsAssignableFrom(t) && t.GetTypeInfo().IsClass) .ToArray(); foreach (var handlerClass in eventHandlers) { tenantServiceCollection.AddScoped(handlerClass); // Register dynamic proxies to intercept direct calls if an IEventHandler is resolved, dispatching the call to // the event bus. foreach (var i in handlerClass.GetInterfaces().Where(t => typeof(IEventHandler).IsAssignableFrom(t))) { tenantServiceCollection.AddScoped(i, serviceProvider => { var proxy = DefaultOrchardEventBus.CreateProxy(i); proxy.EventBus = serviceProvider.GetService <IEventBus>(); return(proxy); }); } } var shellServiceProvider = tenantServiceCollection.BuildServiceProvider(); var eventBusState = shellServiceProvider.GetService <IEventBusState>(); // Register any IEventHandler method in the event bus foreach (var handlerClass in eventHandlers) { foreach (var handlerInterface in handlerClass.GetInterfaces().Where(x => typeof(IEventHandler).IsAssignableFrom(x) && typeof(IEventHandler) != x)) { foreach (var interfaceMethod in handlerInterface.GetMethods()) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug($"{handlerClass.Name}/{handlerInterface.Name}.{interfaceMethod.Name}"); } //var classMethod = handlerClass.GetMethods().Where(x => x.Name == interfaceMethod.Name && x.GetParameters().Length == interfaceMethod.GetParameters().Length).FirstOrDefault(); Func <IServiceProvider, IDictionary <string, object>, Task> d = (sp, parameters) => DefaultOrchardEventBus.Invoke(sp, parameters, interfaceMethod, handlerClass); eventBusState.Add(handlerInterface.Name + "." + interfaceMethod.Name, d); } } } return(shellServiceProvider); }
public static void ValidateCachesException() { var exception = Substitute.For<DbException>(); var invalidConnection = Substitute.For<IDbConnection>(); invalidConnection .When(x => x.Open()) .Do(x => { throw exception; }); var factory = new DbConnectionFactory(LocalDbConnection, c => invalidConnection); try { factory.Validate(); } catch (DbException) { } try { // This should cache the result and not call open. factory.Validate(); } catch (DbException) { } invalidConnection.Received(1).Open(); }
public PKEventHandler(ProxyService proxy, ILogger logger, IMetrics metrics, IDiscordClient client, DbConnectionFactory connectionFactory, IServiceProvider services, CommandTree tree) { _proxy = proxy; _logger = logger; _metrics = metrics; _client = (DiscordShardedClient)client; _connectionFactory = connectionFactory; _services = services; _tree = tree; }
public SystemController(IDataStore data, DbConnectionFactory conn, TokenAuthService auth) { _data = data; _conn = conn; _auth = auth; }
public ProxyCacheService(DbConnectionFactory conn, IMemoryCache cache, ILogger logger) { _conn = conn; _cache = cache; _logger = logger; }
public DbConnection GetDbConnection(string connectionString) { return(DbConnectionFactory.GetDbConnection(DriverType.Postgresql, connectionString)); }
public LoggerCleanService(DbConnectionFactory db, DiscordShardedClient client) { _db = db; _client = client; }
public SystemController(SystemStore systems, MemberStore members, SwitchStore switches, DbConnectionFactory conn, TokenAuthService auth) { _systems = systems; _members = members; _switches = switches; _conn = conn; _auth = auth; }
public DbConnectionTests() { jsonDataReader = new JsonDataReader(); dbConnectionFactory = new DbConnectionFactory(); dbConnectionBuilder = new DbConnectionBuilder(); }
private static void ConfigureApplication(IUnityContainer container) { //_ambientContainer.RegisterType<IDbRepository, DbRepository>(new PerResolveLifetimeManager()); if (Convert.ToBoolean(ConfigurationManager.AppSettings.Get("UseEffort")) == true) { IDataLoader loader = new Effort.DataLoaders.CsvDataLoader(AppDomain.CurrentDomain.BaseDirectory + "\\Seed"); _ambientContainer.RegisterType <HRContext, HRContext>(new PerResolveLifetimeManager(), new InjectionConstructor(DbConnectionFactory.CreateTransient(loader))); } else { _ambientContainer.RegisterType <HRContext, HRContext>(new PerResolveLifetimeManager(), new InjectionConstructor()); } _ambientContainer.RegisterType <IDbRepository, DbRepository>(new PerResolveLifetimeManager()); _ambientContainer.RegisterType <IActivityManager, ActivityManager>(new PerResolveLifetimeManager()); _ambientContainer.RegisterType <IPersonManager, PersonManager>(new PerResolveLifetimeManager()); _ambientContainer.RegisterType <ISessionManager, SessionManager>(new PerResolveLifetimeManager()); _ambientContainer.RegisterType <IUtilityManager, UtilityManager>(new PerResolveLifetimeManager()); }
public void Initialize() { _connection = DbConnectionFactory.CreateTransient(); _databaseContext = new CicekSepetiDbContextTest(_connection); _objRepo = new FlowerRepository(_databaseContext); }
public MarriageRepository(string connStr) { _db = DbConnectionFactory.GetMysqlConnection(connStr); }
public DapperService(DbConnectionFactory dbConnectionFactory) { _dbConnectionFactory = dbConnectionFactory; }
public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint) { IServiceCollection tenantServiceCollection = _serviceProvider.CreateChildContainer(_applicationServices); tenantServiceCollection.AddInstance(settings); tenantServiceCollection.AddInstance(blueprint.Descriptor); tenantServiceCollection.AddInstance(blueprint); // Sure this is right? tenantServiceCollection.AddInstance(_loggerFactory); IServiceCollection moduleServiceCollection = _serviceProvider.CreateChildContainer(_applicationServices); foreach (var dependency in blueprint.Dependencies .Where(t => typeof(IModule).IsAssignableFrom(t.Type))) { moduleServiceCollection.AddScoped(typeof(IModule), dependency.Type); } var featureByType = blueprint.Dependencies.ToDictionary(x => x.Type, x => x.Feature); var moduleServiceProvider = moduleServiceCollection.BuildServiceProvider(); // Let any module add custom service descriptors to the tenant foreach (var service in moduleServiceProvider.GetServices<IModule>()) { service.Configure(tenantServiceCollection); } foreach (var dependency in blueprint.Dependencies .Where(t => !typeof(IModule).IsAssignableFrom(t.Type))) { foreach (var interfaceType in dependency.Type.GetInterfaces() .Where(itf => typeof(IDependency).IsAssignableFrom(itf))) { _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType); if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) { tenantServiceCollection.AddSingleton(interfaceType, dependency.Type); } else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType)) { tenantServiceCollection.AddScoped(interfaceType, dependency.Type); } else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType)) { tenantServiceCollection.AddTransient(interfaceType, dependency.Type); } else { tenantServiceCollection.AddScoped(interfaceType, dependency.Type); } } } // Configure event handlers, they are not part of the blueprint, so they have // to be added manually. Or need to create a module for this. tenantServiceCollection.AddScoped<IEventBus, DefaultOrchardEventBus>(); tenantServiceCollection.AddSingleton<IEventBusState, EventBusState>(); // Configuring data access var indexes = blueprint .Dependencies .Where(x => typeof(IIndexProvider).IsAssignableFrom(x.Type)) .Select(x => x.Type).ToArray(); if (settings.DatabaseProvider != null) { var store = new Store(cfg => { // @"Data Source =.; Initial Catalog = test1; User Id=sa;Password=demo123!" IConnectionFactory connectionFactory = null; switch (settings.DatabaseProvider) { case "SqlConnection": connectionFactory = new DbConnectionFactory<SqlConnection>(settings.ConnectionString); break; //case "SqliteConnection": // connectionFactory = new DbConnectionFactory<SqliteConnection>(settings.ConnectionString); // break; default: throw new ArgumentException("Unkown database provider: " + settings.DatabaseProvider); } var sqlFactory = new SqlDocumentStorageFactory(connectionFactory); ; cfg.ConnectionFactory = connectionFactory; cfg.DocumentStorageFactory = sqlFactory; cfg.IsolationLevel = sqlFactory.IsolationLevel = IsolationLevel.ReadUncommitted; if (!String.IsNullOrWhiteSpace(settings.TablePrefix)) { cfg.TablePrefix = sqlFactory.TablePrefix = settings.TablePrefix + "_"; } //cfg.RunDefaultMigration(); } ); var idGenerator = new LinearBlockIdGenerator(store.Configuration.ConnectionFactory, 20, "contentitem", store.Configuration.TablePrefix); store.RegisterIndexes(indexes); tenantServiceCollection.AddInstance<IStore>(store); tenantServiceCollection.AddInstance<LinearBlockIdGenerator>(idGenerator); tenantServiceCollection.AddScoped<ISession>(serviceProvider => store.CreateSession() ); } tenantServiceCollection.AddInstance<ITypeFeatureProvider>(new TypeFeatureProvider(featureByType)); // Register event handlers on the event bus var eventHandlers = tenantServiceCollection .Select(x => x.ImplementationType) .Where(t => t != null && typeof(IEventHandler).IsAssignableFrom(t) && t.GetTypeInfo().IsClass) .ToArray(); foreach (var handlerClass in eventHandlers) { tenantServiceCollection.AddScoped(handlerClass); // Register dynamic proxies to intercept direct calls if an IEventHandler is resolved, dispatching the call to // the event bus. foreach (var i in handlerClass.GetInterfaces().Where(t => typeof(IEventHandler).IsAssignableFrom(t))) { tenantServiceCollection.AddScoped(i, serviceProvider => { var proxy = DefaultOrchardEventBus.CreateProxy(i); proxy.EventBus = serviceProvider.GetService<IEventBus>(); return proxy; }); } } var shellServiceProvider = tenantServiceCollection.BuildServiceProvider(); var eventBusState = shellServiceProvider.GetService<IEventBusState>(); // Register any IEventHandler method in the event bus foreach (var handlerClass in eventHandlers) { foreach (var handlerInterface in handlerClass.GetInterfaces().Where(x => typeof(IEventHandler).IsAssignableFrom(x))) { foreach (var interfaceMethod in handlerInterface.GetMethods()) { //var classMethod = handlerClass.GetMethods().Where(x => x.Name == interfaceMethod.Name && x.GetParameters().Length == interfaceMethod.GetParameters().Length).FirstOrDefault(); Func<IServiceProvider, IDictionary<string, object>, Task> d = (sp, parameters) => DefaultOrchardEventBus.Invoke(sp, parameters, interfaceMethod, handlerClass); eventBusState.Add(handlerInterface.Name + "." + interfaceMethod.Name, d); } } } return shellServiceProvider; }
public void Init() { var connection = DbConnectionFactory.CreateTransient(); TestContext = new MyTestContext(connection); }
public PersonRepository(string connStr) { _db = DbConnectionFactory.GetMysqlConnection(connStr); }
public static MyPortalDbContext GetTestData() { var effortConnection = DbConnectionFactory.CreateTransient(); var context = new MyPortalDbContext(effortConnection); #region BasketItems var basketItems = new List <BasketItem> { new BasketItem { Id = 1, StudentId = 1, ProductId = 1 }, new BasketItem { Id = 2, ProductId = 1, StudentId = 1 }, new BasketItem { Id = 3, ProductId = 1, StudentId = 1 }, new BasketItem { Id = 4, ProductId = 3, StudentId = 3 } }; #endregion #region CommentBanks var commentBanks = new List <CommentBank> { new CommentBank { Name = "Opening", Id = 1 }, new CommentBank { Name = "Middle", Id = 2 }, new CommentBank { Name = "Closing", Id = 3 } }; #endregion #region Comments var comments = new List <Comment> { new Comment { CommentBankId = 1, Value = "Hello" }, new Comment { CommentBankId = 2, Value = "<he> works very hard" }, new Comment { CommentBankId = 2, Value = "<he> needs to improve his work" }, new Comment { CommentBankId = 3, Value = "Thank you" } }; #endregion #region Documents var documents = new List <Document> { new Document { Description = "Doc1", Url = "http://ftp.test.com/doc1", Date = DateTime.Today, IsGeneral = true, Approved = true, UploaderId = 1 }, new Document { Description = "Doc2", Url = "http://ftp.test.com/doc2", Date = DateTime.Today, IsGeneral = true, Approved = true, UploaderId = 1 }, new Document { Description = "Doc3", Url = "http://ftp.test.com/doc3", Date = DateTime.Today, IsGeneral = true, Approved = false, UploaderId = 1 }, new Document { Description = "Doc4", Url = "http://ftp.test.com/doc4", Date = DateTime.Today, IsGeneral = false, Approved = true, UploaderId = 1 } }; #endregion #region Grades var grades = new List <Grade>(); #endregion #region GradeSets var gradeSets = new List <GradeSet>(); #endregion #region LessonPlans var lessonPlans = new List <LessonPlan> { }; #endregion #region Logs var logs = new List <Log> { new Log { Date = DateTime.Now, AuthorId = 3, Message = "Test", StudentId = 3, TypeId = 1 }, new Log { Date = DateTime.Now, AuthorId = 3, Message = "Test2", StudentId = 3, TypeId = 2 }, new Log { Date = DateTime.Today, AuthorId = 3, Message = "Test3", StudentId = 3, TypeId = 3 }, new Log { Date = DateTime.Today, AuthorId = 3, Message = "Test4", StudentId = 3, TypeId = 4 } }; #endregion #region LogTypes var logTypes = new List <LogType> { new LogType { Name = "Type 1" }, new LogType { Name = "Type 2" }, new LogType { Name = "Type 3" }, new LogType { Name = "Type 4" } }; #endregion #region Products var products = new List <Product> { new Product { Id = 1, Description = "Art Pack", Price = (decimal)7.50, OnceOnly = false, Visible = true }, new Product { Id = 2, Description = "School Dinner", OnceOnly = false, Visible = false, Price = (decimal)1.50 }, new Product { Id = 3, Description = "School Trip", OnceOnly = true, Visible = true, Price = (decimal)100.00 }, new Product { Id = 4, Description = "Delete Me", OnceOnly = false, Visible = true, Price = 35.99m } }; #endregion #region RegGroups var regGroups = new List <RegGroup> { new RegGroup { Id = 1, Name = "1A", TutorId = 1, YearGroupId = 1 }, new RegGroup { Id = 2, Name = "4A", TutorId = 1, YearGroupId = 2 }, new RegGroup { Id = 3, Name = "7A", YearGroupId = 3, TutorId = 1 }, new RegGroup { Id = 4, Name = "11A", YearGroupId = 4, TutorId = 1 } }; #endregion #region Results var results = new List <Result> { new Result { StudentId = 1, SubjectId = 1, ResultSetId = 1, Value = "A" }, new Result { StudentId = 1, SubjectId = 2, ResultSetId = 1, Value = "C" } }; #endregion #region ResultSets var resultSets = new List <ResultSet> { new ResultSet { Id = 1, Name = "Current", IsCurrent = true }, new ResultSet { Id = 2, Name = "Old", IsCurrent = false } }; #endregion #region Sales var sales = new List <Sale>(); #endregion #region Staff var staff = new List <Staff> { new Staff { Id = 1, FirstName = "Georgia", LastName = "Alibi", Code = "GAL", Email = "*****@*****.**", JobTitle = "Test Teacher", Title = "Mrs" }, new Staff { Id = 2, FirstName = "Chloe", LastName = "Farrar", Code = "CFA", Title = "Mrs", Email = "*****@*****.**", JobTitle = "Test Teacher" }, new Staff { Id = 3, FirstName = "Lily", LastName = "Sprague", Code = "LSP", Title = "Mrs", JobTitle = "Test SLT", Email = "*****@*****.**" }, new Staff { Id = 4, FirstName = "William", LastName = "Townsend", Code = "WTO", Title = "Mr", Email = "*****@*****.**", JobTitle = "Test SLT" } }; #endregion #region StaffDocuments var staffDocuments = new List <StaffDocument>(); #endregion #region StaffObservations var staffObservations = new List <StaffObservation>(); #endregion #region Students var students = new List <Student> { new Student { Id = 1, FirstName = "Aaron", LastName = "Aardvark", YearGroupId = 3, Email = "*****@*****.**", AccountBalance = (decimal)200.00, CandidateNumber = "1234", RegGroupId = 3, Gender = "M" }, new Student { Id = 2, FirstName = "Dorothy", LastName = "Perkins", YearGroupId = 1, Email = "*****@*****.**", CandidateNumber = "5678", AccountBalance = (decimal)10.00, RegGroupId = 1, Gender = "F" }, new Student { Id = 3, FirstName = "John", LastName = "Appleseed", YearGroupId = 2, RegGroupId = 2, Email = "*****@*****.**", AccountBalance = (decimal)0.00, CandidateNumber = "7821", Gender = "X" }, new Student { Id = 4, FirstName = "Betty", LastName = "Newbie", YearGroupId = 4, RegGroupId = 4, AccountBalance = (decimal)100.00, Email = "*****@*****.**", CandidateNumber = "6452", Gender = "F" } }; #endregion #region StudentDocuments var studentDocuments = new List <StudentDocument>(); #endregion #region StudyTopics var studyTopics = new List <StudyTopic> { }; #endregion #region Subjects var subjects = new List <Subject> { new Subject { Name = "English", LeaderId = 3, Code = "En" }, new Subject { Name = "Maths", LeaderId = 3, Code = "Ma" }, new Subject { Name = "Science", LeaderId = 3, Code = "Sc" } }; #endregion #region TrainingCertificates var trainingCertificates = new List <TrainingCertificate>(); #endregion #region TrainingCourses var trainingCourses = new List <TrainingCourse>(); #endregion #region TrainingStatuses var trainingStatuses = new List <TrainingStatus>(); #endregion #region YearGroups var yearGroups = new List <YearGroup> { new YearGroup { Id = 1, Name = "Year 1", KeyStage = 1, HeadId = 3 }, new YearGroup { Id = 2, Name = "Year 4", KeyStage = 2, HeadId = 3 }, new YearGroup { Id = 3, Name = "Year 7", HeadId = 3, KeyStage = 3 }, new YearGroup { Id = 4, Name = "Year 11", HeadId = 3, KeyStage = 4 } }; #endregion context.BasketItems.AddRange(basketItems); context.CommentBanks.AddRange(commentBanks); context.Comments.AddRange(comments); context.Documents.AddRange(documents); context.Grades.AddRange(grades); context.GradeSets.AddRange(gradeSets); context.LessonPlans.AddRange(lessonPlans); context.Logs.AddRange(logs); context.LogTypes.AddRange(logTypes); context.Products.AddRange(products); context.RegGroups.AddRange(regGroups); context.Results.AddRange(results); context.ResultSets.AddRange(resultSets); context.Sales.AddRange(sales); context.Staff.AddRange(staff); context.StaffDocuments.AddRange(staffDocuments); context.StaffObservations.AddRange(staffObservations); context.Students.AddRange(students); context.StudentDocuments.AddRange(studentDocuments); context.StudyTopics.AddRange(studyTopics); context.Subjects.AddRange(subjects); context.TrainingCertificates.AddRange(trainingCertificates); context.TrainingCourses.AddRange(trainingCourses); context.TrainingStatuses.AddRange(trainingStatuses); context.YearGroups.AddRange(yearGroups); context.SaveChanges(); return(context); }
protected DapperRepositoryBase() { _dbConnection = DbConnectionFactory.CreateDbConnection(DatabaseType.SqlServer); }
public TaskDefinitionRepository(DbConnectionFactory connectionFactory) { _connectionFactory = connectionFactory; }
public UserRepository(DbConnectionFactory factory) { _factory = factory; }
public PKEventHandler(ProxyService proxy, ILogger logger, IMetrics metrics, DiscordShardedClient client, DbConnectionFactory connectionFactory, ILifetimeScope services, CommandTree tree, Scope sentryScope, ProxyCache cache, LastMessageCacheService lastMessageCache, LoggerCleanService loggerClean) { _proxy = proxy; _logger = logger; _metrics = metrics; _client = client; _connectionFactory = connectionFactory; _services = services; _tree = tree; _sentryScope = sentryScope; _cache = cache; _lastMessageCache = lastMessageCache; _loggerClean = loggerClean; }
public static IComponentContext RegisterDependancies() { var builder = new ContainerBuilder(); var dataContext = new PromactErpContext(DbConnectionFactory.CreateTransient()); builder.RegisterInstance(dataContext).As <DbContext>().SingleInstance(); var httpClientMock = new Mock <IHttpClientService>(); var httpClientMockObject = httpClientMock.Object; builder.RegisterInstance(httpClientMock).As <Mock <IHttpClientService> >(); builder.RegisterInstance(httpClientMockObject).As <IHttpClientService>(); builder.RegisterType <ApplicationUserStore>().As <IUserStore <ApplicationUser> >(); builder.RegisterType <ApplicationUserManager>().AsSelf(); builder.RegisterType <ApplicationSignInManager>().AsSelf(); builder.RegisterType <EnvironmentVariableTestRepository>().As <IEnvironmentVariableRepository>(); builder.Register <IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication); builder.RegisterGeneric(typeof(Repository <>)).As(typeof(IRepository <>)); builder.RegisterType <LeaveRequestRepository>().As <ILeaveRequestRepository>(); builder.RegisterType <ScrumBotRepository>().As <IScrumBotRepository>(); builder.RegisterType <ScrumSetUpRepository>().As <IScrumSetUpRepository>(); builder.RegisterType <LeaveReportRepository>().As <ILeaveReportRepository>(); builder.RegisterType <ScrumReportRepository>().As <IScrumReportRepository>(); builder.RegisterType <OAuthLoginRepository>().As <IOAuthLoginRepository>(); builder.RegisterType <Client>().As <IClient>(); builder.RegisterType <OauthCallsRepository>().As <IOauthCallsRepository>(); builder.RegisterType <SlackRepository>().As <ISlackRepository>(); builder.RegisterType <AttachmentRepository>().As <IAttachmentRepository>(); builder.RegisterType <SlackUserRepository>().As <ISlackUserRepository>(); builder.RegisterType <StringConstantRepository>().As <IStringConstantRepository>(); builder.RegisterType <SlackChannelRepository>().As <ISlackChannelRepository>(); builder.RegisterType <TaskMailRepository>().As <ITaskMailRepository>(); builder.RegisterType <BotQuestionRepository>().As <IBotQuestionRepository>(); builder.RegisterType <ServiceRepository>().As <IServiceRepository>(); builder.RegisterType <OauthCallHttpContextRespository>().As <IOauthCallHttpContextRespository>(); builder.RegisterType <TaskMailReportRepository>().As <ITaskMailReportRepository>(); builder.RegisterType <MailSettingRepository>().As <IMailSettingRepository>(); var emailServiceMock = new Mock <IEmailService>(); var emailServiceMockObject = emailServiceMock.Object; builder.RegisterInstance(emailServiceMock).As <Mock <IEmailService> >(); builder.RegisterInstance(emailServiceMockObject).As <IEmailService>(); builder.RegisterType <EmailServiceTemplateRepository>().As <IEmailServiceTemplateRepository>(); builder.RegisterType <GroupRepository>().As <IGroupRepository>(); builder.RegisterType <MailSettingDetailsByProjectAndModuleRepository>().As <IMailSettingDetailsByProjectAndModuleRepository>(); var iLoggerMock = new Mock <ILogger>(); var iLoggerMockObject = iLoggerMock.Object; builder.RegisterInstance(iLoggerMock).As <Mock <ILogger> >(); builder.RegisterInstance(iLoggerMockObject).As <ILogger>(); builder.Register(x => AutoMapperConfiguration.ConfigureMap()).As <IMapper>().SingleInstance(); var mockServiceRepository = new Mock <IServiceRepository>(); var mockServiceRepositoryObject = mockServiceRepository.Object; builder.RegisterInstance(mockServiceRepository).As <Mock <IServiceRepository> >(); builder.RegisterInstance(mockServiceRepositoryObject).As <IServiceRepository>(); var httpContext = new Mock <HttpContextBase>(); var httpContextObject = httpContext.Object; builder.RegisterInstance(httpContext).As <Mock <HttpContextBase> >(); builder.RegisterInstance(httpContextObject).As <HttpContextBase>(); builder.RegisterType <RedmineRepository>().As <IRedmineRepository>(); var container = builder.Build(); return(container); }
public EffortTestBase() { EffortConnection = DbConnectionFactory.CreateTransient(); PropertyDbTestContext = new PropertyDbContext(); PropertyDbTestContext.Database.CreateIfNotExists(); }
public IdentityAuthOptionsConfigRepository(string connectionString) { _logger = LogManager.GetCurrentClassLogger(); _connectionProvider = new DbConnectionFactory(connectionString); }
public Manager() { var connection = DbConnectionFactory.CreateTransient(); Db = new LocationDb(connection); }
public static IServiceCollection AddDataAccess(this IServiceCollection services) { services.AddScoped <IDataMigrationManager, DataMigrationManager>(); services.AddScoped <IModularTenantEvents, AutomaticDataMigrations>(); // Adding supported databases services.TryAddDataProvider(name: "Sql Server", value: "SqlConnection", hasConnectionString: true); services.TryAddDataProvider(name: "Sqlite", value: "Sqlite", hasConnectionString: false); services.TryAddDataProvider(name: "MySql", value: "MySql", hasConnectionString: true); services.TryAddDataProvider(name: "Postgres", value: "Postgres", hasConnectionString: true); // Configuring data access services.AddSingleton <IStore>(sp => { var shellSettings = sp.GetService <ShellSettings>(); var hostingEnvironment = sp.GetService <IHostingEnvironment>(); if (shellSettings.DatabaseProvider == null) { return(null); } var shellOptions = sp.GetService <IOptions <ShellOptions> >(); IConnectionFactory connectionFactory = null; var isolationLevel = IsolationLevel.Unspecified; switch (shellSettings.DatabaseProvider) { case "SqlConnection": connectionFactory = new DbConnectionFactory <SqlConnection>(shellSettings.ConnectionString); isolationLevel = IsolationLevel.ReadUncommitted; break; case "Sqlite": var option = shellOptions.Value; var databaseFolder = Path.Combine(hostingEnvironment.ContentRootPath, option.ShellsRootContainerName, option.ShellsContainerName, shellSettings.Name); var databaseFile = Path.Combine(databaseFolder, "yessql.db"); Directory.CreateDirectory(databaseFolder); connectionFactory = new DbConnectionFactory <SqliteConnection>($"Data Source={databaseFile};Cache=Shared"); isolationLevel = IsolationLevel.ReadUncommitted; break; case "MySql": connectionFactory = new DbConnectionFactory <MySqlConnection>(shellSettings.ConnectionString); isolationLevel = IsolationLevel.ReadUncommitted; break; case "Postgres": connectionFactory = new DbConnectionFactory <NpgsqlConnection>(shellSettings.ConnectionString); isolationLevel = IsolationLevel.ReadUncommitted; break; default: throw new ArgumentException("Unknown database provider: " + shellSettings.DatabaseProvider); } var storeConfiguration = new Configuration { ConnectionFactory = connectionFactory, IsolationLevel = isolationLevel }; storeConfiguration.RegisterMySql(); storeConfiguration.RegisterSqLite(); storeConfiguration.RegisterSqlServer(); storeConfiguration.RegisterPostgreSql(); if (!string.IsNullOrWhiteSpace(shellSettings.TablePrefix)) { storeConfiguration.TablePrefix = shellSettings.TablePrefix + "_"; } var sqlFactory = new SqlDocumentStorageFactory(); if (!string.IsNullOrWhiteSpace(shellSettings.TablePrefix)) { sqlFactory.TablePrefix = shellSettings.TablePrefix + "_"; } storeConfiguration.DocumentStorageFactory = sqlFactory; var store = new Store(storeConfiguration); var indexes = sp.GetServices <IIndexProvider>(); store.RegisterIndexes(indexes.ToArray()); return(store); }); services.AddScoped <ISession>(sp => { var store = sp.GetService <IStore>(); if (store == null) { return(null); } return(store.CreateSession()); }); return(services); }
public override void RunAll() { string dbId = "EFRepoTestOracle"; using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_Add(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_Get(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_Any(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_Any_WithFilter(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_Any_WithFilter_NothingFound(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_FirstOrDefault(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_FirstOrDefault_WithFilter(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_FirstOrDefault_WithFilter_NothingFound(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_Modify(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_Remove(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_GetAll_NothingFound(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_Any_NothingFound(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_FirstOrDefault_NothingFound(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_AddRange(uow, 100, 2); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_GetAll(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_AllMatching(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_AllMatching_NothingFound(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_GetAllPaged(uow, 2); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_Max(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_RemoveRange(uow); } using (var uow = new OracleFullContext(DbConnectionFactory.CreatePersistent(dbId))) { this.BaseUnitOfWorkUnitTests_BankAccount_Rollback(uow); } }
public static void ValidateOpensConnectionEachTime() { var validConnection = Substitute.For<IDbConnection>(); var factory = new DbConnectionFactory(LocalDbConnection, c => validConnection); const int CallCount = 2; for (int i = 0; i < CallCount; ++i) { Assert.DoesNotThrow(() => factory.Validate()); } validConnection.Received(CallCount).Open(); }
public BookRepositoryTest() { connection = DbConnectionFactory.CreateTransient(); databaseContext = new BookContext(connection); objRepo = new TimeTracker.Repository.BookRepository(databaseContext); }
public static void TemplateFactoryCreatesCorrectTypeOfConnection() { var factory = new DbConnectionFactory<OleDbConnection>("Provider=SQLOLEDB;" + LocalDbConnection); var connection = factory.CreateConnection(); Assert.IsType<OleDbConnection>(connection); }
public PostgresDataStore(DbConnectionFactory conn, ILogger logger, ProxyCache cache) { _conn = conn; _logger = logger; _cache = cache; }
public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint) { var featureByType = blueprint.Dependencies.ToDictionary(x => x.Type, x => x.Feature); IServiceCollection tenantServiceCollection = _serviceProvider.CreateChildContainer(_applicationServices); tenantServiceCollection.AddInstance(settings); tenantServiceCollection.AddInstance(blueprint.Descriptor); tenantServiceCollection.AddInstance(blueprint); // Sure this is right? tenantServiceCollection.AddInstance(_loggerFactory); foreach (var dependency in blueprint.Dependencies .Where(t => !typeof(IModule).IsAssignableFrom(t.Type))) { foreach (var interfaceType in dependency.Type.GetInterfaces() .Where(itf => typeof(IDependency).IsAssignableFrom(itf))) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType); } if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) { tenantServiceCollection.AddSingleton(interfaceType, dependency.Type); } else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType)) { tenantServiceCollection.AddTransient(interfaceType, dependency.Type); } else if (typeof(IDependency).IsAssignableFrom(interfaceType)) { tenantServiceCollection.AddScoped(interfaceType, dependency.Type); } } } // Register components foreach (var dependency in blueprint.Dependencies) { var serviceComponentAttribute = dependency.Type.GetTypeInfo().GetCustomAttribute<ServiceScopeAttribute>(); if (serviceComponentAttribute != null) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, serviceComponentAttribute.ServiceType); } serviceComponentAttribute.Register(tenantServiceCollection, dependency.Type); } } // Configure event handlers, they are not part of the blueprint, so they have // to be added manually. Or need to create a module for this. tenantServiceCollection.AddScoped<IEventBus, DefaultOrchardEventBus>(); tenantServiceCollection.AddSingleton<IEventBusState, EventBusState>(); //// Apply custom options for the tenant //var options = blueprint //.Dependencies //.Where(x => typeof(IConfigure).IsAssignableFrom(x.Type)) //.Select(x => x.Type).ToArray(); //// TODO: Group all options by type and reuse the same configuration object //// such that multiple feature can update the same configuration object. //foreach (var type in options) //{ // var optionType = type // .GetInterfaces() // .Where(x => typeof(IConfigure).IsAssignableFrom(x)) // .FirstOrDefault() // .GetGenericArguments() // .FirstOrDefault(); // if(optionType == null) // { // // Ignore non-generic implementation // continue; // } // var optionObject = Activator.CreateInstance(optionType); // var configureMethod = type.GetMethod("Configure"); // var optionHost = Activator.CreateInstance(type); // configureMethod.Invoke(optionHost, new[] { optionObject }); // tenantServiceCollection.ConfigureOptions(optionObject); //} // Configuring data access var indexes = blueprint .Dependencies .Where(x => typeof(IIndexProvider).IsAssignableFrom(x.Type)) .Select(x => x.Type).ToArray(); if (settings.DatabaseProvider != null) { var store = new Store(cfg => { // @"Data Source =.; Initial Catalog = test1; User Id=sa;Password=demo123!" IConnectionFactory connectionFactory = null; switch (settings.DatabaseProvider) { case "SqlConnection": connectionFactory = new DbConnectionFactory<SqlConnection>(settings.ConnectionString); break; //case "SqliteConnection": // connectionFactory = new DbConnectionFactory<SqliteConnection>(settings.ConnectionString); // break; default: throw new ArgumentException("Unknown database provider: " + settings.DatabaseProvider); } cfg.ConnectionFactory = connectionFactory; cfg.IsolationLevel = IsolationLevel.ReadUncommitted; if (!String.IsNullOrWhiteSpace(settings.TablePrefix)) { cfg.TablePrefix = settings.TablePrefix + "_"; } #if SQL var sqlFactory = new SqlDocumentStorageFactory(connectionFactory); sqlFactory.IsolationLevel = IsolationLevel.ReadUncommitted; sqlFactory.ConnectionFactory = connectionFactory; if (!String.IsNullOrWhiteSpace(settings.TablePrefix)) { sqlFactory.TablePrefix = settings.TablePrefix + "_"; } cfg.DocumentStorageFactory = sqlFactory; #else var storageFactory = new LightningDocumentStorageFactory(Path.Combine(_appDataFolderRoot.RootFolder, "Sites", settings.Name, "Documents")); cfg.DocumentStorageFactory = storageFactory; #endif //cfg.RunDefaultMigration(); } ); var idGenerator = new LinearBlockIdGenerator(store.Configuration.ConnectionFactory, 20, "contentitem", store.Configuration.TablePrefix); store.RegisterIndexes(indexes); tenantServiceCollection.AddInstance<IStore>(store); tenantServiceCollection.AddInstance<LinearBlockIdGenerator>(idGenerator); tenantServiceCollection.AddScoped<ISession>(serviceProvider => store.CreateSession() ); } tenantServiceCollection.AddInstance<ITypeFeatureProvider>(new TypeFeatureProvider(featureByType)); IServiceCollection moduleServiceCollection = _serviceProvider.CreateChildContainer(_applicationServices); foreach (var dependency in blueprint.Dependencies .Where(t => typeof(IModule).IsAssignableFrom(t.Type))) { moduleServiceCollection.AddScoped(typeof(IModule), dependency.Type); } var moduleServiceProvider = moduleServiceCollection.BuildServiceProvider(); // Let any module add custom service descriptors to the tenant foreach (var service in moduleServiceProvider.GetServices<IModule>()) { service.Configure(tenantServiceCollection); } // Register event handlers on the event bus var eventHandlers = tenantServiceCollection .Select(x => x.ImplementationType) .Distinct() .Where(t => t != null && typeof(IEventHandler).IsAssignableFrom(t) && t.GetTypeInfo().IsClass) .ToArray(); foreach (var handlerClass in eventHandlers) { tenantServiceCollection.AddScoped(handlerClass); // Register dynamic proxies to intercept direct calls if an IEventHandler is resolved, dispatching the call to // the event bus. foreach (var i in handlerClass.GetInterfaces().Where(t => typeof(IEventHandler).IsAssignableFrom(t))) { tenantServiceCollection.AddScoped(i, serviceProvider => { var proxy = DefaultOrchardEventBus.CreateProxy(i); proxy.EventBus = serviceProvider.GetService<IEventBus>(); return proxy; }); } } var shellServiceProvider = tenantServiceCollection.BuildServiceProvider(); var eventBusState = shellServiceProvider.GetService<IEventBusState>(); // Register any IEventHandler method in the event bus foreach (var handlerClass in eventHandlers) { foreach (var handlerInterface in handlerClass.GetInterfaces().Where(x => typeof(IEventHandler).IsAssignableFrom(x) && typeof(IEventHandler) != x)) { foreach (var interfaceMethod in handlerInterface.GetMethods()) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug($"{handlerClass.Name}/{handlerInterface.Name}.{interfaceMethod.Name}"); } //var classMethod = handlerClass.GetMethods().Where(x => x.Name == interfaceMethod.Name && x.GetParameters().Length == interfaceMethod.GetParameters().Length).FirstOrDefault(); Func<IServiceProvider, IDictionary<string, object>, Task> d = (sp, parameters) => DefaultOrchardEventBus.Invoke(sp, parameters, interfaceMethod, handlerClass); eventBusState.Add(handlerInterface.Name + "." + interfaceMethod.Name, d); } } } return shellServiceProvider; }
public ViewUsersHelper(string connectionString) { factory = new DbConnectionFactory(connectionString); context = new DbContext(factory); }