public void ShrinkDatabase(string connectionString) { using (SqlCeEngine engine = new SqlCeEngine(connectionString)) { engine.Shrink(); } }
public void ShrinkDatabase(string connectionString) { using (SqlCeEngine engine = new SqlCeEngine(connectionString)) { engine.Shrink(); } }
public void ShrinkDatabase(string connectionString, int commandTimeout = 30) { using (SqlCeEngine engine = new SqlCeEngine(connectionString)) { engine.Shrink(); } }
private void ShrinkDatabase(object sender, EventArgs e) { var connectionString = _objectExplorer.ConnectionString; var engine = new SqlCeEngine(connectionString); engine.Shrink(); }
/// <summary> /// Helper method to optimize the sqlce file. /// </summary> public void Shrink() { using (var db = new SqlCeEngine(m_connectionString)) { db.Shrink(); } }
/// <summary> /// Compacts and shrinks the given database. /// </summary> public void Compact() { using (var eng = new SqlCeEngine(_connectionString)) { eng.Compact(_connectionString); eng.Shrink(); } }
/// <summary> /// Database saving handler /// </summary> /// <param name="repeatedly">should it go indefinatly? just for background thread</param> private static void DatabaseHandler(bool repeatedly) { DateTime lastcheck = DateTime.MinValue; while (true) { //store all audit records using (DNSAdminEntities db = new DNSAdminEntities()) { AuditRecord auditrec = null; while (auditrecords.TryDequeue(out auditrec)) { db.AuditRecords.AddObject(auditrec); } db.SaveChanges(); db.AcceptAllChanges(); } //check 10 minutes passed if ((DateTime.UtcNow - lastcheck).TotalMinutes > 10) { lastcheck = DateTime.UtcNow; //remove old records int removeitems = 0; using (DNSAdminEntities db = new DNSAdminEntities()) { var deletelist = db.AuditRecords.OrderByDescending(i => i.TimestampUTC).ToList().Skip(AuditMediaDBMaximumRecords).ToList(); removeitems = deletelist.Count(); foreach (var item in deletelist) { db.DeleteObject(item); } db.SaveChanges(); db.AcceptAllChanges(); } //if any records removed, compact database if (removeitems > 0) { using (SqlCeEngine engine = new SqlCeEngine("Data Source = |DataDirectory|\\DNSAdmin.sdf")) { engine.Shrink(); } } } if (repeatedly) { Thread.Sleep(5000); } else { break; } } }
/// <summary> /// Shrink the database file by connection string to it. /// </summary> /// <param name="connectionString">Connection string to the database file that should be shrink.</param> private static void ShrinkDatabaseFile(string connectionString) { if (string.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentNullException("connectionString"); } using (var sqlCeEngine = new SqlCeEngine(connectionString)) { sqlCeEngine.Shrink(); } }
/////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Archives database. /// This method creates archive database if the original one contains /// data to archive and cleans original database (removes archived data). /// If method succeeds, archive will contain schedules older than /// specified date. /// If original database does not contain data to archive, archive file /// will not be created and DbArchiveResult.IsArchiveCreated property /// will be set to "false". /// Method throws an exception if failure occures. /// </summary> /// <param name="path"> /// File path of original database. /// </param> /// <param name="date"> /// Schedules older than this date will be archived. /// </param> /// <returns> /// DbArchiveResult object. /// </returns> public static DbArchiveResult ArchiveDatabase(string path, DateTime date) { Debug.Assert(path != null); bool isCreated = false; DateTime?firstDate = null; DateTime?lastDate = null; string baseConnStr = DatabaseHelper.BuildSqlConnString(path, true); string archPath = null; // check if database has schedules to archive if (_HasDataToArchive(baseConnStr, date)) { // make archive file path archPath = _BuildArchivePath(path); // copy original file File.Copy(path, archPath); try { string archConnStr = DatabaseHelper.BuildSqlConnString( archPath, true); // apply script to archive _ApplyScript(archConnStr, ResourceLoader.ReadFileAsString(ARCHIVE_SCRIPT_FILE_NAME), date); // query archive dates _QueryDates(archConnStr, out firstDate, out lastDate); // compact archive file SqlCeEngine engine = new SqlCeEngine(archConnStr); engine.Shrink(); // apply script to original database _ApplyScript(baseConnStr, ResourceLoader.ReadFileAsString(CLEAN_SCRIPT_FILE_NAME), date); isCreated = true; } catch { DatabaseEngine.DeleteDatabase(archPath); throw; } } return(new DbArchiveResult(archPath, isCreated, firstDate, lastDate)); }
public static void MaintainDatabase() { Tracer.WriteLine("Creating database engine"); // Create the database engine using (var engine = new SqlCeEngine($"Data Source={DatabasePath}")) { Tracer.WriteLine("Shrinking database"); // Compact the database engine.Shrink(); } }
/// <summary> /// Verifies the data base. /// </summary> /// <param name="path">The path.</param> /// <param name="contentProtected">if set to <c>true</c> [content protected].</param> /// <param name="password">The password.</param> /// <remarks>Documented by Dev03, 2009-04-30</remarks> public static void VerifyDataBase(string path, bool contentProtected, string password) { string connectionString = contentProtected ? MSSQLCEConn.GetFullConnectionString(path, password) : MSSQLCEConn.GetFullConnectionString(path); using (SqlCeEngine sqlEngine = new SqlCeEngine()) { sqlEngine.LocalConnectionString = connectionString; sqlEngine.Repair(connectionString, RepairOption.RecoverAllPossibleRows); sqlEngine.Shrink(); try { File.Delete(Path.ChangeExtension(path, ".log")); } catch { Debug.WriteLine("Can not delete logfile "); } } }
private void verify() { SqlCeEngine engine = new SqlCeEngine(connection.ConnectionString); if (!engine.Verify()) { engine.Repair(connection.ConnectionString, RepairOption.RecoverCorruptedRows); } else { engine.Shrink(); } }
public bool ShrinkDatabase() { try { SqlCeEngine engine = new SqlCeEngine(_connection.ConnectionString); engine.Compact(_connection.ConnectionString); engine.Shrink(); } catch (Exception exp) { string msg = exp.Message; //System.Windows.Forms.MessageBox.Show(msg); return(false); } return(true); }
protected override void StartInternal() { Environment.CurrentDirectory = AppConfig.InstallationPath; using (SqlCeEngine eng = new SqlCeEngine("Data Source = Persistence.sdf")) { eng.Shrink(); } string address = "net.pipe://localhost/PersistenceService.svc"; NetNamedPipeBinding binding = new NetNamedPipeBinding(); binding.MaxReceivedMessageSize = int.MaxValue; binding.ReaderQuotas.MaxStringContentLength = int.MaxValue; _host = new ServiceHost(typeof(PersistenceServiceImpl)); _host.AddServiceEndpoint(typeof(IPersistenceService), binding, address); _host.Open(); }
public bool Shrink() { bool curReturn = true; System.Data.SqlServerCe.SqlCeEngine mySqlEngine = new SqlCeEngine(); try { String curSqlStmt = ""; mySqlEngine.LocalConnectionString = Properties.Settings.Default.waterskiConnectionStringApp; mySqlEngine.Shrink(); MessageBox.Show( "Compression complete for connection \n" + mySqlEngine.LocalConnectionString ); } catch ( Exception ex ) { curReturn = false; MessageBox.Show( "Error attempting to shrink database" + "Database connection: " + mySqlEngine.LocalConnectionString + "\n\nError: " + ex.Message ); } return curReturn; }
public bool Shrink() { bool curReturn = true; System.Data.SqlServerCe.SqlCeEngine mySqlEngine = new SqlCeEngine(); try { String curSqlStmt = ""; mySqlEngine.LocalConnectionString = Properties.Settings.Default.waterskiConnectionStringApp; mySqlEngine.Shrink(); MessageBox.Show("Compression complete for connection \n" + mySqlEngine.LocalConnectionString); } catch (Exception ex) { curReturn = false; MessageBox.Show("Error attempting to shrink database" + "Database connection: " + mySqlEngine.LocalConnectionString + "\n\nError: " + ex.Message); } return(curReturn); }
/// <summary> /// Closes all connections. /// </summary> /// <remarks>Documented by Dev05, 2009-01-16</remarks> public static void CloseAllConnections() { List <string> connectionStrings = new List <string>(); lock (connections) { foreach (SqlCeConnection con in connections.Values) { try { if (con.State == ConnectionState.Open) { if (!connectionStrings.Contains(con.ConnectionString)) { connectionStrings.Add(con.ConnectionString); } con.Close(); } } catch (Exception e) { Trace.WriteLine("Error closing Connection: " + e.ToString()); } } } connections.Clear(); SqlCeEngine sqlEngine = new SqlCeEngine(); foreach (string cs in connectionStrings) { try { sqlEngine.LocalConnectionString = cs; sqlEngine.Shrink(); } catch (Exception exp) { Trace.Write(exp.ToString()); } } sqlEngine.Dispose(); }
public static bool ShrinkDatabase(string filePath) { string connectionString = "Data Source = " + filePath + "; Password = "******"An error occurred in compacting the database." + "\nThe error text is as follows:\n" + Global.getExceptionText(ex); System.Media.SystemSounds.Hand.Play(); MessageBox.Show(message, "Error Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error); ErrorLogger.LogError(ex); return(false); } return(true); }
public void Shrink() { using (var engine = new SqlCeEngine(ConnectionString)) engine.Shrink(); }
public bool execCommandFile() { bool curReturn = true; int curDelimIdx; decimal curDatabaseVersion = 9999.00M; String inputBuffer, curSqlStmt = ""; StringBuilder curInputCmd = new StringBuilder( "" ); ImportData curImportData = new ImportData(); StreamReader myReader; myProgressInfo = new ProgressWindow(); #region Process all commands in the input file myReader = getImportFile(); if ( myReader != null ) { int curInputLineCount = 0; try { while ( ( inputBuffer = myReader.ReadLine() ) != null ) { curInputLineCount++; myProgressInfo.setProgressValue( curInputLineCount ); if ( inputBuffer.TrimStart( ' ' ).StartsWith( "## " ) ) { curDatabaseVersion = Convert.ToDecimal( inputBuffer.Substring( 4 ) ); } if ( inputBuffer.TrimStart( ' ' ).StartsWith( "//" ) || inputBuffer.TrimStart( ' ' ).StartsWith( "##" ) ) { } else { if ( curDatabaseVersion > myDatabaseVersion ) { curDelimIdx = inputBuffer.IndexOf( ';' ); if ( curDelimIdx >= 0 ) { if ( curDelimIdx > 0 ) { curInputCmd.Append( inputBuffer.Substring( 0, curDelimIdx ) ); } curSqlStmt = curInputCmd.ToString(); curSqlStmt.TrimStart( ' ' ); if ( curSqlStmt.Trim().ToUpper().StartsWith( "DROP " ) ) { execDropTable( replaceLinefeed( curSqlStmt ) ); } else if ( curSqlStmt.Trim().ToUpper().StartsWith( "CREATE " ) ) { execCreateTable( replaceLinefeed( curSqlStmt ) ); curInputCmd = new StringBuilder( "" ); } else { execSchemaCmd( replaceLinefeed( curSqlStmt ) ); } curInputCmd = new StringBuilder( "" ); } else { curInputCmd.Append( inputBuffer ); } } } } curSqlStmt = ""; System.Data.SqlServerCe.SqlCeEngine mySqlEngine = new SqlCeEngine(); mySqlEngine.LocalConnectionString = Properties.Settings.Default.waterskiConnectionStringApp; mySqlEngine.Shrink(); } catch ( Exception ex ) { curReturn = false; String ExcpMsg = ex.Message; if ( mySqlStmt != null ) { ExcpMsg += "\n" + curSqlStmt; } MessageBox.Show( "Error attempting to update database schema" + "\n\nError: " + ExcpMsg ); } } #endregion myProgressInfo.Close(); return curReturn; }
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; }
private bool updateSchema(String inFileRef) { bool curReturnValue = true; int curDelimIdx; String inputBuffer, curSqlStmt = ""; StringBuilder curInputCmd = new StringBuilder( "" ); ImportData curImportData = new ImportData(); StreamReader myReader; myProgressInfo = new ProgressWindow(); try { #region Process all commands in the input file myReader = getImportFile( inFileRef ); if ( myReader != null ) { int curInputLineCount = 0; try { MessageBox.Show( "Your database is about to be upgraded. Please click OK or continue to any dialogs." ); while ( ( inputBuffer = myReader.ReadLine() ) != null ) { curInputLineCount++; myProgressInfo.setProgressValue( curInputLineCount ); if ( inputBuffer.TrimStart( ' ' ).StartsWith( "//" ) ) { } else { curDelimIdx = inputBuffer.IndexOf( ';' ); if ( curDelimIdx >= 0 ) { if ( curDelimIdx > 0 ) { curInputCmd.Append( inputBuffer.Substring( 0, curDelimIdx ) ); } curSqlStmt = curInputCmd.ToString(); curSqlStmt.TrimStart( ' ' ); if ( curSqlStmt.Trim().ToUpper().StartsWith( "DROP " ) ) { execDropTable( replaceLinefeed(curSqlStmt) ); } else if ( curSqlStmt.Trim().ToUpper().StartsWith( "CREATE " ) ) { execCreateTable( replaceLinefeed(curSqlStmt) ); curInputCmd = new StringBuilder( "" ); } else { execSchemaCmd( replaceLinefeed(curSqlStmt) ); } curInputCmd = new StringBuilder( "" ); } else { curInputCmd.Append( inputBuffer ); } } } curSqlStmt = ""; System.Data.SqlServerCe.SqlCeEngine mySqlEngine = new SqlCeEngine(); mySqlEngine.LocalConnectionString = Properties.Settings.Default.waterskiConnectionStringApp; mySqlEngine.Shrink(); } catch ( Exception ex ) { curReturnValue = false; String ExcpMsg = ex.Message; if ( mySqlStmt != null ) { ExcpMsg += "\n" + curSqlStmt; } MessageBox.Show( "Error attempting to update database schema" + "\n\nError: " + ExcpMsg ); } } #endregion } catch ( Exception ex ) { curReturnValue = false; String ExcpMsg = ex.Message; if ( mySqlStmt != null ) { ExcpMsg += "\n" + mySqlStmt.CommandText; } MessageBox.Show( "Error attempting to update database schema" + "\n\nError: " + ExcpMsg ); } myProgressInfo.Close(); return curReturnValue; }
/// <summary> /// Database saving handler /// </summary> /// <param name="repeatedly">should it go indefinatly? just for background thread</param> private static void DatabaseHandler(bool repeatedly) { DateTime lastcheck = DateTime.MinValue; while (true) { //store all audit records using (DNSAdminEntities db = new DNSAdminEntities()) { AuditRecord auditrec = null; while (auditrecords.TryDequeue(out auditrec)) { db.AuditRecords.AddObject(auditrec); } db.SaveChanges(); db.AcceptAllChanges(); } //check 10 minutes passed if ((DateTime.UtcNow - lastcheck).TotalMinutes > 10) { lastcheck = DateTime.UtcNow; //remove old records int removeitems = 0; using (DNSAdminEntities db = new DNSAdminEntities()) { var deletelist = db.AuditRecords.OrderByDescending(i => i.TimestampUTC).ToList().Skip(AuditMediaDBMaximumRecords).ToList(); removeitems = deletelist.Count(); foreach (var item in deletelist) db.DeleteObject(item); db.SaveChanges(); db.AcceptAllChanges(); } //if any records removed, compact database if (removeitems > 0) { using (SqlCeEngine engine = new SqlCeEngine("Data Source = |DataDirectory|\\DNSAdmin.sdf")) { engine.Shrink(); } } } if (repeatedly) Thread.Sleep(5000); else break; } }
private bool updateSchema(String inFileRef) { bool curReturnValue = true; int curDelimIdx; String inputBuffer, curSqlStmt = ""; StringBuilder curInputCmd = new StringBuilder(""); ImportData curImportData = new ImportData(); StreamReader myReader; myProgressInfo = new ProgressWindow(); try { #region Process all commands in the input file myReader = getImportFile(inFileRef); if (myReader != null) { int curInputLineCount = 0; try { MessageBox.Show("Your database is about to be upgraded. Please click OK or continue to any dialogs."); while ((inputBuffer = myReader.ReadLine()) != null) { curInputLineCount++; myProgressInfo.setProgressValue(curInputLineCount); if (inputBuffer.TrimStart(' ').StartsWith("//")) { } else { curDelimIdx = inputBuffer.IndexOf(';'); if (curDelimIdx >= 0) { if (curDelimIdx > 0) { curInputCmd.Append(inputBuffer.Substring(0, curDelimIdx)); } curSqlStmt = curInputCmd.ToString(); curSqlStmt.TrimStart(' '); if (curSqlStmt.Trim().ToUpper().StartsWith("DROP ")) { execDropTable(replaceLinefeed(curSqlStmt)); } else if (curSqlStmt.Trim().ToUpper().StartsWith("CREATE ")) { execCreateTable(replaceLinefeed(curSqlStmt)); curInputCmd = new StringBuilder(""); } else { execSchemaCmd(replaceLinefeed(curSqlStmt)); } curInputCmd = new StringBuilder(""); } else { curInputCmd.Append(inputBuffer); } } } curSqlStmt = ""; System.Data.SqlServerCe.SqlCeEngine mySqlEngine = new SqlCeEngine(); mySqlEngine.LocalConnectionString = Properties.Settings.Default.waterskiConnectionStringApp; mySqlEngine.Shrink(); } catch (Exception ex) { curReturnValue = false; String ExcpMsg = ex.Message; if (mySqlStmt != null) { ExcpMsg += "\n" + curSqlStmt; } MessageBox.Show("Error attempting to update database schema" + "\n\nError: " + ExcpMsg); } } #endregion } catch (Exception ex) { curReturnValue = false; String ExcpMsg = ex.Message; if (mySqlStmt != null) { ExcpMsg += "\n" + mySqlStmt.CommandText; } MessageBox.Show("Error attempting to update database schema" + "\n\nError: " + ExcpMsg); } myProgressInfo.Close(); return(curReturnValue); }
public void Shrink() { using (SqlCeEngine engine = new SqlCeEngine(_connString)) engine.Shrink(); }
public void Shrink() { m_Engine.Shrink(); }
public bool execCommandFile() { bool curReturn = true; int curDelimIdx; decimal curDatabaseVersion = 9999.00M; String inputBuffer, curSqlStmt = ""; StringBuilder curInputCmd = new StringBuilder(""); ImportData curImportData = new ImportData(); StreamReader myReader; myProgressInfo = new ProgressWindow(); #region Process all commands in the input file myReader = getImportFile(); if (myReader != null) { int curInputLineCount = 0; try { while ((inputBuffer = myReader.ReadLine()) != null) { curInputLineCount++; myProgressInfo.setProgressValue(curInputLineCount); if (inputBuffer.TrimStart(' ').StartsWith("## ")) { curDatabaseVersion = Convert.ToDecimal(inputBuffer.Substring(4)); } if (inputBuffer.TrimStart(' ').StartsWith("//") || inputBuffer.TrimStart(' ').StartsWith("##")) { } else { if (curDatabaseVersion > myDatabaseVersion) { curDelimIdx = inputBuffer.IndexOf(';'); if (curDelimIdx >= 0) { if (curDelimIdx > 0) { curInputCmd.Append(inputBuffer.Substring(0, curDelimIdx)); } curSqlStmt = curInputCmd.ToString(); curSqlStmt.TrimStart(' '); if (curSqlStmt.Trim().ToUpper().StartsWith("DROP ")) { execDropTable(replaceLinefeed(curSqlStmt)); } else if (curSqlStmt.Trim().ToUpper().StartsWith("CREATE ")) { execCreateTable(replaceLinefeed(curSqlStmt)); curInputCmd = new StringBuilder(""); } else { execSchemaCmd(replaceLinefeed(curSqlStmt)); } curInputCmd = new StringBuilder(""); } else { curInputCmd.Append(inputBuffer); } } } } curSqlStmt = ""; System.Data.SqlServerCe.SqlCeEngine mySqlEngine = new SqlCeEngine(); mySqlEngine.LocalConnectionString = Properties.Settings.Default.waterskiConnectionStringApp; mySqlEngine.Shrink(); } catch (Exception ex) { curReturn = false; String ExcpMsg = ex.Message; if (mySqlStmt != null) { ExcpMsg += "\n" + curSqlStmt; } MessageBox.Show("Error attempting to update database schema" + "\n\nError: " + ExcpMsg); } } #endregion myProgressInfo.Close(); return(curReturn); }