public GrainStorageTests(ITestOutputHelper output) { timingFactor = CalibrateTimings(); this.output = output; var rnd = new Random(); dbNames = new Dictionary <string, SqlConnectionStringBuilder>(); dbInstanceName = rnd.Next().ToString(); ISqlLocalDbProvider provider = new SqlLocalDbProvider(); instance = provider.GetOrCreateInstance(dbInstanceName); instance.Start(); //do the database setups dbNames.Add("basic", CreateADatabase(rnd)); dbNames.Add("SimpleSQLStore", CreateADatabase(rnd)); //this is the call to start up the test cluster base.Initialize(); }
private bool CheckSqlServer() { try { ISqlLocalDbProvider provider = new SqlLocalDbProvider(); ISqlLocalDbInstance instance = provider.GetOrCreateInstance(Global.Product); instance.Start(); } catch (Exception e) { MessageBox.Show("LocalDB Instance could not be started:\n\n" + e.Message, $"{Global.Product}", MessageBoxButton.OK, MessageBoxImage.Error); return(false); } // create Database and Files if MDF not exists if (!File.Exists(Global.DatabaseMdfPath)) { DbCreator.Create(Global.Product, Global.DatabaseFolder); } using (SqlConnection c = new SqlConnection(Properties.Settings.Default.SQLEXPRESS)) { try { c.Open(); return(true); } catch (Exception e) { MessageBox.Show("Error opening Database:\n\n" + e.Message, $"{Global.Product}", MessageBoxButton.OK, MessageBoxImage.Error); return(false); } } }
private void SetupLocalDbDatabase() { var localDbProvider = new SqlLocalDbProvider(); var localInstance = localDbProvider.CreateInstance(DatabaseName); // instance name = db name, the api will always use the latest version localInstance.Start(); this.SetupMsSqlDatabase(localInstance.CreateConnectionStringBuilder().ConnectionString); }
private void Initialize(string instanceName, string databaseName) { this.databaseName = databaseName; this.instanceName = instanceName; var existing = SqlLocalDbApi.GetInstanceInfo(instanceName); if (existing.Exists) { if (existing.IsRunning) { SqlLocalDbApi.StopInstance(instanceName); } SqlLocalDbApi.DeleteInstance(instanceName); } ISqlLocalDbProvider provider = new SqlLocalDbProvider(); this.instance = provider.GetOrCreateInstance(instanceName); instance.Start(); var connectionStringBuilder = instance.CreateConnectionStringBuilder(); using (var conn = new SqlConnection(connectionStringBuilder.ConnectionString)) { var serverConnection = new ServerConnection(conn); // By default, LocalDB stores database files in the user's home folder. Messy for temporary test databases. // Store them in the user's temp folder instead. var testDatabasesDirectory = Path.Combine(Path.GetTempPath(), "TestDatabases"); if (!Directory.Exists(testDatabasesDirectory)) { Directory.CreateDirectory(testDatabasesDirectory); } // Generate a unique name for our mdf file to avoid clashing with other ongoing test runs. var databaseFileNameRoot = string.Format("{0}_{1}_{2}", databaseName, DateTime.Now.ToString("yyyyMMdd_HHmmss"), Guid.NewGuid().ToString("N")); var mdfFileName = databaseFileNameRoot + ".mdf"; var ldfFileName = databaseFileNameRoot + "_log.ldf"; this.mdfFilePath = Path.Combine(testDatabasesDirectory, mdfFileName); this.ldfFilePath = Path.Combine(testDatabasesDirectory, ldfFileName); var sql = string.Format("CREATE DATABASE {0} ON (NAME = N'{0}', FILENAME = '{1}')", databaseName, this.mdfFilePath); Console.WriteLine(string.Format("Creating database {0} at {1}", databaseName, this.mdfFilePath)); serverConnection.ExecuteNonQuery(sql); } connectionStringBuilder.InitialCatalog = this.databaseName; this.connectionString = connectionStringBuilder.ConnectionString; }
private ISqlLocalDbInstance GetAppropriateLocalDbInstance( SqlLocalDbApiWrapper localDbApi, string localDbInstanceName, IEnumerable <string> allowedLocalDbVersions) { SqlLocalDbProvider localDbProvider = new SqlLocalDbProvider(); SqlLocalDbInstance existingInstance = GetExistingInstance(localDbProvider, localDbInstanceName); if (existingInstance != null) { return(existingInstance); } // No versions configured so just create an instance without specifying a version. // This will create an instance using the latest version. if (!allowedLocalDbVersions.Any()) { SqlLocalDbInstance newInstance = localDbProvider.CreateInstance(localDbInstanceName); return(newInstance); } // Order the version numbers so we try highest version to lowest version. IEnumerable <string> orderedVersionNumbers = allowedLocalDbVersions.OrderByDescending(version => version); IEnumerable <string> installedVersions = localDbApi.Versions; foreach (string versionNumber in orderedVersionNumbers) { if (installedVersions.Contains(versionNumber)) { localDbProvider.Version = versionNumber; SqlLocalDbInstance newInstance = localDbProvider.CreateInstance(localDbInstanceName); return(newInstance); } } string errorMessage = $@"DbTestMonkey was unable to find an appropriate LocalDb version to use. The following versions were configured to be considered in the app.config by you: {string.Join(",", allowedLocalDbVersions.Select(s => "\"" + s + "\""))} However only the following LocalDb versions were found to be installed: {string.Join(",", installedVersions.Select(s => "\"" + s + "\""))} Please correct this error by one of the following options: * Add an installed version of LocalDb into your projects app.config <allowedLocalDbVersions> element. You can find the installed versions by running ""sqllocaldb versions"" at the command line. * Remove the <allowedLocalDbVersions> element from your app.config which means DbTestMonkey will use the latest installed version of LocalDb on your machine. * Install a version of LocalDb that is configured in your app.config <allowedLocalDbVersions> element."; throw new InvalidOperationException(errorMessage); }
public ISqlLocalDbInstance Start(string serverInstanceName) { Debug.WriteLine("Starting localDb server..."); var localDbProvider = new SqlLocalDbProvider(); LocalDb = localDbProvider.GetOrCreateInstance(serverInstanceName); if (!LocalDb.GetInstanceInfo().IsRunning) { LocalDb.Start(); } return(LocalDb); }
private SqlLocalDbInstance GetExistingInstance(SqlLocalDbProvider localDbProvider, string localDbInstanceName) { try { SqlLocalDbInstance existingInstance = localDbProvider.GetInstance(localDbInstanceName); IEnumerable <string> filePaths = GetPhysicalFilesForServer(existingInstance); bool isMissingFiles = filePaths.Any(path => !File.Exists(path)); // If at least one file doesn't exist, delete them all. // We have found that the SqlLocalDbInstanceInfo.Exists property to not be reliable. if (isMissingFiles) { LogAction("Existing LocalDb instance with name " + localDbInstanceName + " was found but some physical files were missing"); LogAction("Deleting instance and will attempt to recreate"); existingInstance.Stop(); SqlLocalDbApi.DeleteInstance(existingInstance.Name, deleteFiles: true); foreach (string filePath in filePaths) { try { File.Delete(filePath); } catch (DirectoryNotFoundException) { } } return(null); } else { LogAction("Found existing LocalDb instance with name " + localDbInstanceName + " and will use it"); LogAction("If you would like to delete this existing instance and let DbTestMonkey create a new instance run the following commands at a command line"); LogAction(" sqllocaldb stop " + localDbInstanceName); LogAction(" sqllocaldb delete " + localDbInstanceName); return(existingInstance); } } catch (InvalidOperationException) { LogAction("Existing LocalDb instance with name " + localDbInstanceName + " was not found"); } return(null); }
public MsSqlStreamStoreFixture(string schema) { _schema = schema; var localDbProvider = new SqlLocalDbProvider { Version = s_sqlLocalDbProviderVersionToUse }; _localDbInstance = localDbProvider.GetOrCreateInstance("StreamStoreTests"); _localDbInstance.Start(); var uniqueName = Guid.NewGuid().ToString().Replace("-", string.Empty); _databaseName = $"StreamStoreTests-{uniqueName}"; ConnectionString = CreateConnectionString(); }
public MsSqlEventStoreFixture(string schema) { _schema = schema; var localDbProvider = new SqlLocalDbProvider { Version = "11.0" }; _localDbInstance = localDbProvider.GetOrCreateInstance("CedarEventStoreTests"); _localDbInstance.Start(); var uniqueName = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString().PadLeft(20, '0'); _databaseName = $"CedarEventStoreTests_{uniqueName}"; ConnectionString = CreateConnectionString(); }
public SqlServerTests() { _localDb = new SqlLocalDbApiWrapper(); ISqlLocalDbProvider provider = new SqlLocalDbProvider(); string instanceName = Guid.NewGuid().ToString(); _instance = provider.CreateInstance(instanceName); _instance.Start(); _connection = _instance.CreateConnection(); _connection.Open(); _database = new Database(_connection); _database.Execute("create database [SqlServerTests]"); }
private void CleanupLocalDbDatabase() { SqlLocalDbApi.AutomaticallyDeleteInstanceFiles = true; SqlLocalDbApi.StopOptions = StopInstanceOptions.KillProcess; var localDbProvider = new SqlLocalDbProvider(); var localDbInstanceInfo = localDbProvider.GetInstances().FirstOrDefault(instance => instance.Name == DatabaseName); if (localDbInstanceInfo != null) { var localDbInstance = localDbProvider.GetInstance(DatabaseName); if (!localDbInstance.IsRunning) { localDbInstance.Start(); } this.CleanupMsSqlDatabase(localDbInstance.CreateConnectionStringBuilder().ConnectionString); SqlLocalDbApi.StopInstance(DatabaseName, TimeSpan.FromSeconds(20.0)); SqlLocalDbApi.DeleteInstance(DatabaseName); } }
public PubSubStoreTests(ITestOutputHelper output) : base() { this.output = output; var rnd = new Random(); dbNames = new Dictionary <string, string>() { { "PubSubStore", rnd.Next().ToString() }, }; dbInstanceName = rnd.Next().ToString(); ISqlLocalDbProvider provider = new SqlLocalDbProvider(); instance = provider.GetOrCreateInstance(dbInstanceName); instance.Start(); Initialize(); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); ISqlLocalDbApi localDB = new SqlLocalDbApiWrapper(); if (!localDB.IsLocalDBInstalled()) { MessageBox.Show("Máy tính của bạn phải cài đặt SQL Server LocalDB hoặc phiên bản Express để có thể sử dụng phần mềm."); return; } string uuid = "nhom7-928cf731-171f-464f-aa55-24e814eeb224"; ISqlLocalDbProvider provider = new SqlLocalDbProvider(); IList <ISqlLocalDbInstanceInfo> instances = provider.GetInstances(); bool flag = false; foreach (ISqlLocalDbInstanceInfo instanceInfo in instances) { if (instanceInfo.Name == uuid) { flag = true; break; } } if (!flag) { WaitForm frm = new WaitForm(); frm.Show(); ISqlLocalDbInstance instance = provider.CreateInstance(uuid); instance.Start(); try { if (IsCurrentUserAdmin()) { } try { using (SqlConnection connection = instance.CreateConnection()) { connection.Open(); try { string scriptText = Resources.script.ToString(); string[] splitter = new string[] { "\r\nGO\r\n" }; string[] commandTexts = scriptText.Split(splitter, StringSplitOptions.RemoveEmptyEntries); foreach (string commandText in commandTexts) { using (SqlCommand command = new SqlCommand(commandText, connection)) { command.ExecuteNonQuery(); } } } finally { connection.Close(); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (IsCurrentUserAdmin()) { } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { instance.Stop(); } frm.Close(); } else { ISqlLocalDbInstance instance = provider.GetInstance(uuid); } Global.connstring = @"Data Source=(LocalDB)\nhom7-928cf731-171f-464f-aa55-24e814eeb224;Initial Catalog=QUANLYTHUVIEN_Nhom7_14521100_15520048_15520062_15520115;Integrated Security=True"; Application.Run(new frmDangNhap()); }
/// <summary> /// Load all github tags in the background. /// </summary> private void LoadData() { // // Initialize the LocalDb service only once. // if (localDb == null) { var provider = new SqlLocalDbProvider(); SqlLocalDbInstance instance; try { // // If we find an existing instance then shut it down and delete it. // instance = provider.GetInstance("RockLauncher"); if (instance.IsRunning) { instance.Stop(); } SqlLocalDbInstance.Delete(instance); } finally { // // Create a new instance and keep a reference to it. // localDb = provider.CreateInstance("RockLauncher"); localDb.Start(); } } // // Load all the instances from the file system. // var instances = Directory.GetDirectories(Support.GetInstancesPath()) .Select(d => Path.GetFileName(d)).ToList(); // // Convert pre-1.0 instance folders to 1.0 instance folders, which contain a // RockWeb for the current instance data. // foreach (string instance in instances) { string instancePath = Path.Combine(Support.GetInstancesPath(), instance); string rockwebPath = Path.Combine(instancePath, "RockWeb"); if (!Directory.Exists(rockwebPath)) { Directory.CreateDirectory(rockwebPath); foreach (var d in Directory.GetDirectories(instancePath)) { if (!Path.GetFileName(d).Equals("RockWeb", StringComparison.CurrentCultureIgnoreCase)) { Directory.Move(d, Path.Combine(rockwebPath, Path.GetFileName(d))); } } foreach (var f in Directory.GetFiles(instancePath)) { Directory.Move(f, Path.Combine(rockwebPath, Path.GetFileName(f))); } } } // // Update the UI with the new list of instances. // Dispatcher.Invoke(() => { cbInstances.ItemsSource = instances; if (instances.Count > 0) { cbInstances.SelectedIndex = 0; } txtStatus.Text = "Idle"; UpdateState(); }); }