/// <summary> /// Recalculates the checksums for each page in the database and compares the new checksums to the expected values. Also verifies /// that each index entry exists in the table and that each table entry exists in the index. /// </summary> /// <returns> /// <c>True</c> if there is no database corruption; otherwise, <c>false</c>. /// </returns> public bool Verify() { using (var engine = new SqlCeEngine(ConnectionString)) { return(engine.Verify(VerifyOption.Enhanced)); } // Same thing using Reflection: //object sqlCeEngine = null; //try //{ // sqlCeEngine = SqlCeEngineType.InvokeMember(null, BindingFlags.CreateInstance, null, null, new object[] { ConnectionString }); // var verifyOptionEnumType = SqlCeAssembly.GetType("System.Data.SqlServerCe.VerifyOption"); // var verifyOptionEnhanced = verifyOptionEnumType.GetField("Enhanced").GetValue(verifyOptionEnumType); // var rv = SqlCeEngineType.InvokeMember("Verify", BindingFlags.InvokeMethod, null, sqlCeEngine, new[] { verifyOptionEnhanced }); // return Convert.ToBoolean(rv); //} //catch (TargetInvocationException ex) //{ // AppEventController.LogError(ex.InnerException ?? ex); // throw; //} //finally //{ // if (sqlCeEngine != null) // SqlCeEngineType.InvokeMember("Dispose", BindingFlags.InvokeMethod, null, sqlCeEngine, null); //} }
public void VerifyDatabase(string connectionString) { using (SqlCeEngine engine = new SqlCeEngine(connectionString)) { engine.Verify(VerifyOption.Enhanced); } }
private SqlCeDB() { try { string path = Environment.CurrentDirectory + "\\log4net.config"; if (File.Exists(path)) { path = "Exists"; } _SqlCeEngine = new SqlCeEngine(conString); if (!_SqlCeEngine.Verify()) { Logger.LogDebug(this, $"Database not found. Creating Database & required tables"); String relativeFilePath = ConfigurationManager.AppSettings[Constants.Keys.DbScript]; string fullPath = AppDomain.CurrentDomain.BaseDirectory + relativeFilePath; _SqlCeEngine.CreateDatabase(); CreateTables(fullPath); } Logger.LogDebug(this, "Creating SqlCeDB Instance"); } catch (Exception e) { Logger.LogError(this, "Exception Occured while creating SqlCeDB Instance", e); } }
public static void RepairDb(string fileName) { SqlCeEngine engine = new SqlCeEngine(TrialDataContext.GetConnectionString(fileName)); if (!engine.Verify()) { engine.Repair(null, RepairOption.RecoverAllOrFail); } }
public BaseGeneralService() { SqlCeEngine engine = new SqlCeEngine(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString); if (false == engine.Verify()) { // MessageBox.Show("Database is corrupted."); engine.Repair(null, RepairOption.RecoverAllOrFail); } }
static LocalCeDbContext() { //不重建数据库结构 //Database.SetInitializer<LocalCeDbContext>(new DropCreateDatabaseAlways<LocalCeDbContext>()); Database.SetInitializer <LocalCeDbContext>(null); SqlCeEngine engine = new SqlCeEngine(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString); if (false == engine.Verify()) { engine.Repair(null, RepairOption.RecoverAllOrFail); } }
/// <summary> /// Recalculates the checksums for each page in the database and compares the new checksums to the expected values. /// </summary> /// <param name="connectionString">Connection string to the database file that should be verified.</param> /// <returns>True if the checksums match and there is no database corruption; otherwise, false.</returns> private static bool VerifyDatabaseFile(string connectionString) { if (string.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentNullException("connectionString"); } using (var sqlCeEngine = new SqlCeEngine(connectionString)) { return(sqlCeEngine.Verify()); } }
private void verify() { SqlCeEngine engine = new SqlCeEngine(connection.ConnectionString); if (!engine.Verify()) { engine.Repair(connection.ConnectionString, RepairOption.RecoverCorruptedRows); } else { engine.Shrink(); } }
// Calls SQLCE's compactor public void compactDatabase() { string connString = @"Data Source = " + dbPath; // Create connection string for SQLCE DB SqlCeEngine engine = new SqlCeEngine(connString); // Instantiate engine object // Do the compaction engine.Compact(null); // We then verify the database, just incase. if (!engine.Verify()) { throw new Exception("Database corrupt"); } }
public void Verify() { try { using (var engine = new SqlCeEngine(ConnectionString)) engine.Verify(); using (var connection = new SqlCeConnection(ConnectionString)) connection.Open(); } catch (SqlCeInvalidDatabaseFormatException) { Upgrade(); } }
public bool Verify() { bool result = false; using (SqlCeEngine engine = new SqlCeEngine(_connString)) { result = engine.Verify(VerifyOption.Enhanced); if (!result) { try { engine.Upgrade(); } catch (Exception) { }; if (!engine.Verify(VerifyOption.Enhanced)) { engine.Repair(null, RepairOption.RecoverCorruptedRows); } result = engine.Verify(VerifyOption.Enhanced); } engine.Dispose(); } return(result); }
public void Verify() { try { using (var engine = new SqlCeEngine(ConnectionString)) engine.Verify(); using (var connection = new SqlCeConnection(ConnectionString)) connection.Open(); } catch (SqlCeInvalidDatabaseFormatException) { MessageBox.Show("The version of the SQL Server Compact Edition database loaded is currently not supported", "Unsupported Database Version"); //Upgrade(); } }
static DataAPI() { string databaseDirectory = $"{ Directory.GetCurrentDirectory() }\\Data_v1\\"; if (!Directory.Exists(databaseDirectory)) { Directory.CreateDirectory(databaseDirectory); } connectionString = $"Data Source = {databaseDirectory}{DB_NAME}"; var en = new SqlCeEngine(connectionString); if (!en.Verify()) { en.CreateDatabase(); } }
public bool Check() { if (string.IsNullOrEmpty(_connectionString)) { return(true); } var sb = new StringBuilder(); sb.Append(string.Format("Data Source = {0}", _connectionString)); if (!string.IsNullOrEmpty(_password)) { sb.Append(string.Format("; Password = {0}", _password)); } Engine = new SqlCeEngine(sb.ToString()); return(Engine.Verify()); }
static void Main(string[] args) { SqlCeEngine engine = new SqlCeEngine("Data Source = C:\\Users\\SomeUser\\Documents\\SomeDB.sdf"); if (false == engine.Verify()) { Console.WriteLine("Database is corrupted."); try { engine.Repair(null, RepairOption.DeleteCorruptedRows); } catch (SqlCeException ex) { Console.WriteLine(ex.Message); } } Console.WriteLine("Press any key to continue."); Console.ReadLine(); }
public static void CreateDatabaseAndTables() { using (var engine = new SqlCeEngine($"Data Source=\"{AppDomain.CurrentDomain.BaseDirectory}Data\\UserData.sdf\"; Password=\"test_password\"")) { if (!engine.Verify()) { engine.CreateDatabase(); using (var connection = new SqlCeConnection($"Data Source=\"{AppDomain.CurrentDomain.BaseDirectory}Data\\UserData.sdf\"; Password=\"test_password\"")) { connection.Execute(@"REMOVE TABLE TestUser;"); connection.Execute(@"CREATE TABLE User( [UserId] [INT] IDENTITY(1,1) PRIMARY KEY NOT NULL, [FirstName] [NVARCHAR](256) NOT NULL, [LastName] [NVARCHAR](256) NOT NULL, [EmailAddress] [NVARCHAR](256) NOT NULL, [CreatedDate] [DATETIME] NOT NULL DEFAULT(GETDATE()), [ModifiedDate] [DATETIME] NOT NULL DEFAULT(GETDATE()));" ); } } } }
public override InstallStatus TryInstall() { switch (_localConfig.Driver) { case SupportedNHDrivers.MsSqlCe4: using (new WriteLockDisposable(SchemaValidationLocker)) { using (var sqlCeEngine = new SqlCeEngine(_configuration.Properties[Environment.ConnectionString])) { if (!sqlCeEngine.Verify()) { sqlCeEngine.CreateDatabase(); } } } break; } InstallStatus installStatus; try { var schemaAlreadyValid = ValidateSchema(_configuration); if (schemaAlreadyValid) { return(new InstallStatus(InstallStatusType.Completed)); } UpdateSchema(_configuration); installStatus = new InstallStatus(InstallStatusType.Completed); } catch (Exception ex) { installStatus = new InstallStatus(InstallStatusType.TriedAndFailed, ex); } return(installStatus); }
internal void Execute(EngineAction action, string newConnectionString) { // Specify connection string for new database options; The following // tokens are valid: // - Password // - LCID // - Encryption Mode // - Case Sensitive // // All other SqlCeConnection.ConnectionString tokens are ignored // // engine.Compact("Data Source=; Password =a@3!7f$dQ;"); if (action != EngineAction.GetInfo) { using (SqlCeEngine engine = new SqlCeEngine(connectionString)) { switch (action) { case EngineAction.Undefined: break; case EngineAction.Shrink: engine.Shrink(); Console.WriteLine("Database successfully shrunk"); break; case EngineAction.Verify: Console.WriteLine(engine.Verify(VerifyOption.Enhanced) ? "Database successfully verified" : "Database verification failed"); break; case EngineAction.Compact: engine.Compact(null); Console.WriteLine("Database successfully compacted"); break; case EngineAction.Upgrade: engine.Upgrade(); Console.WriteLine("Database successfully upgraded"); break; case EngineAction.Create: engine.CreateDatabase(); Console.WriteLine("Database successfully created"); break; case EngineAction.RepairDelete: engine.Repair(null, RepairOption.DeleteCorruptedRows); Console.WriteLine("Database successfully repaired"); break; case EngineAction.RepairRecover: engine.Repair(null, RepairOption.RecoverAllOrFail); Console.WriteLine("Database successfully repaired"); break; case EngineAction.SetOption: engine.Compact(newConnectionString); Console.WriteLine("Database option(s) successfully changed"); break; default: break; } } } else if (action == EngineAction.GetInfo) { using (SqlCeConnection cn = new SqlCeConnection(connectionString)) { cn.Open(); List <KeyValuePair <string, string> > valueList = new List <KeyValuePair <string, string> >(); // 3.5 or later only API valueList = cn.GetDatabaseInfo(); valueList.Add(new KeyValuePair <string, string>("Database", cn.Database)); valueList.Add(new KeyValuePair <string, string>("ServerVersion", cn.ServerVersion)); if (System.IO.File.Exists(cn.Database)) { System.IO.FileInfo fi = new System.IO.FileInfo(cn.Database); valueList.Add(new KeyValuePair <string, string>("DatabaseSize", fi.Length.ToString(CultureInfo.InvariantCulture))); valueList.Add(new KeyValuePair <string, string>("Created", fi.CreationTime.ToShortDateString() + " " + fi.CreationTime.ToShortTimeString())); } valueList.Add(new KeyValuePair <string, string>(string.Empty, string.Empty)); valueList.Insert(0, new KeyValuePair <string, string>("SqlCeCmd", "Database Information")); foreach (KeyValuePair <string, string> pair in valueList) { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", pair.Key, pair.Value)); } } } return; }
// Calls SQLCE's verification function public bool verifyDatabase() { string connString = @"Data Source = " + dbPath; // Create connection string for SQLCE DB SqlCeEngine engine = new SqlCeEngine(connString); // Instantiate engine object if (!engine.Verify()) { throw new Exception("Database corrupt"); // Host application should use a try..catch block to catch this } return true; // Return true as Database is intact }
/// <summary> /// Ensures the database integrity. /// </summary> /// <param name="systemId">The system id.</param> /// <param name="descriptor">The descriptor.</param> /// <param name="mode">The mode.</param> /// <exception cref="UnexpectedNHibernateConfigurationException"> /// Unexpected dialect. /// or /// Unexpected connection driver. /// </exception> /// <exception cref="InvalidConfigurationException"> /// Unable to find connection information in NHibernate Descriptor settings. /// or /// Unable to find data source in connection string. /// </exception> /// <exception cref="DatabaseVerificationErrorException"></exception> public virtual void EnsureDatabaseIntegrity(long systemId, Dictionary<string, string> descriptor, SchemaFactoryModeEnum mode) { if (descriptor == null) { ThrowHelper.ThrowArgumentNullException("descriptor"); } if (descriptor.ContainsKey(DIALECT)) { string dialect = descriptor[DIALECT]; if (!dialect.StartsWith(DIALECT_EXPECTED_VALUE_BUILTIN) && !dialect.StartsWith(DIALECT_EXPECTED_VALUE_CUSTOM)) { throw new UnexpectedNHibernateConfigurationException("Unexpected dialect."); } } if (descriptor.ContainsKey(CONNECTION_DRIVER)) { if (!CONNECTION_DRIVER_EXPECTED_VALUE.Equals(descriptor[CONNECTION_DRIVER])) { throw new UnexpectedNHibernateConfigurationException("Unexpected connection driver."); } } FileInfo databaseFile = null; string connectionString = string.Empty; if (descriptor.ContainsKey(CONNECTION_STRING)) { connectionString = descriptor[CONNECTION_STRING]; databaseFile = GetDatabaseFile(connectionString); } else if (descriptor.ContainsKey(CONNECTION_STRING_NAME)) { connectionString = ConfigurationManager.ConnectionStrings[descriptor[CONNECTION_STRING_NAME]].ConnectionString; databaseFile = GetDatabaseFile(connectionString); } else { throw new InvalidConfigurationException("Unable to find connection information in NHibernate Descriptor settings."); } if (databaseFile == null) { throw new InvalidConfigurationException("Unable to find data source or database file name in connection string."); } using (SqlCeEngine en = new SqlCeEngine(connectionString)) { if (!databaseFile.Exists) { en.CreateDatabase(); } else { if (mode == SchemaFactoryModeEnum.Create || mode == SchemaFactoryModeEnum.Create_And_Drop) { databaseFile.Delete(); en.CreateDatabase(); } else { if (!en.Verify(VerifyOption.Enhanced)) { throw new DatabaseVerificationErrorException(); } } } } }
public void Verify() { using (var engine = new SqlCeEngine(ConnectionString)) engine.Verify(); }
/// <summary> /// Ensures the database integrity. /// </summary> /// <param name="systemId">The system id.</param> /// <param name="descriptor">The descriptor.</param> /// <param name="mode">The mode.</param> /// <exception cref="UnexpectedNHibernateConfigurationException"> /// Unexpected dialect. /// or /// Unexpected connection driver. /// </exception> /// <exception cref="InvalidConfigurationException"> /// Unable to find connection information in NHibernate Descriptor settings. /// or /// Unable to find data source in connection string. /// </exception> /// <exception cref="DatabaseVerificationErrorException"></exception> public virtual void EnsureDatabaseIntegrity(long systemId, Dictionary<string, string> descriptor, SchemaFactoryModeEnum mode) { if (descriptor == null) { ThrowHelper.ThrowArgumentNullException("descriptor"); } if (descriptor.ContainsKey(DIALECT)) { string dialect = descriptor[DIALECT]; if (!dialect.StartsWith(DIALECT_EXPECTED_VALUE_BUILTIN) && !dialect.StartsWith(DIALECT_EXPECTED_VALUE_CUSTOM)) { throw new UnexpectedNHibernateConfigurationException("Unexpected dialect."); } } if (descriptor.ContainsKey(CONNECTION_DRIVER)) { if (!CONNECTION_DRIVER_EXPECTED_VALUE.Equals(descriptor[CONNECTION_DRIVER])) { throw new UnexpectedNHibernateConfigurationException("Unexpected connection driver."); } } string databaseFile = string.Empty; string connectionString = string.Empty; if (descriptor.ContainsKey(CONNECTION_STRING)) { connectionString = descriptor[CONNECTION_STRING]; databaseFile = GetDatabaseFile(connectionString); } else if (descriptor.ContainsKey(CONNECTION_STRING_NAME)) { connectionString = ConfigurationManager.ConnectionStrings[descriptor[CONNECTION_STRING_NAME]].ConnectionString; databaseFile = GetDatabaseFile(connectionString); } else { throw new InvalidConfigurationException("Unable to find connection information in NHibernate Descriptor settings."); } if (string.IsNullOrEmpty(databaseFile)) { throw new InvalidConfigurationException("Unable to find data source in connection string."); } using (SqlCeEngine en = new SqlCeEngine(connectionString)) { FileInfo dbFileInfo = new FileInfo(databaseFile); if (!dbFileInfo.Exists) { en.CreateDatabase(); } else { if (mode == SchemaFactoryModeEnum.Create || mode == SchemaFactoryModeEnum.Create_And_Drop) { dbFileInfo.Delete(); en.CreateDatabase(); } else { if (!en.Verify(VerifyOption.Enhanced)) { throw new DatabaseVerificationErrorException(); } } } } }
private void button3_Click(object sender, EventArgs e) { /*string query = textBox4.Text; * string comonnn = BaseName.Text; * SqlCeConnection con = new SqlCeConnection("Data Source = comboBox1.Text"); * SqlCeDataAdapter da = new SqlCeDataAdapter(); * DataTable dt = new DataTable(); * SqlCeCommand cmd = new SqlCeCommand(); * DataSet ds = new DataSet(); * * con.ConnectionString = comonnn; * cmd.Connection = con; * cmd.CommandText = query; * con.Open(); * da.Fill(dt); * cmd.ExecuteNonQuery(); * con.Close(); * if (ds.Tables[0].Rows.Count != 0) * { * dataGridView1.DataSource = ds.Tables[0]; * }else * { * MessageBox.Show("Błąd połączenia, spróbuj jeszcze raz", "Wiadomość", MessageBoxButtons.OK, MessageBoxIcon.Error); * } */ SqlCeCommand cmd; string ZapytanieSQl = string.Empty; SqlCeConnection con = new SqlCeConnection(string.Format("Data Source = comboBox1.sdf")); try { using (SqlCeEngine ce = new SqlCeEngine(con.ConnectionString)) { if (!ce.Verify()) { ce.CreateDatabase(); if (con.State == ConnectionState.Closed) { con.Open(); con.Close(); } } } } catch (Exception ex) { string byk = string.Format("Problem w czasie tworzenia bazy danych: \n{0}", ex.Message); MessageBox.Show(byk, "Błąd Kuuurwa", MessageBoxButtons.OK, MessageBoxIcon.Error); } try { if (con == null) { return; } if (con.State == ConnectionState.Closed) { con.Open(); } } catch (Exception ex) { string byk = string.Format("Problem w czasie tworzenia tabel: \n {0}", ex.Message); MessageBox.Show(byk, "Wiadomo, raczej to nie jest pozytywny komunikat :D", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public override InstallStatus TryInstall() { switch (_localConfig.Driver) { case SupportedNHDrivers.MsSqlCe4: using (new WriteLockDisposable(SchemaValidationLocker)) { using (var sqlCeEngine = new SqlCeEngine(_configuration.Properties[Environment.ConnectionString])) { if (!sqlCeEngine.Verify()) { sqlCeEngine.CreateDatabase(); } } } break; } InstallStatus installStatus; try { var schemaAlreadyValid = ValidateSchema(_configuration); if (schemaAlreadyValid) return new InstallStatus(InstallStatusType.Completed); UpdateSchema(_configuration); installStatus = new InstallStatus(InstallStatusType.Completed); } catch (Exception ex) { installStatus = new InstallStatus(InstallStatusType.TriedAndFailed, ex); } return installStatus; }
public static void RepairDB() { var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RegBase"].ConnectionString; SqlCeEngine engine = new SqlCeEngine(connectionString); if (false == engine.Verify()) { Console.WriteLine("Database is corrupted."); try { engine.Repair(null, RepairOption.RecoverAllPossibleRows); } catch (SqlCeException ex) { Console.WriteLine(ex.Message); } } using (RegBase regBase = new RegBase()) { if (regBase.sexes.Count() == 0) { regBase.sexes.Add(new sex() { value = "мужcкой" }); regBase.sexes.Add(new sex() { value = "женcкий" }); } if (regBase.i_ua_domen_names.Count() == 0) { regBase.i_ua_domen_names.Add(new i_ua_domen_names() { value = "i.ua" }); regBase.i_ua_domen_names.Add(new i_ua_domen_names() { value = "ua.fm" }); regBase.i_ua_domen_names.Add(new i_ua_domen_names() { value = "email.ua" }); } if (regBase.countrys.Count() == 0) { regBase.countrys.Add(new country() { value = "Украина" }); regBase.countrys.Add(new country() { value = "Россия" }); } if (regBase.citys.Count() == 0) { regBase.citys.Add(new city() { value = "Харьков" }); regBase.citys.Add(new city() { value = "Москва" }); } if (regBase.secret_questions.Count() == 0) { regBase.secret_questions.Add(new secret_questions() { value = "Любимое блюдо" }); regBase.secret_questions.Add(new secret_questions() { value = "Имя животного" }); regBase.secret_questions.Add(new secret_questions() { value = "Памятная дата" }); regBase.secret_questions.Add(new secret_questions() { value = "Девичья фамилия матери" }); regBase.secret_questions.Add(new secret_questions() { value = "Прозвище в школе" }); regBase.secret_questions.Add(new secret_questions() { value = "Номер паспорта" }); } if (regBase.settings.Count() == 0) { } regBase.SaveChanges(); } }
/// <summary> /// Recalculates the checksums for each page in the database and compares the new checksums to the expected values. Also verifies /// that each index entry exists in the table and that each table entry exists in the index. Applies only to SQL CE. /// </summary> /// <returns> /// <c>True</c> if there is no database corruption; otherwise, <c>false</c>. /// </returns> internal static bool Verify() { using (SqlCeEngine engine = new SqlCeEngine(Util.ConnectionString)) { return engine.Verify(VerifyOption.Enhanced); } }
public bool Verify() { using (SqlCeEngine engine = new SqlCeEngine(_connString)) return(engine.Verify(VerifyOption.Enhanced)); }
/// <summary> /// Recalculates the checksums for each page in the database and compares the new checksums to the expected values. Also verifies /// that each index entry exists in the table and that each table entry exists in the index. /// </summary> /// <returns> /// <c>True</c> if there is no database corruption; otherwise, <c>false</c>. /// </returns> public bool Verify() { using (var engine = new SqlCeEngine(ConnectionString)) { return engine.Verify(VerifyOption.Enhanced); } // Same thing using Reflection: //object sqlCeEngine = null; //try //{ // sqlCeEngine = SqlCeEngineType.InvokeMember(null, BindingFlags.CreateInstance, null, null, new object[] { ConnectionString }); // var verifyOptionEnumType = SqlCeAssembly.GetType("System.Data.SqlServerCe.VerifyOption"); // var verifyOptionEnhanced = verifyOptionEnumType.GetField("Enhanced").GetValue(verifyOptionEnumType); // var rv = SqlCeEngineType.InvokeMember("Verify", BindingFlags.InvokeMethod, null, sqlCeEngine, new[] { verifyOptionEnhanced }); // return Convert.ToBoolean(rv); //} //catch (TargetInvocationException ex) //{ // AppEventController.LogError(ex.InnerException ?? ex); // throw; //} //finally //{ // if (sqlCeEngine != null) // SqlCeEngineType.InvokeMember("Dispose", BindingFlags.InvokeMethod, null, sqlCeEngine, null); //} }