gongqiuhong 10 months ago
parent
commit
6b4826bb0c
3 changed files with 148 additions and 27 deletions
  1. 41 9
      DbBackup/Form1.Designer.cs
  2. 102 18
      DbBackup/Form1.cs
  3. 5 0
      DbBackup/ViewModel/PlanInfo.cs

+ 41 - 9
DbBackup/Form1.Designer.cs

@@ -111,6 +111,8 @@
             this.layoutControlItem12 = new DevExpress.XtraLayout.LayoutControlItem();
             this.layoutControlGroup2 = new DevExpress.XtraLayout.LayoutControlGroup();
             this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem();
+            this.checkClear = new DevExpress.XtraEditors.CheckEdit();
+            this.layoutControlItem25 = new DevExpress.XtraLayout.LayoutControlItem();
             ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
             this.layoutControl1.SuspendLayout();
             ((System.ComponentModel.ISupportInitialize)(this.panelControl1)).BeginInit();
@@ -177,10 +179,13 @@
             ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem12)).BeginInit();
             ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).BeginInit();
             ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit();
+            ((System.ComponentModel.ISupportInitialize)(this.checkClear.Properties)).BeginInit();
+            ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem25)).BeginInit();
             this.SuspendLayout();
             // 
             // layoutControl1
             // 
+            this.layoutControl1.Controls.Add(this.checkClear);
             this.layoutControl1.Controls.Add(this.btnStop);
             this.layoutControl1.Controls.Add(this.panelControl1);
             this.layoutControl1.Controls.Add(this.btnStart);
@@ -220,9 +225,9 @@
             // btnStop
             // 
             this.btnStop.Enabled = false;
-            this.btnStop.Location = new System.Drawing.Point(118, 452);
+            this.btnStop.Location = new System.Drawing.Point(104, 452);
             this.btnStop.Name = "btnStop";
-            this.btnStop.Size = new System.Drawing.Size(93, 23);
+            this.btnStop.Size = new System.Drawing.Size(107, 23);
             this.btnStop.StyleController = this.layoutControl1;
             this.btnStop.TabIndex = 16;
             this.btnStop.Text = "停止备份计划";
@@ -297,7 +302,7 @@
             // 
             this.btnStart.Location = new System.Drawing.Point(15, 452);
             this.btnStart.Name = "btnStart";
-            this.btnStart.Size = new System.Drawing.Size(93, 23);
+            this.btnStart.Size = new System.Drawing.Size(79, 23);
             this.btnStart.StyleController = this.layoutControl1;
             this.btnStart.TabIndex = 14;
             this.btnStart.Text = "启动备份计划";
@@ -637,7 +642,8 @@
             this.layoutControlItem22,
             this.layoutControlItem23,
             this.layoutControlItem24,
-            this.emptySpaceItem2});
+            this.emptySpaceItem2,
+            this.layoutControlItem25});
             this.layoutControlGroup5.Location = new System.Drawing.Point(0, 0);
             this.layoutControlGroup5.Name = "layoutControlGroup5";
             this.layoutControlGroup5.Size = new System.Drawing.Size(200, 508);
@@ -651,7 +657,7 @@
             this.itemStartStop.MinSize = new System.Drawing.Size(86, 40);
             this.itemStartStop.Name = "itemStartStop";
             this.itemStartStop.Padding = new DevExpress.XtraLayout.Utils.Padding(2, 5, 15, 2);
-            this.itemStartStop.Size = new System.Drawing.Size(100, 40);
+            this.itemStartStop.Size = new System.Drawing.Size(86, 40);
             this.itemStartStop.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
             this.itemStartStop.TextSize = new System.Drawing.Size(0, 0);
             this.itemStartStop.TextVisible = false;
@@ -686,12 +692,12 @@
             // layoutControlItem19
             // 
             this.layoutControlItem19.Control = this.btnStop;
-            this.layoutControlItem19.Location = new System.Drawing.Point(100, 400);
+            this.layoutControlItem19.Location = new System.Drawing.Point(86, 400);
             this.layoutControlItem19.MaxSize = new System.Drawing.Size(0, 40);
             this.layoutControlItem19.MinSize = new System.Drawing.Size(86, 40);
             this.layoutControlItem19.Name = "layoutControlItem19";
             this.layoutControlItem19.Padding = new DevExpress.XtraLayout.Utils.Padding(5, 2, 15, 2);
