protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseNpgsql(DbConnectionString.GetTestConn()); } }
/// <summary> /// Get all databases /// </summary> public string[] GetDatabases(DbConnectionString connection) { connection.Database = "postgres"; NpgsqlConnection conn = new NpgsqlConnection(this.CreateConnectionString(connection)); try { conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand("SELECT datname FROM pg_database;", conn); List <String> retVal = new List <string>(10); using (var reader = cmd.ExecuteReader()) while (reader.Read()) { retVal.Add(Convert.ToString(reader[0])); } return(retVal.ToArray()); } catch { throw; } finally { conn.Close(); } }
public void ExplorerObjectDoubleClick(ExplorerObjectEventArgs e) { FormConnectionString dlg = new FormConnectionString(); dlg.ProviderID = "postgre"; dlg.UseProviderInConnectionString = false; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { DbConnectionString dbConnStr = dlg.DbConnectionString; ConfigConnections connStream = new ConfigConnections("postgis", "546B0513-D71D-4490-9E27-94CD5D72C64A"); string connectionString = dbConnStr.ConnectionString; string id = ConfigTextStream.ExtractValue(connectionString, "database"); id = connStream.GetName(id); connStream.Add(id, dbConnStr.ToString()); e.NewExplorerObject = new PostGISExplorerObject(this.ParentExplorerObject, id, dbConnStr); //string connStr = dlg.ConnectionString; //ConfigTextStream stream = new ConfigTextStream("postgis_connections", true, true); //string id = ConfigTextStream.ExtractValue(connStr, "Database"); //id += "@" + ConfigTextStream.ExtractValue(connStr, "Server"); //if (id == "@") id = "PostGIS Connection"; //stream.Write(connStr, ref id); //stream.Close(); //e.NewExplorerObject = new PostGISExplorerObject(id, dlg.ConnectionString); } }
async public override Task <bool> Refresh() { await base.Refresh(); base.AddChildObject(new PostGISNewConnectionObject(this)); //ConfigTextStream stream = new ConfigTextStream("postgis_connections"); //string connStr, id; //while ((connStr = stream.Read(out id)) != null) //{ // base.AddChildObject(new PostGISExplorerObject(id, connStr)); //} //stream.Close(); ConfigConnections conStream = new ConfigConnections("postgis", "546B0513-D71D-4490-9E27-94CD5D72C64A"); Dictionary <string, string> DbConnectionStrings = conStream.Connections; foreach (string DbConnName in DbConnectionStrings.Keys) { DbConnectionString dbConn = new DbConnectionString(); dbConn.FromString(DbConnectionStrings[DbConnName]); base.AddChildObject(new PostGISExplorerObject(this, DbConnName, dbConn)); } return(true); }
public static async Task ExportFiles(DbConnectionString dbConnectionString, string sqlQuery, string folderPath, CancellationToken Ct, IProgress <ReportMessage> progress) { using (SqlConnection dbCon = new SqlConnection(dbConnectionString.ConnectionString)) { dbCon.Open(); using (SqlCommand cmd = new SqlCommand(sqlQuery, dbCon)) { // 10 hours cmd.CommandTimeout = 60 * 60 * 10; using (SqlDataReader reader = await cmd.ExecuteReaderAsync()) { try { while (await reader.ReadAsync()) { Ct.ThrowIfCancellationRequested(); var fileName = Convert.ToString(reader.GetValue(0)); string validFileName = MakeValidFileName(progress, fileName); var bytes = (byte[])reader.GetValue(1); var fullPath = Path.Combine(folderPath, validFileName); File.WriteAllBytes(fullPath, bytes); progress.Report(ReportMessage.Standard("Exported: " + validFileName)); } } finally { cmd.Cancel(); reader.Close(); } } } } }
public void Initialize(DbConnectionString cnxStr) { var viewModel = ServiceLocator.GetRequiredService <ExportDocumentsControlVM>(); this.DataContext = viewModel; this.Dispatcher.Invoke(() => viewModel.InitializeDb(cnxStr)); }
public MainWindow() { InitializeComponent(); DemoDbSettings settings = ServiceLocator.GetRequiredService <DemoDbSettings>(); var dbConnectionStr = new DbConnectionString(settings.ConnectionString, settings.DbName); var tested = 0; if (tested == 0) { var histo = new SSMSPlusHistory.UI.HistoryControl(); Panel.Children.Add(histo); } else if (tested == 1) { var search = new SSMSPlusSearch.UI.SchemaSearchControl(); search.Initialize(dbConnectionStr); Panel.Children.Add(search); } else if (tested == 2) { var docs = new SSMSPlusDocument.UI.ExportDocumentsControl(); docs.Initialize(dbConnectionStr); Panel.Children.Add(docs); } else if (tested == 3) { var ui = new PreferencesWindow(); ui.ShowAndActivate(); } }
public async Task <IResponseEntity> UpdateAsync(TaskQzEditRequest req) { if (req == null || req?.Id == "") { return(ResponseEntity.Error("更新的实体主键丢失")); } var entity = _mapper.Map <SysTaskQzEntity>(req); if (entity.IsDefaultDatabase) { DbInfo dbInfo = _authUser.Tenant.DbOptions.Where(x => x.Key == Constants.SystemDbKey).FirstOrDefault(); DbConnectionString connectionString = dbInfo.ConnectionStrings.Where(x => x.UseType == DbUseType.Master).FirstOrDefault(); entity.ConnectionParam = JsonConvert.SerializeObject(new { ConnectionString = connectionString.ConnectionString, DbType = Convert.ToInt32(dbInfo.DbType) }); } await _SysTaskQzRepository.UpdateAsync(entity); if (entity.IsStart) { var res = await _schedulerCenter.AddScheduleJobAsync(entity); } return(ResponseEntity.Ok("更新成功")); }
public void OwnedTypesDoNotNeedToBeIncluded() { var newBillingAddress = new Address { City = "Krakow", ZipPostCode = "04-218" }; var newDeliveryAddress = new Address { City = "Warsaw", ZipPostCode = "00-001" }; var newOrderInfo = new OrderInfo { BillingAddress = newBillingAddress, DeliveryAddress = newDeliveryAddress, OrderNumber = "#1" }; var dbConnectionString = DbConnectionString.Create(nameof(ConfiguringRelationships), GetCallerName()); var dbCtxOptions = dbConnectionString .AsSqlConnectionString <ShopContext>() .EnsureDb(); using (var context = dbCtxOptions.BuildDbContext().StartLogging(_testOutput.AsLineWriter())) { context.Add(newOrderInfo); context.SaveChanges(); } using (var context = dbCtxOptions.BuildDbContext().StartLogging(_testOutput.AsLineWriter())) { var oi = context .OrderInfos .Single(); oi.BillingAddress.Should().NotBeNull("because it's an owned type"); oi.DeliveryAddress.Should().NotBeNull("because it's also an owned type"); } }
void PostGISDataset_ConnectionStringChanged(gView.Framework.OGC.DB.OgcSpatialDataset sender, string provider) { try { _connectionString = DbConnectionString.ParseNpgsqlConnectionString(_connectionString); _factory = Npgsql.NpgsqlFactory.Instance; #region Version try { object obj = base.ExecuteFunction("select postgis_version()"); if (obj is string) { string version = obj.ToString(); if (!int.TryParse(version.Split('.')[0], out _majorVersion)) { _majorVersion = 1; } } } catch { _majorVersion = 1; } #endregion } catch { _factory = null; } }
public void CreatesOneToManyRelationship() { var dbConnectionString = DbConnectionString.Create(nameof(ConfiguringRelationships), GetCallerName()); using var context = dbConnectionString .AsSqlConnectionString <ManufacturerContext>() .EnsureDb() .BuildDbContext() .StartLogging(_testOutput.AsLineWriter()); var newUsbs = new[] { new UsbSlot { UsbVersion = "3.0" }, new UsbSlot { UsbVersion = "2.0" } }; var newNotebook = new Notebook { Name = "Pear", Usbs = newUsbs }; context.Add(newNotebook); context.SaveChanges(); context .Notebooks .Include(n => n.Usbs) .SingleOrDefault() .Should().NotBeNull("because has been successfully added"); }
public void CreatesOptionTwoOneToOneRelationship() { var dbConnectionString = DbConnectionString.Create(nameof(ConfiguringRelationships), GetCallerName()); using var context = dbConnectionString .AsSqlConnectionString <ConventionContext>() .EnsureDb() .BuildDbContext() .StartLogging(_testOutput.AsLineWriter()); var newAttendee = new Attendee { Name = "John Smith" }; // Attendee can exist without Ticket. context.Add(newAttendee); // var newAttendee is now being tracked. context.SaveChanges(); newAttendee.Ticket.Should().BeNull($"because it has not been provided and {nameof(Attendee)} can exist without {nameof(Ticket)}"); newAttendee.Ticket = new Ticket { Type = "normal" }; // Properties Attendee, AttendeeId and TicketId are handled by EF Core. context.SaveChanges(); var nameTicketTypePair = context .Attendees .Include(a => a.Ticket) // Now, Include() handles joining in the DB. .Select(a => new { a.Name, a.Ticket.Type }) // Much simpler than the one in OptionOne. .First(); nameTicketTypePair.Should().BeEquivalentTo(new { Name = "John Smith", Type = "normal" }, "because that's the expected output" + " of the above query"); }
/// <summary> /// Create a connection string in the configuration file /// </summary> public static String CreateConnectionString(this XmlDocument config, DbConnectionString connectionString) { config.RegisterDataProvider(connectionString.Provider); // First is there already a connectionstring with the specified name? if (!String.IsNullOrEmpty(connectionString.Name)) { var existingConnectionString = config.GetConnectionString(connectionString.Name); if (existingConnectionString.Provider != null) // update { var connectionStrings = config.GetOrCreateElement("/configuration/connectionStrings"); var connectionStringXml = config.SelectSingleNode($"./add[@name='{connectionString.Name}']"); connectionStringXml.Attributes["connectionString"].Value = connectionString.Provider.CreateConnectionString(connectionString); return(connectionString.Name); } } // Anonymous scope { if (String.IsNullOrEmpty(connectionString.Name)) { connectionString.Name = Guid.NewGuid().ToConfigName(); } var connectionStrings = config.GetOrCreateElement("/configuration/connectionStrings"); var connectionStringXml = config.CreateElement("add"); connectionStringXml.Attributes.Append(config.CreateAttributeValue("name", connectionString.Name)); connectionStringXml.Attributes.Append(config.CreateAttributeValue("providerName", connectionString.Provider.InvariantName)); connectionStringXml.Attributes.Append(config.CreateAttributeValue("connectionString", connectionString.Provider.CreateConnectionString(connectionString))); connectionStrings.AppendChild(connectionStringXml); } return(connectionString.Name); }
async public override Task <bool> SetConnectionString(string value) { var ret = await base.SetConnectionString(value); _connectionString = DbConnectionString.ParseNpgsqlConnectionString(_connectionString); return(ret); }
public void CreatesManyToManyRelationshipByConvention() { var dbConnectionString = DbConnectionString.Create(nameof(ConfiguringRelationships), GetCallerName()); using var context = dbConnectionString .AsSqlConnectionString <BookStoreContext>() .EnsureDb() .BuildDbContext() .StartLogging(_testOutput.AsLineWriter()); var aFreemanAuthor = new Author { Name = "Adam Freeman" }; var eEvansAuthor = new Author { Name = "Eric Evans" }; var aspBook = new Book { Title = "...ASP.NET CORE..." }; var dddBook = new Book { Title = "...DDD..." }; context .Invoking(ctx => { ctx.AddRange(new[] { aFreemanAuthor, eEvansAuthor }); ctx.AddRange(new[] { aspBook, dddBook }); ctx.SaveChanges(); }) .Should().NotThrow("because it's actually the 'zero-or-one-or-many' relationship."); context.Entry(aspBook).State.Should().Be(EntityState.Unchanged, "because it has already been saved and" + " has not been modified afterwards"); aspBook.AuthorLinks.Should().BeNull("because tracking doesn't automatically loads navigation properties"); context.Entry(aspBook).Collection(a => a.AuthorLinks).Load(); // Load navigation property explicitly. context.Entry(aspBook).State.Should().Be(EntityState.Unchanged, "because it's still unchanged - just its property has been loaded"); aspBook.AuthorLinks.Should().NotBeNull("because already loaded"); aspBook.AuthorLinks.Count().Should().Be(0, "because no links have been specified"); aspBook.AuthorLinks = aspBook.AuthorLinks.Append(new BookAuthor { Author = aFreemanAuthor }).ToList(); context.Invoking(ctx => ctx.SaveChanges()).Should().NotThrow("because just Author must be specified in BookAuthor - the rest is" + " handled by EF Core"); aspBook.AuthorLinks = aspBook.AuthorLinks.Append(new BookAuthor { Author = eEvansAuthor }).ToList(); dddBook.AuthorLinks = new List <BookAuthor> { new BookAuthor { Author = eEvansAuthor }, new BookAuthor { Author = aFreemanAuthor } }; context.SaveChanges(); context.Set <BookAuthor>().Count().Should().Be(4, "because 2 authors * 2 books"); }
public void InitDb(DbConnectionString dbConnectionString) { if (!_initedDb.TryAdd(dbConnectionString, dbConnectionString.AsSqlConnectionString <T>())) { return; // Db already initialized. } _initedDb[dbConnectionString].EnsureDb(); _actions.ForEach(a => a.Invoke(_initedDb[dbConnectionString])); }
public FormConnectionString(DbConnectionString initialConnString) : this() { _initialConnString = initialConnString; if (_initialConnString != null) { _useProvider = _initialConnString.UseProviderInConnectionString; } }
public void TablePerHierarchySupportsInheritance() { var cardPayment = new PaymentCard { Amount = 2000M, Receipt = "ęśąćż" }; var cashPayment = new PaymentCash { Amount = 100M }; var notebookSoldIt = new SoldIt { WhatSold = "Notebook", Payment = cardPayment }; var keyboardSoldIt = new SoldIt { WhatSold = "Keyboard", Payment = cashPayment }; var dbConnectionString = DbConnectionString.Create(nameof(ConfiguringRelationships), GetCallerName()); var dbCtxOptions = dbConnectionString .AsSqlConnectionString <ShippingContext>() .EnsureDb(); using (var context = dbCtxOptions.BuildDbContext().StartLogging(_testOutput.AsLineWriter())) { context.AddRange(new[] { notebookSoldIt, keyboardSoldIt }); context.SaveChanges(); } using (var context = dbCtxOptions.BuildDbContext().StartLogging(_testOutput.AsLineWriter())) { var notebookPayment = context .SoldIts .Where(si => si.WhatSold == "Notebook") .Select(si => si.Payment) .Single(); var keyboardPayment = context .SoldIts .Where(si => si.WhatSold == "Keyboard") .Select(si => si.Payment) .Single(); notebookPayment.Should().BeOfType <PaymentCard>("because the original type has been preserved"); notebookPayment.Type.Should().Be("card", $"because that's a discriminator value indicating {nameof(PaymentCard)} type"); keyboardPayment.Should().BeOfType <PaymentCash>("because the original type has been preserved"); keyboardPayment.Type.Should().Be("cash", $"because that's a discriminator value indicating {nameof(PaymentCash)} type"); context .Set <Payment>() .OfType <PaymentCard>() .First().Receipt .Should() .Be("ęśąćż", "because that's another way to handle a hierarchical table"); } }
/// <summary> /// Populate configurators /// </summary> private void PopulateConfigurators() { foreach (var config in DatabaseConfiguratorRegistrar.Configurators) { cbxProviderType.Items.Add(config); } this.ConnectionString = new DbConnectionString() { }; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddTransient <IDrawAMapService, DrawAMapService>(); services.AddSingleton <IGroupService, GroupService>(); //将appsettings.json中的JwtSettings部分文件读取到JwtSettings中,这是给其他地方用的 services.Configure <JwtSettings>(Configuration.GetSection("JwtSettings")); services.Configure <DbConnectionString>(Configuration.GetSection("DbConnectionString")); //由于初始化的时候我们就需要用,所以使用Bind的方式读取配置 //将配置绑定到JwtSettings实例中 var jwtSettings = new JwtSettings(); var dbConnectionString = new DbConnectionString(); Configuration.Bind("JwtSettings", jwtSettings); Configuration.Bind("DbConnectionString", dbConnectionString); services.AddAuthentication(options => { //认证middleware配置 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(o => { //主要是jwt token参数设置 o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { //Token颁发机构 ValidIssuer = jwtSettings.Issuer, //颁发给谁 ValidAudience = jwtSettings.Audience, //这里的key要进行加密,需要引用Microsoft.IdentityModel.Tokens IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)), //ValidateIssuerSigningKey=true, ////是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比 ValidateLifetime = true, ////允许的服务器时间偏移量 //ClockSkew=TimeSpan.Zero }; //o.SecurityTokenValidators.Clear();//将SecurityTokenValidators清除掉,否则它会在里面拿验证 //o.SecurityTokenValidators.Add(new TokenValidator()); //o.Events = new JwtBearerEvents //{ // //重写OnMessageReceived // OnMessageReceived = context => { // var token = context.Request.Headers["bingosoft.token"]; // context.Token = token.FirstOrDefault(); // return Task.CompletedTask; // } //}; }); services.AddMvc(); }
private void Launch(DbConnectionString dbConnectionString) { var toolWindow = _packageProvider.AsyncPackage.FindToolWindow(typeof(SearchToolWindow), id++, true) as SearchToolWindow; toolWindow.Intialize(dbConnectionString); var frame = (IVsWindowFrame)toolWindow.Frame; frame.SetProperty((int)__VSFPROPID.VSFPROPID_FrameMode, VSFRAMEMODE.VSFM_MdiChild); Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(frame.Show()); }
public void Init(string selectFieldNames) { _provider = new DataProvider(); DbConnectionString connString = new DbConnectionString(); connString.UseProviderInConnectionString = true; connString.FromString(this.JoinConnectionString); _provider.Open(connString.ConnectionString); _selectFieldNames = String.IsNullOrEmpty(selectFieldNames.Trim()) ? "*" : _provider.ToFieldNames(selectFieldNames); }
/// <summary> /// Create a new database /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnNew_Click(object sender, EventArgs e) { frmNewDatabase newDatabase = new frmNewDatabase(this.ConnectionString); if (newDatabase.ShowDialog() == DialogResult.OK) { if (newDatabase.ConnectionString.Provider != this.ConnectionString.Provider) { this.ConnectionString = newDatabase.ConnectionString; } } }
public QueryingTheDbFixture(ITestOutputHelper testOutput) { _testOutput = testOutput; _dbConnectionString = DbConnectionString.Create(GetType().Name); _fact = DbContextFactoryManager <BookStoreContext> .Instance.GetDbContextFactory(nameof(QueryingTheDbFixture)); _fact.RegisterOnInit(dbCtxOpts => { dbCtxOpts.SeedWith(@"TestData\RawTestData1.json"); }); _fact.InitDb(_dbConnectionString); }
public ChangingTheDbContent(ITestOutputHelper testOutput) { _testOutput = testOutput; _fact = DbContextFactoryManager <BookStoreContext> .Instance.GetDbContextFactory(nameof(ChangingTheDbContent)); _fact.RegisterOnInit(dbCtxOpts => { dbCtxOpts.SeedWith(@"TestData\RawTestData1.json"); }); var dbConnectionStrings = ListFactMethodNames().Select(str => DbConnectionString.Create(GetType().Name, str)); _fact.InitDbAsync(dbConnectionStrings).Wait(); }
public EventTableConnection( DbConnectionString dbConn, string table, string idField, string xField, string yField, ISpatialReference sRef) { _dbConn = dbConn; _table = table; _xField = xField; _yField = yField; _idField = idField; _sRef = sRef; }
public async Task <int> ReIndexAsync(DbConnectionString dbConnectionString) { using (await _asyncLock.LockAsync()) { var dbid = await _schemaSearchRepository.DbExists(dbConnectionString); if (dbid > 0) { await _schemaSearchRepository.DropDbAsync(dbid); } return(await IndexAsync(dbConnectionString)); } }
public WebPortalUnitOfWork(DbConnectionString webPortalConnectionString) { Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true; _webPortalConnectionString = webPortalConnectionString; MatchRepository = new MatchRepository(_webPortalConnectionString); SportRepository = new SportRepository(_webPortalConnectionString); TeamRepository = new TeamRepository(_webPortalConnectionString); PlayerRepository = new PlayerRepository(_webPortalConnectionString); ScrapingInformationRepository = new ScrapingInformationRepository(_webPortalConnectionString); ProviderRepository = new ProviderRepository(_webPortalConnectionString); PlayerOverUnderRepository = new PlayerOverUnderRepository(_webPortalConnectionString); PlayerHeadToHeadRepository = new PlayerHeadToHeadRepository(_webPortalConnectionString); TempTableToTestRepository = new TempTableToTestRepository(_webPortalConnectionString); }
public OracleExplorerObject(IExplorerObject parent, string server, DbConnectionString connectionString) : base(parent, typeof(IFeatureDataset)) { _server = server; _connectionString = connectionString; List <ToolStripMenuItem> items = new List <ToolStripMenuItem>(); ToolStripMenuItem item = new ToolStripMenuItem(LocalizedResources.GetResString("Menu.ConnectionProperties", "Connection Properties...")); item.Click += new EventHandler(ConnectionProperties_Click); items.Add(item); _contextItems = items.ToArray(); }
public MongoDbAccessLayer(IDbSetting settings, DbConnectionString dbConnectionString) { _settings = settings; _client = new MongoClient($"mongodb://{dbConnectionString.DbHost}:{dbConnectionString.DbPort}"); var database = _client.GetDatabase(_settings.DatabaseName); _inputTypes = database.GetCollection <InputType>(_settings.InputTypeCollectionName); _forms = database.GetCollection <Form>(_settings.FormCollectionName); _submissions = database.GetCollection <Submission>(_settings.SubmissionCollectionName); //////REMOVE/////// _inputTypes.InsertMany(typeNames); Console.WriteLine("MongoDbAccessLayer Initialized"); }
public ChirpChirpContext(DbConnectionString dbConnectionString) : base(dbConnectionString) { Database.SetInitializer(new DropCreateDatabaseAlways<ChirpChirpContext>()); }