} // func CompareDirectoryRoot #endregion protected override void ProcessRecord() { using (bar = Notify.CreateStatus(String.Format("Synchronize {0} -> {1}", Source, Target), String.Empty)) { bar.Maximum = 0; // start compare var t = Task.Factory.StartNew(CompareDirectoryRoot); // copy files bar.StartRemaining(); DequeueActions(true); if (!Stopping) { try { t.Wait(); } catch (AggregateException e) { WriteError(new ErrorRecord(e.InnerException, "1", ErrorCategory.OperationStopped, this)); throw; } } } } // proc ProcessRecord
private bool CleanDirectoryPath(CmdletProgress bar, DateTime dtNow, TimeSpan age, DirectoryInfo currentDirecotry, string relativePath) { var empty = true; foreach (var fsi in currentDirecotry.EnumerateFileSystemInfos()) { var currentRelativePath = Path.Combine(relativePath, fsi.Name); var di = fsi as DirectoryInfo; var fi = fsi as FileInfo; if (di != null) { if (CleanDirectoryPath(bar, dtNow, age, di, currentRelativePath)) { directoriesDeleted++; empty = DeleteSafe(bar, di.Delete, currentRelativePath); } else empty = false; } else if (fi != null) { if (IsOutAged(dtNow, fi.LastAccessTime, age) || IsOutAged(dtNow, fi.LastWriteTime, age) || IsOutAged(dtNow, fi.LastAccessTime, age)) { bytesDeleted += fi.Length; filesDeleted++; if (!DeleteSafe(bar, fi.Delete, currentRelativePath)) empty = false; } else empty = false; } } return empty; }
} // proc ZipFileItem private void GZipFileItem(CmdletNotify notify, CmdletProgress bar, Stream src, DirectoryInfo targetPath, FileIndexItem item) { using (var dst = new FileWrite(notify, new FileInfo(Path.Combine(targetPath.FullName, item.ArchiveName)), false, CompressMode.Auto)) { Stuff.CopyRawBytes(bar, item.RelativePath, src.Length, src, dst.Stream); dst.Commit(); } } // proc GZipFileItem
} // proc CloseZipStream private void ZipFileItem(CmdletNotify notify, CmdletProgress bar, Stream src, ZipOutputStream zip, FileIndexItem item) { var entry = new ZipEntry(ZipEntry.CleanName(item.RelativePath)); entry.DateTime = item.LastWriteTimeUtc; entry.Size = src.Length; entry.Comment = item.GetComment(); entry.CompressionMethod = ZipFile(item.RelativePath) ? CompressionMethod.Deflated : CompressionMethod.Stored; zip.PutNextEntry(entry); Stuff.CopyRawBytes(bar, item.RelativePath, src.Length, src, zip); zip.CloseEntry(); zip.Flush(); } // proc ZipFileItem
} // func EnumerateDirectory private bool DeleteSafe(CmdletProgress bar, Action delete, string relativePath) { try { if (ShouldProcess(relativePath, "remove")) { bar.CurrentOperation = $"Delete {relativePath}..."; delete(); } return(true); } catch (Exception e) { WriteWarning($"Delete failed: {relativePath} ([{e.GetType().Name}] {e.Message})"); return(false); } } // proc DeleteSafe
private bool CleanDirectoryPath(CmdletProgress bar, DateTime dtNow, TimeSpan age, DirectoryInfo currentDirecotry, string relativePath) { var empty = true; foreach (var fsi in EnumerateDirectory(currentDirecotry, relativePath)) { var currentRelativePath = Path.Combine(relativePath, fsi.Name); if (fsi is DirectoryInfo di) { if (CleanDirectoryPath(bar, dtNow, age, di, currentRelativePath)) { directoriesDeleted++; empty = DeleteSafe(bar, di.Delete, currentRelativePath); } else { empty = false; } } else if (fsi is FileInfo fi) { if (IsOutAged(dtNow, fi.LastAccessTime, age) || IsOutAged(dtNow, fi.LastWriteTime, age) || IsOutAged(dtNow, fi.CreationTime, age)) { bytesDeleted += fi.Length; filesDeleted++; if (!DeleteSafe(bar, fi.Delete, currentRelativePath)) { empty = false; } } else { empty = false; } } } return(empty); } // proc CleanDirectory
private bool DeleteSafe(CmdletProgress bar, Action delete, string relativePath) { try { if (ShouldProcess(relativePath, "remove")) { bar.CurrentOperation = $"Delete {relativePath}..."; delete(); } return true; } catch (Exception e) { WriteWarning($"Delete failed: {relativePath} ([{e.GetType().Name}] {e.Message})"); return false; } }
protected override void ProcessRecord() { using (var con = new SqlConnection(Connection)) using (var bar = Notify.CreateStatus($"Backup database {con.Database}...", "Verbinde...")) { progress = bar; con.Open(); con.InfoMessage += Con_InfoMessage; // get index information using (var cmd = con.CreateCommand()) { cmd.CommandTimeout = 0; var indexTasks = new List <Tuple <string, string> >(); bar.StatusDescription = $"Check indizes..."; cmd.CommandText = String.Format(String.Join(Environment.NewLine, "SELECT s.[name], o.[name], i.[name], avg_fragmentation_in_percent, fragment_count", " FROM sys.dm_db_index_physical_stats(DB_ID(N'{0}'), NULL, NULL, NULL, NULL) AS f", " INNER JOIN sys.indexes AS i ON(f.object_id = i.object_id AND f.index_id = i.index_id)", " INNER JOIN sys.objects AS o ON(i.object_id = o.object_id)", " INNER JOIN sys.schemas s on(o.schema_id = s.schema_id)"), con.Database ); using (var r = cmd.ExecuteReader()) { while (r.Read()) { var schemaName = r.GetString(0); var tableName = r.GetString(1); var indexName = r.GetString(2); var frag = r.GetDouble(3); var fragCount = r.IsDBNull(4) ? 0 : r.GetInt64(4); var action = frag >= 5.0f && frag < 30.0 ? "REORGANIZE" : frag >= 30.0f ? "REBUILD" : null; if (action != null) { indexTasks.Add( new Tuple <string, string>( $"Index {indexName} of {schemaName}.{tableName} - {action} (fragmentation: {frag:N1})...", $"ALTER INDEX [{indexName}] ON [{schemaName}].[{tableName}] {action}" ) ); } } } // check indizes if (indexTasks.Count > 0) { bar.Maximum = indexTasks.Count; for (var i = 0; i < indexTasks.Count; i++) { bar.Position = i; bar.CurrentOperation = indexTasks[i].Item1; cmd.CommandText = indexTasks[i].Item2; cmd.ExecuteNonQuery(); } } bar.CurrentOperation = null; // do backup bar.StatusDescription = $"Execute Backup..."; cmd.CommandText = String.Format(String.Join(Environment.NewLine, "BACKUP DATABASE [{0}]", "TO DISK = N'{1}' WITH NOFORMAT, INIT, ", "NAME = N'{0}-Vollständig Datenbank Sichern', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, ", "STATS = 1, CHECKSUM" ), con.Database, BackupFile ); bar.Maximum = 100; bar.StartRemaining(); cmd.ExecuteScalar(); // ExecuteNonQuery does not fire InfoMessage bar.StopRemaining(); // check backup state bar.StatusDescription = $"Check Backup..."; cmd.CommandText = String.Format("select position from msdb..backupset where database_name = N'{0}' and backup_set_id = (select max(backup_set_id) from msdb..backupset where database_name = N'{0}')", con.Database); var pos = cmd.ExecuteScalar(); if (pos is DBNull) { throw new Exception("Backup information not found."); } // verify backup bar.StatusDescription = $"Verify Backup..."; cmd.CommandText = String.Format("RESTORE VERIFYONLY FROM DISK = N'{0}' WITH FILE = {1}, NOUNLOAD, NOREWIND", BackupFile, pos); cmd.ExecuteScalar(); } } } // proc ProcessRecord