-            this.layoutControlItem19.Size = new System.Drawing.Size(100, 40);
+            this.layoutControlItem19.Size = new System.Drawing.Size(114, 40);
             this.layoutControlItem19.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
             this.layoutControlItem19.TextSize = new System.Drawing.Size(0, 0);
             this.layoutControlItem19.TextVisible = false;
@@ -763,10 +769,10 @@
             // emptySpaceItem2
             // 
             this.emptySpaceItem2.AllowHotTrack = false;
-            this.emptySpaceItem2.Location = new System.Drawing.Point(0, 440);
+            this.emptySpaceItem2.Location = new System.Drawing.Point(86, 440);
             this.emptySpaceItem2.MinSize = new System.Drawing.Size(104, 24);
             this.emptySpaceItem2.Name = "emptySpaceItem2";
-            this.emptySpaceItem2.Size = new System.Drawing.Size(200, 68);
+            this.emptySpaceItem2.Size = new System.Drawing.Size(114, 68);
             this.emptySpaceItem2.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
             this.emptySpaceItem2.TextSize = new System.Drawing.Size(0, 0);
             // 
@@ -1098,6 +1104,28 @@
             this.layoutControlItem6.TextSize = new System.Drawing.Size(0, 0);
             this.layoutControlItem6.TextVisible = false;
             // 
+            // checkClear
+            // 
+            this.checkClear.Location = new System.Drawing.Point(15, 492);
+            this.checkClear.Name = "checkClear";
+            this.checkClear.Properties.Caption = "自动清理";
+            this.checkClear.Size = new System.Drawing.Size(79, 20);
+            this.checkClear.StyleController = this.layoutControl1;
+            this.checkClear.TabIndex = 17;
+            // 
+            // layoutControlItem25
+            // 
+            this.layoutControlItem25.Control = this.checkClear;
+            this.layoutControlItem25.Location = new System.Drawing.Point(0, 440);
+            this.layoutControlItem25.MaxSize = new System.Drawing.Size(0, 24);
+            this.layoutControlItem25.MinSize = new System.Drawing.Size(75, 24);
+            this.layoutControlItem25.Name = "layoutControlItem25";
+            this.layoutControlItem25.Padding = new DevExpress.XtraLayout.Utils.Padding(2, 5, 15, 2);
+            this.layoutControlItem25.Size = new System.Drawing.Size(86, 68);
+            this.layoutControlItem25.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
+            this.layoutControlItem25.TextSize = new System.Drawing.Size(0, 0);
+            this.layoutControlItem25.TextVisible = false;
+            // 
             // Form1
             // 
             this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 14F);
@@ -1177,6 +1205,8 @@
             ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem12)).EndInit();
             ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).EndInit();
             ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit();
+            ((System.ComponentModel.ISupportInitialize)(this.checkClear.Properties)).EndInit();
+            ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem25)).EndInit();
             this.ResumeLayout(false);
 
         }
@@ -1257,6 +1287,8 @@
         private DevExpress.XtraLayout.LayoutControlItem layoutControlItem23;
         private DevExpress.XtraLayout.LayoutControlItem layoutControlItem24;
         private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem2;
+        private DevExpress.XtraEditors.CheckEdit checkClear;
+        private DevExpress.XtraLayout.LayoutControlItem layoutControlItem25;
     }
 }
 

+ 102 - 18
DbBackup/Form1.cs

@@ -22,6 +22,7 @@ namespace DbBackup
     {
         List<LogInfo> logData1 = new List<LogInfo>();
         List<LogInfo> logData2 = new List<LogInfo>();
+        bool isBackupAll = false;
         Dictionary<int, string> dic = new Dictionary<int, string>()
         {
             { 1,"一" },
@@ -31,7 +32,6 @@ namespace DbBackup
             { 5,"五" },
             { 6,"六" },
             { 0,"日" },
-
         };
         public Form1()
         {
@@ -73,16 +73,16 @@ namespace DbBackup
                 txtAllExeTime.DateTime = planInfo.AllTime;
                 txtWeekDays.Text = dic.First(p => p.Key == planInfo.IncWeekDay).Value;
                 txtIncExeTime.DateTime = planInfo.IncTime;
-                btnStart.Enabled = !planInfo.Enable;
-                btnStop.Enabled = planInfo.Enable;
-                panelControl1.Enabled = panelControl2.Enabled = !planInfo.Enable;
                 txtDbAddr3.Text = planInfo.DbAddr;
                 txtUser3.Text = planInfo.User;
                 txtPwd3.Text = planInfo.Pwd;
                 txtService3.Text = planInfo.ServiceName;
+                checkClear.Checked = planInfo.EnableClear;
+                SetEnable(!planInfo.Enable);
             }
             DoPlainAll();
             DoPlainInc();
+            ClearZip();
         }
         //备份
         private async void btnBackup_Click(object sender, EventArgs e)
@@ -92,6 +92,7 @@ namespace DbBackup
                 DxHelper.MsgBoxHelper.ShowError("请选择备份类型");
                 return;
             }
+
             string dbAddr = txtDbAddr.Text.Trim();
             string user = txtUser.Text.Trim();
             string pwd = txtPwd.Text.Trim();
@@ -105,9 +106,11 @@ namespace DbBackup
                   {
                       try
                       {
+
                           Info("开始全量备份...");
                           var zipFile = DbHelper.BackupDb(dbAddr, user, pwd, service);//全量备份
                           Info($"全量备份完成,文件={zipFile}");
+
                       }
                       catch (Exception ex)
                       {
@@ -204,13 +207,11 @@ namespace DbBackup
                 User = txtUser3.Text.Trim(),
                 Pwd = txtPwd3.Text.Trim(),
                 ServiceName = txtService3.Text.Trim(),
+                EnableClear = checkClear.Checked,
             };
             info.IncWeekDay = dic.First(p => p.Value == txtWeekDays.Text).Key;
             File.WriteAllText("Data\\plan.json", JsonConvert.SerializeObject(info));
-            panelControl1.Enabled = false;
-            panelControl2.Enabled = false;
-            btnStart.Enabled = false;
-            btnStop.Enabled = true;
+            SetEnable(false);
             Info("备份计划已启动");
         }
         //停止备份计划
@@ -226,15 +227,89 @@ namespace DbBackup
                 User = txtUser3.Text.Trim(),
                 Pwd = txtPwd3.Text.Trim(),
                 ServiceName = txtService3.Text.Trim(),
+                EnableClear = checkClear.Checked,
             };
             info.IncWeekDay = dic.First(p => p.Value == txtWeekDays.Text).Key;
             File.WriteAllText("Data\\plan.json", JsonConvert.SerializeObject(info));
-            panelControl1.Enabled = true;
-            panelControl2.Enabled = true;
-            btnStart.Enabled = true;
-            btnStop.Enabled = false;
+            SetEnable(true);
             Info("备份计划已停止");
+        }
 
+        private void ClearZip()
+        {
+            Task.Run(() =>
+            {
+                while (!this.IsDisposed && !this.Disposing)
+                {
+                    try
+                    {
+                        string file = "Data\\plan.json";
+                        if (File.Exists(file))
+                        {
+                            PlanInfo info = null;
+                            try
+                            {
+                                var str = File.ReadAllText(file);
+                                info = JsonConvert.DeserializeObject<PlanInfo>(str);
+                            }
+                            catch (Exception ex)
+                            {
+                                Serilog.Log.Error("自动清理-->plan.json文件读取异常", ex);
+                                continue;
+                            }
+                            if (info.Enable && info.EnableClear && !isBackupAll)//自动清理 删除之前的全量备份文件
+                            {
+                                Info("自动清理-->开始自动清理...");
+                                var dicFiles = Directory.EnumerateFiles($@"{AppDomain.CurrentDomain.BaseDirectory}\Backup", "all-*.7z", SearchOption.TopDirectoryOnly)
+                                   .ToDictionary(p => p, q =>
+                                   {
+                                       var name = Path.GetFileName(q);
+                                       var idx = name.IndexOf("-");
+                                       var time = DateTime.ParseExact(name.Substring(idx + 1, 14), "yyyyMMddHHmmss", null);
+                                       return time;
+                                   });
+                                if (dicFiles.Count > 0)
+                                {
+                                    var maxTime = dicFiles.Values.Max();
+                                    int clearCount = 0;
+                                    foreach (var item in dicFiles)
+                                    {
+                                        if (item.Value != maxTime)
+                                        {
+                                            try
+                                            {
+                                                Info($"自动清理-->正在删除文件[{Path.GetFileName(item.Key)}]...");
+                                                File.Delete(item.Key);
+                                                clearCount++;
+                                            }
+                                            catch (Exception ex)
+                                            {
+                                                Err($"自动清理-->文件[{Path.GetFileName(item.Key)}]删除失败", ex);
+
+                                            }
+                                        }
+                                    }
+                                    Info($"自动清理-->自动清理完成,共删除{clearCount}个文件");
+                                }
+                                else
+                                {
+                                    Info($"自动清理-->自动清理完成,共删除{0}个文件");
+                                }
+                            }
+                        }
+                    }
+                    catch (Exception ex)
+                    {
+
+                        Err($"自动清理-->自动清理异常", ex);
+
+                    }
+                    finally
+                    {
+                        Wait(60);
+                    }
+                }
+            });
         }
 
         private void DoPlainAll()
@@ -272,6 +347,7 @@ namespace DbBackup
 
                                 if (doAllBackup)
                                 {
+                                    isBackupAll = true;
                                     Info("备份计划-->开始全量备份...");
                                     var zipFile = DbHelper.BackupDb(dbAddr, user, pwd, service);//全量备份
                                     Info($"备份计划-->全量备份完成,文件={zipFile}");
@@ -284,6 +360,7 @@ namespace DbBackup
                             }
                             finally
                             {
+                                isBackupAll = false;
                                 if (doAllBackup)
                                     Wait(60);
                             }
@@ -334,7 +411,7 @@ namespace DbBackup
                                 {
                                     Info("备份计划-->开始增量备份...");
                                     //获取最后一个全量备份的文件
-                                    var lastFile = Directory.EnumerateFiles("Backup","all-*.7z")
+                                    var lastFile = Directory.EnumerateFiles("Backup", "all-*.7z")
                                         .Where(p => Path.GetFileNameWithoutExtension(p).Length == 18)
                                         .OrderByDescending(p =>
                                         {
@@ -392,6 +469,18 @@ namespace DbBackup
                 dir = AppDomain.CurrentDomain.BaseDirectory;
             System.Diagnostics.Process.Start("explorer.exe", dir);
         }
+        private void SetEnable(bool enable)
+        {
+            txtDbAddr3.Enabled = enable;
+            txtUser3.Enabled = enable;
+            txtPwd3.Enabled = enable;
+            txtService3.Enabled = enable;
+            checkClear.Enabled = enable;
+            panelControl1.Enabled = enable;
+            panelControl2.Enabled = enable;
+            btnStart.Enabled = enable;
+            btnStop.Enabled = !enable;
+        }
         private void txtBackupIncrement_CheckedChanged(object sender, EventArgs e)
         {
             CheckEdit currentCheckBox = (CheckEdit)sender;
@@ -442,7 +531,6 @@ namespace DbBackup
                 gvLog.RefreshData();
             }));
         }
-
         private void btnConnectTest1_Click(object sender, EventArgs e)
         {
             try
@@ -475,7 +563,6 @@ namespace DbBackup
                 Err("数据库连接测试失败!", ex);
             }
         }
-
         private void ClearNoneZipFile()
         {
             var files = Directory.GetFiles("Backup");
@@ -502,7 +589,6 @@ namespace DbBackup
             }
         }
 
-
         //获取当前时间所在月份的最大天数
         private int GetMaxDay()
         {
@@ -512,7 +598,5 @@ namespace DbBackup
             return d2.Day;
 
         }
-
-
     }
 }

+ 5 - 0
DbBackup/ViewModel/PlanInfo.cs

@@ -53,5 +53,10 @@ namespace DbBackup.ViewModel
         /// 服务名
         /// </summary>
         public string ServiceName { get; set; }
+
+        /// <summary>
+        /// 是否自动清理
+        /// </summary>
+        public bool EnableClear { get; set; }
     }
 }