-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
1397 lines (1202 loc) · 59.9 KB
/
Copy pathMainForm.cs
File metadata and controls
1397 lines (1202 loc) · 59.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using FileOrganizer.Services;
using FileOrganizer.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace FileOrganizer
{
public partial class MainForm : Form
{
private readonly IFileOrganizerService _fileOrganizerService;
private readonly IStatisticsService _statisticsService;
private readonly ICleanupService _cleanupService;
private readonly ISchedulerService _schedulerService;
private readonly IDatabaseService _databaseService;
private readonly ILogger<MainForm> _logger;
private readonly AppConfig _config;
private TabControl _tabControl;
public MainForm(
IFileOrganizerService fileOrganizerService,
IStatisticsService statisticsService,
ICleanupService cleanupService,
ISchedulerService schedulerService,
IDatabaseService databaseService,
ILogger<MainForm> logger,
IOptions<AppConfig> config)
{
_fileOrganizerService = fileOrganizerService;
_statisticsService = statisticsService;
_cleanupService = cleanupService;
_schedulerService = schedulerService;
_databaseService = databaseService;
_logger = logger;
_config = config.Value;
InitializeComponent();
InitializeDatabase();
_ = _schedulerService.StartSchedulerAsync();
}
private async void InitializeDatabase()
{
try
{
await _databaseService.InitializeDatabaseAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing database");
}
}
private void InitializeComponent()
{
this.SuspendLayout();
this.AutoScaleDimensions = new SizeF(7F, 15F);
this.AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new Size(1200, 700);
this.Text = "Smart File Management System";
this.MinimumSize = new Size(1000, 600);
this.StartPosition = FormStartPosition.CenterScreen;
this.FormClosing += async (s, e) => await _schedulerService.StopSchedulerAsync();
_tabControl = new TabControl
{
Location = new Point(10, 10),
Size = new Size(1180, 680),
Dock = DockStyle.Fill
};
_tabControl.TabPages.Add(CreateOrganizeTab());
_tabControl.TabPages.Add(CreateStatisticsTab());
_tabControl.TabPages.Add(CreateRulesTab());
_tabControl.TabPages.Add(CreateCleanupTab());
_tabControl.TabPages.Add(CreateSchedulerTab());
_tabControl.TabPages.Add(CreateHistoryTab());
_tabControl.TabPages.Add(CreateSettingsTab());
this.Controls.Add(_tabControl);
this.ResumeLayout(false);
}
private TabPage CreateOrganizeTab()
{
var tab = new TabPage { Text = "Organize Files", Padding = new Padding(10) };
var lblPath = new Label { Text = "Source Folder:", Location = new Point(10, 15), AutoSize = true };
var txtPath = new TextBox
{
Location = new Point(120, 12),
Size = new Size(800, 25),
Text = _config.DefaultSourcePath
};
var btnBrowse = new Button
{
Text = "Browse...",
Location = new Point(930, 12),
Size = new Size(100, 25)
};
btnBrowse.Click += (s, e) =>
{
using (var dialog = new FolderBrowserDialog { SelectedPath = txtPath.Text })
{
if (dialog.ShowDialog() == DialogResult.OK)
txtPath.Text = dialog.SelectedPath;
}
};
var btnOrganize = new Button
{
Text = "Organize Now",
Location = new Point(10, 55),
Size = new Size(150, 35),
BackColor = Color.FromArgb(0, 122, 204),
ForeColor = Color.White,
Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold)
};
var btnStartWatch = new Button
{
Text = "Start Real-Time Watch",
Location = new Point(170, 55),
Size = new Size(150, 35),
BackColor = Color.FromArgb(107, 142, 35),
ForeColor = Color.White
};
var btnStopWatch = new Button
{
Text = "Stop Watching",
Location = new Point(330, 55),
Size = new Size(150, 35),
BackColor = Color.FromArgb(220, 20, 60),
ForeColor = Color.White
};
var btnScanNow = new Button
{
Text = "Scan Now",
Location = new Point(490, 55),
Size = new Size(100, 35),
BackColor = Color.FromArgb(30, 144, 255),
ForeColor = Color.White
};
var progressBar = new ProgressBar
{
Location = new Point(10, 100),
Size = new Size(1020, 30),
Visible = false
};
var logBox = new RichTextBox
{
Location = new Point(10, 140),
Size = new Size(1020, 450),
ReadOnly = true,
BackColor = Color.White
};
btnOrganize.Click += async (s, e) =>
{
if (string.IsNullOrWhiteSpace(txtPath.Text) || !Directory.Exists(txtPath.Text))
{
MessageBox.Show("Please select a valid folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
btnOrganize.Enabled = false;
progressBar.Visible = true;
logBox.Clear();
logBox.AppendText("\n=== ORGANIZATION STARTED ===\n");
var files = Directory.GetFiles(txtPath.Text, "*", SearchOption.TopDirectoryOnly);
progressBar.Maximum = files.Length > 0 ? files.Length : 1;
progressBar.Value = 0;
var progress = new Progress<string>(msg =>
{
logBox.AppendText(msg + "\n");
if (progressBar.Value < progressBar.Maximum)
progressBar.Value++;
});
try
{
// Actual file movement with rules enabled
var rules = await _databaseService.GetAllRulesAsync();
var result = await _fileOrganizerService.OrganizeFilesWithRulesAsync(txtPath.Text, rules, progress);
MessageBox.Show($"✓ Successfully moved {result.ProcessedFiles} files!", "Organization Complete",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
btnOrganize.Enabled = true;
}
};
btnStartWatch.Click += (s, e) =>
{
_fileOrganizerService.StartRealTimeWatching(txtPath.Text);
logBox.AppendText("✓ Real-time watching started\n");
btnStartWatch.Enabled = false;
btnStopWatch.Enabled = true;
};
btnStopWatch.Click += (s, e) =>
{
_fileOrganizerService.StopRealTimeWatching();
logBox.AppendText("✓ Real-time watching stopped\n");
btnStartWatch.Enabled = true;
btnStopWatch.Enabled = false;
};
btnScanNow.Click += async (s, e) =>
{
if (string.IsNullOrWhiteSpace(txtPath.Text) || !Directory.Exists(txtPath.Text))
{
MessageBox.Show("Please select a valid folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
btnScanNow.Enabled = false;
progressBar.Visible = true;
logBox.AppendText("\n=== MANUAL SCAN STARTED (DRY RUN) ===\n");
logBox.AppendText("Note: This prevents accidental file movement. No files will be moved.\n\n");
var files = Directory.GetFiles(txtPath.Text, "*", SearchOption.TopDirectoryOnly);
progressBar.Maximum = files.Length > 0 ? files.Length : 1;
progressBar.Value = 0;
try
{
// Scan files acts strictly as a dry run - we use get preview which calculates matches but doesn't move files
var rules = await _databaseService.GetAllRulesAsync();
var preview = await _fileOrganizerService.GetPreviewChangesAsync(txtPath.Text, rules);
int matchCount = 0;
foreach (var p in preview)
{
logBox.AppendText($"[SCAN] {p.FileName}\n");
logBox.AppendText($" -> Matches Category/Rule: {p.Category}\n");
logBox.AppendText($" -> Would move to: {p.DestinationPath}\n");
if (progressBar.Value < progressBar.Maximum) progressBar.Value++;
matchCount++;
}
logBox.AppendText($"\n✓ Scan Complete: Filtered matched {matchCount} files. (Dry Run - nothing moved)\n");
MessageBox.Show($"✓ Scanned {matchCount} files! No files were accidentally moved.", "Scan Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
logBox.AppendText($"❌ Error: {ex.Message}\n");
}
finally
{
btnScanNow.Enabled = true;
}
};
var btnPreview = new Button
{
Text = "Preview Changes",
Location = new Point(600, 55),
Size = new Size(120, 35),
BackColor = Color.FromArgb(255, 140, 0),
ForeColor = Color.White
};
btnPreview.Click += async (s, e) =>
{
if (string.IsNullOrWhiteSpace(txtPath.Text) || !Directory.Exists(txtPath.Text))
{
MessageBox.Show("Please select a valid folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
btnPreview.Enabled = false;
logBox.Clear();
logBox.AppendText("🔍 Generating preview of changes...\n\n");
try
{
var preview = await _fileOrganizerService.GetPreviewChangesAsync(txtPath.Text);
if (preview.Count == 0)
{
logBox.AppendText("No files to organize.\n");
MessageBox.Show("No files found to organize", "Preview", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
long totalSize = 0;
int conflictCount = 0;
logBox.AppendText($"📋 Preview Summary:\n");
logBox.AppendText($"Total files to organize: {preview.Count}\n\n");
foreach (var change in preview)
{
totalSize += change.FileSize;
if (change.WillConflict) conflictCount++;
logBox.AppendText($"📄 {change.FileName}\n");
logBox.AppendText($" Current: {change.CurrentPath}\n");
logBox.AppendText($" → Destination: {change.DestinationPath}\n");
logBox.AppendText($" Category: {change.Category}\n");
if (change.WillConflict)
logBox.AppendText($" ⚠ Conflict! Strategy: {change.ConflictResolution}\n");
logBox.AppendText("\n");
}
logBox.AppendText($"\n📊 Total Size: {FormatBytes(totalSize)}\n");
logBox.AppendText($"⚠ Conflicts: {conflictCount}\n");
logBox.AppendText($"\n✓ Preview generated successfully. Click 'Organize Now' to apply these changes.\n");
}
catch (Exception ex)
{
logBox.AppendText($"❌ Error generating preview: {ex.Message}\n");
MessageBox.Show($"Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
btnPreview.Enabled = true;
}
};
tab.Controls.AddRange(new Control[] { lblPath, txtPath, btnBrowse, btnOrganize, btnStartWatch, btnStopWatch, btnScanNow, btnPreview, progressBar, logBox });
return tab;
}
private TabPage CreateStatisticsTab()
{
var tab = new TabPage { Text = "📊 Statistics", Padding = new Padding(10) };
var lblPath = new Label { Text = "Analyze Folder:", Location = new Point(10, 15), AutoSize = true };
var txtPath = new TextBox
{
Location = new Point(120, 12),
Size = new Size(800, 25),
Text = _config.DefaultSourcePath
};
var btnBrowse = new Button
{
Text = "Browse...",
Location = new Point(930, 12),
Size = new Size(100, 25)
};
btnBrowse.Click += (s, e) =>
{
using (var dialog = new FolderBrowserDialog { SelectedPath = txtPath.Text })
{
if (dialog.ShowDialog() == DialogResult.OK)
txtPath.Text = dialog.SelectedPath;
}
};
var btnAnalyze = new Button
{
Text = "Analyze",
Location = new Point(10, 55),
Size = new Size(120, 35),
BackColor = Color.FromArgb(0, 122, 204),
ForeColor = Color.White,
Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold)
};
var statsBox = new RichTextBox
{
Location = new Point(10, 100),
Size = new Size(1020, 490),
ReadOnly = true,
BackColor = Color.WhiteSmoke
};
btnAnalyze.Click += async (s, e) =>
{
if (string.IsNullOrWhiteSpace(txtPath.Text) || !Directory.Exists(txtPath.Text))
{
MessageBox.Show("Please select a valid folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
btnAnalyze.Enabled = false;
statsBox.Clear();
statsBox.AppendText("Analyzing folder...\n\n");
try
{
var stats = await _statisticsService.GetFolderStatisticsAsync(txtPath.Text);
var storage = await _statisticsService.GetStorageByCategoryAsync(txtPath.Text);
var largest = await _statisticsService.GetLargestFoldersAsync(txtPath.Text, 5);
statsBox.Clear();
statsBox.AppendText($"📁 FOLDER ANALYSIS: {txtPath.Text}\n");
statsBox.AppendText(new string('=', 100) + "\n\n");
statsBox.AppendText($"Total Size: {FolderStatistics.FormatBytes(stats.TotalSize)}\n");
statsBox.AppendText($"Total Files: {stats.TotalFiles}\n");
statsBox.AppendText($"Total Folders: {stats.TotalFolders}\n");
statsBox.AppendText($"Last Scanned: {stats.LastUpdated:yyyy-MM-dd HH:mm:ss}\n\n");
statsBox.AppendText("FILES BY CATEGORY:\n");
statsBox.AppendText(new string('-', 50) + "\n");
foreach (var cat in stats.FilesByCategory.OrderByDescending(x => x.Value))
{
var catStorage = storage.ContainsKey(cat.Key) ? FolderStatistics.FormatBytes(storage[cat.Key]) : "0 B";
statsBox.AppendText($" {cat.Key,-20} {cat.Value,6} files {catStorage,15}\n");
}
statsBox.AppendText("\nLARGEST FOLDERS:\n");
statsBox.AppendText(new string('-', 50) + "\n");
foreach (var folder in largest)
{
statsBox.AppendText($" {folder.folder,-40} {FolderStatistics.FormatBytes(folder.size),15}\n");
}
}
catch (Exception ex)
{
statsBox.AppendText($"❌ Error: {ex.Message}");
}
finally
{
btnAnalyze.Enabled = true;
}
};
var btnExportReport = new Button
{
Text = "Export Report",
Location = new Point(140, 55),
Size = new Size(120, 35),
BackColor = Color.FromArgb(34, 139, 34),
ForeColor = Color.White,
Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold)
};
btnExportReport.Click += (s, e) =>
{
using (var dialog = new SaveFileDialog { Filter = "Text Files|*.txt|CSV Files|*.csv", DefaultExt = ".txt", FileName = $"FileOrganizer_Report_{DateTime.Now:yyyy-MM-dd}.txt" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
System.IO.File.WriteAllText(dialog.FileName, statsBox.Text);
MessageBox.Show($"✓ Report exported to {Path.GetFileName(dialog.FileName)}", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
};
tab.Controls.AddRange(new Control[] { lblPath, txtPath, btnBrowse, btnAnalyze, btnExportReport, statsBox });
return tab;
}
private TabPage CreateRulesTab()
{
var tab = new TabPage { Text = "⚙️ Custom Rules", Padding = new Padding(10) };
var lblRuleName = new Label { Text = "Rule Name:", Location = new Point(10, 15), AutoSize = true };
var txtRuleName = new TextBox { Location = new Point(120, 12), Size = new Size(250, 25) };
var lblPattern = new Label { Text = "File Pattern:", Location = new Point(10, 45), AutoSize = true };
var txtPattern = new TextBox { Location = new Point(120, 42), Size = new Size(250, 25), Text = "*.pdf" };
var lblFolder = new Label { Text = "Target Folder:", Location = new Point(10, 75), AutoSize = true };
var txtFolder = new TextBox { Location = new Point(120, 72), Size = new Size(250, 25) };
var chkKeyword = new CheckBox { Text = "Keyword Rule", Location = new Point(10, 105), AutoSize = true };
var lblKeyword = new Label { Text = "Keyword:", Location = new Point(10, 135), AutoSize = true };
var txtKeyword = new TextBox { Location = new Point(120, 132), Size = new Size(250, 25) };
chkKeyword.CheckedChanged += (s, e) =>
{
txtPattern.Enabled = !chkKeyword.Checked;
txtFolder.Enabled = !chkKeyword.Checked;
txtKeyword.Enabled = chkKeyword.Checked;
};
var btnBrowse = new Button { Text = "Browse...", Location = new Point(380, 72), Size = new Size(80, 25) };
btnBrowse.Click += (s, e) =>
{
using (var dialog = new FolderBrowserDialog())
{
if (dialog.ShowDialog() == DialogResult.OK)
txtFolder.Text = dialog.SelectedPath;
}
};
var btnAddRule = new Button
{
Text = "Add Rule",
Location = new Point(120, 165),
Size = new Size(100, 30),
BackColor = Color.FromArgb(0, 122, 204),
ForeColor = Color.White
};
var rulesList = new ListBox
{
Location = new Point(10, 205),
Size = new Size(450, 285)
};
var btnDeleteRule = new Button
{
Text = "Delete Selected",
Location = new Point(10, 500),
Size = new Size(120, 30),
BackColor = Color.FromArgb(220, 20, 60),
ForeColor = Color.White
};
var infoBox = new RichTextBox
{
Location = new Point(480, 205),
Size = new Size(540, 325),
ReadOnly = true,
BackColor = Color.WhiteSmoke
};
Func<Task> RefreshRules = async () =>
{
var rules = await _databaseService.GetAllRulesAsync();
rulesList.Items.Clear();
foreach (var rule in rules)
{
string display = rule.IsKeywordRule
? $"{(rule.Enabled ? "✓" : "✗")} {rule.RuleName} (Keyword: {rule.Keyword})"
: $"{(rule.Enabled ? "✓" : "✗")} {rule.RuleName} ({rule.FilePattern})";
rulesList.Items.Add(display);
}
};
btnAddRule.Click += async (s, e) =>
{
if (string.IsNullOrWhiteSpace(txtRuleName.Text))
{
MessageBox.Show("Please enter a rule name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (chkKeyword.Checked && string.IsNullOrWhiteSpace(txtKeyword.Text))
{
MessageBox.Show("Please enter a keyword for keyword rule", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var rule = new OrganizationRule
{
RuleName = txtRuleName.Text,
FilePattern = chkKeyword.Checked ? "*.*" : txtPattern.Text,
TargetFolder = chkKeyword.Checked ? "" : txtFolder.Text,
IsKeywordRule = chkKeyword.Checked,
Keyword = chkKeyword.Checked ? txtKeyword.Text : null,
Enabled = true
};
await _databaseService.AddOrUpdateRuleAsync(rule);
await RefreshRules();
MessageBox.Show("✓ Rule added successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtRuleName.Clear();
txtPattern.Text = "*.pdf";
txtFolder.Clear();
chkKeyword.Checked = false;
txtKeyword.Clear();
};
rulesList.SelectedIndexChanged += async (s, e) =>
{
if (rulesList.SelectedIndex >= 0)
{
var rules = await _databaseService.GetAllRulesAsync();
var rule = rules[rulesList.SelectedIndex];
infoBox.Clear();
infoBox.AppendText($"Rule: {rule.RuleName}\n");
infoBox.AppendText(new string('=', 50) + "\n\n");
infoBox.AppendText($"Status: {(rule.Enabled ? "✓ Enabled" : "✗ Disabled")}\n");
if (rule.IsKeywordRule)
{
infoBox.AppendText($"Type: Keyword Rule\n");
infoBox.AppendText($"Keyword: {rule.Keyword}\n");
infoBox.AppendText($"Target Folder: Auto-generated ({rule.Keyword})\n");
}
else
{
infoBox.AppendText($"File Pattern: {rule.FilePattern}\n");
infoBox.AppendText($"Target Folder: {rule.TargetFolder}\n");
}
infoBox.AppendText($"Min Size: {FolderStatistics.FormatBytes(rule.MinSizeBytes)}\n");
infoBox.AppendText($"Max Size: {FolderStatistics.FormatBytes(rule.MaxSizeBytes)}\n");
infoBox.AppendText($"Created: {rule.CreatedDate:yyyy-MM-dd HH:mm:ss}\n");
}
};
btnDeleteRule.Click += async (s, e) =>
{
if (rulesList.SelectedIndex >= 0)
{
var rules = await _databaseService.GetAllRulesAsync();
if (MessageBox.Show("Delete this rule?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
await _databaseService.DeleteRuleAsync(rules[rulesList.SelectedIndex].Id);
await RefreshRules();
}
}
};
_ = RefreshRules();
tab.Controls.AddRange(new Control[] { lblRuleName, txtRuleName, lblPattern, txtPattern, lblFolder, txtFolder, chkKeyword, lblKeyword, txtKeyword, btnBrowse, btnAddRule, rulesList, btnDeleteRule, infoBox });
return tab;
}
private TabPage CreateCleanupTab()
{
var tab = new TabPage { Text = "🧹 Cleanup Tools", Padding = new Padding(10) };
var lblPath = new Label { Text = "Target Folder:", Location = new Point(10, 15), AutoSize = true };
var txtPath = new TextBox
{
Location = new Point(120, 12),
Size = new Size(800, 25),
Text = _config.DefaultSourcePath
};
var btnBrowse = new Button
{
Text = "Browse...",
Location = new Point(930, 12),
Size = new Size(100, 25)
};
btnBrowse.Click += (s, e) =>
{
using (var dialog = new FolderBrowserDialog { SelectedPath = txtPath.Text })
{
if (dialog.ShowDialog() == DialogResult.OK)
txtPath.Text = dialog.SelectedPath;
}
};
var lblDays = new Label { Text = "Delete files older than (days):", Location = new Point(10, 50), AutoSize = true };
var spinDays = new NumericUpDown { Location = new Point(250, 47), Value = 30, Minimum = 1, Maximum = 365 };
// Row 1: Remove Old Files
var btnRemoveOldRecycle = new Button
{
Text = "Remove Old → Recycle",
Location = new Point(10, 85),
Size = new Size(160, 35),
BackColor = Color.FromArgb(70, 130, 180),
ForeColor = Color.White
};
var btnRemoveOldPermanent = new Button
{
Text = "Remove Old → Delete",
Location = new Point(180, 85),
Size = new Size(160, 35),
BackColor = Color.FromArgb(220, 20, 60),
ForeColor = Color.White
};
// Row 2: Remove Empty Folders
var btnRemoveEmptyRecycle = new Button
{
Text = "Empty Folders → Recycle",
Location = new Point(10, 125),
Size = new Size(160, 35),
BackColor = Color.FromArgb(70, 130, 180),
ForeColor = Color.White
};
var btnRemoveEmptyPermanent = new Button
{
Text = "Empty Folders → Delete",
Location = new Point(180, 125),
Size = new Size(160, 35),
BackColor = Color.FromArgb(220, 20, 60),
ForeColor = Color.White
};
// Row 3: Clean Duplicates
var btnCleanDuplicatesRecycle = new Button
{
Text = "Duplicates → Recycle",
Location = new Point(10, 165),
Size = new Size(160, 35),
BackColor = Color.FromArgb(70, 130, 180),
ForeColor = Color.White
};
var btnCleanDuplicatesPermanent = new Button
{
Text = "Duplicates → Delete",
Location = new Point(180, 165),
Size = new Size(160, 35),
BackColor = Color.FromArgb(220, 20, 60),
ForeColor = Color.White
};
var resultBox = new RichTextBox
{
Location = new Point(10, 210),
Size = new Size(1020, 380),
ReadOnly = true,
BackColor = Color.WhiteSmoke
};
btnRemoveOldRecycle.Click += async (s, e) =>
{
if (!Directory.Exists(txtPath.Text))
{
MessageBox.Show("Invalid folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
resultBox.Clear();
resultBox.AppendText($"Removing files older than {spinDays.Value} days (to Recycle Bin)...\n\n");
var progress = new Progress<string>(msg => resultBox.AppendText(msg + "\n"));
var count = await _cleanupService.RemoveOldFilesAsync(txtPath.Text, (int)spinDays.Value, DeletionMode.RecycleBin, progress);
resultBox.AppendText($"\n✓ Removed {count} old files to Recycle Bin");
};
btnRemoveOldPermanent.Click += async (s, e) =>
{
if (!Directory.Exists(txtPath.Text))
{
MessageBox.Show("Invalid folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var result = MessageBox.Show(
"Are you sure? Files will be PERMANENTLY DELETED and cannot be recovered!",
"Permanent Delete Confirmation",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (result != DialogResult.Yes) return;
resultBox.Clear();
resultBox.AppendText($"Permanently deleting files older than {spinDays.Value} days...\n\n");
var progress = new Progress<string>(msg => resultBox.AppendText(msg + "\n"));
var count = await _cleanupService.RemoveOldFilesAsync(txtPath.Text, (int)spinDays.Value, DeletionMode.Permanent, progress);
resultBox.AppendText($"\n✓ Permanently deleted {count} old files");
};
btnRemoveEmptyRecycle.Click += async (s, e) =>
{
if (!Directory.Exists(txtPath.Text))
{
MessageBox.Show("Invalid folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
resultBox.Clear();
resultBox.AppendText("Removing empty folders (to Recycle Bin)...\n\n");
var progress = new Progress<string>(msg => resultBox.AppendText(msg + "\n"));
var count = await _cleanupService.RemoveEmptyFoldersAsync(txtPath.Text, DeletionMode.RecycleBin, progress);
resultBox.AppendText($"\n✓ Removed {count} empty folders to Recycle Bin");
};
btnRemoveEmptyPermanent.Click += async (s, e) =>
{
if (!Directory.Exists(txtPath.Text))
{
MessageBox.Show("Invalid folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var result = MessageBox.Show(
"Are you sure? Folders will be PERMANENTLY DELETED and cannot be recovered!",
"Permanent Delete Confirmation",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (result != DialogResult.Yes) return;
resultBox.Clear();
resultBox.AppendText("Permanently deleting empty folders...\n\n");
var progress = new Progress<string>(msg => resultBox.AppendText(msg + "\n"));
var count = await _cleanupService.RemoveEmptyFoldersAsync(txtPath.Text, DeletionMode.Permanent, progress);
resultBox.AppendText($"\n✓ Permanently deleted {count} empty folders");
};
btnCleanDuplicatesRecycle.Click += async (s, e) =>
{
if (!Directory.Exists(txtPath.Text))
{
MessageBox.Show("Invalid folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
resultBox.Clear();
resultBox.AppendText("Scanning for duplicates and cleaning up (to Recycle Bin)...\n\n");
var progress = new Progress<string>(msg => resultBox.AppendText(msg + "\n"));
var freed = await _cleanupService.CleanupDuplicatesAsync(txtPath.Text, DeletionMode.RecycleBin, progress);
resultBox.AppendText($"\n✓ Freed {FolderStatistics.FormatBytes(freed)} of disk space (to Recycle Bin)");
};
btnCleanDuplicatesPermanent.Click += async (s, e) =>
{
if (!Directory.Exists(txtPath.Text))
{
MessageBox.Show("Invalid folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var result = MessageBox.Show(
"Are you sure? Duplicates will be PERMANENTLY DELETED and cannot be recovered!",
"Permanent Delete Confirmation",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (result != DialogResult.Yes) return;
resultBox.Clear();
resultBox.AppendText("Permanently deleting duplicate files...\n\n");
var progress = new Progress<string>(msg => resultBox.AppendText(msg + "\n"));
var freed = await _cleanupService.CleanupDuplicatesAsync(txtPath.Text, DeletionMode.Permanent, progress);
resultBox.AppendText($"\n✓ Permanently deleted duplicates, freed {FolderStatistics.FormatBytes(freed)} of disk space");
};
tab.Controls.AddRange(new Control[] {
lblPath, txtPath, btnBrowse, lblDays, spinDays,
btnRemoveOldRecycle, btnRemoveOldPermanent,
btnRemoveEmptyRecycle, btnRemoveEmptyPermanent,
btnCleanDuplicatesRecycle, btnCleanDuplicatesPermanent,
resultBox
});
return tab;
}
private TabPage CreateSchedulerTab()
{
var tab = new TabPage { Text = "⏰ Scheduler", Padding = new Padding(10) };
var lblTaskName = new Label { Text = "Task Name:", Location = new Point(10, 15), AutoSize = true };
var txtTaskName = new TextBox { Location = new Point(120, 12), Size = new Size(300, 25) };
var lblFolder = new Label { Text = "Source Folder:", Location = new Point(10, 45), AutoSize = true };
var txtFolder = new TextBox { Location = new Point(120, 42), Size = new Size(300, 25) };
var btnBrowse = new Button { Text = "Browse...", Location = new Point(430, 42), Size = new Size(80, 25) };
btnBrowse.Click += (s, e) =>
{
using (var dialog = new FolderBrowserDialog())
{
if (dialog.ShowDialog() == DialogResult.OK)
txtFolder.Text = dialog.SelectedPath;
}
};
var chkCleanup = new CheckBox { Text = "Remove Old Files", Location = new Point(10, 75), AutoSize = true, Checked = true };
var chkDuplicates = new CheckBox { Text = "Clean Duplicates", Location = new Point(200, 75), AutoSize = true };
var chkEmpty = new CheckBox { Text = "Remove Empty Folders", Location = new Point(400, 75), AutoSize = true };
var lblDay = new Label { Text = "Day:", Location = new Point(10, 105), AutoSize = true };
var cmbDay = new ComboBox { Location = new Point(50, 102), Size = new Size(150, 25), DropDownStyle = ComboBoxStyle.DropDownList };
foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek)))
cmbDay.Items.Add(day);
cmbDay.SelectedIndex = 0;
var lblTime = new Label { Text = "Time (HH:mm):", Location = new Point(220, 105), AutoSize = true };
var txtTime = new TextBox { Location = new Point(320, 102), Size = new Size(100, 25), Text = "02:00" };
var btnAddTask = new Button
{
Text = "Add Scheduled Task",
Location = new Point(10, 140),
Size = new Size(150, 35),
BackColor = Color.FromArgb(0, 122, 204),
ForeColor = Color.White
};
var tasksList = new ListBox
{
Location = new Point(10, 185),
Size = new Size(450, 305)
};
var btnDeleteTask = new Button
{
Text = "Delete Selected",
Location = new Point(10, 500),
Size = new Size(120, 30),
BackColor = Color.FromArgb(220, 20, 60),
ForeColor = Color.White
};
var infoBox = new RichTextBox
{
Location = new Point(480, 185),
Size = new Size(540, 345),
ReadOnly = true,
BackColor = Color.WhiteSmoke
};
Func<Task> RefreshTasks = async () =>
{
var tasks = await _databaseService.GetAllScheduledTasksAsync();
tasksList.Items.Clear();
foreach (var task in tasks)
tasksList.Items.Add($"{(task.Enabled ? "✓" : "✗")} {task.TaskName}");
};
btnAddTask.Click += async (s, e) =>
{
if (string.IsNullOrWhiteSpace(txtTaskName.Text) || string.IsNullOrWhiteSpace(txtFolder.Text))
{
MessageBox.Show("Please fill all fields", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!TimeSpan.TryParse(txtTime.Text, out var time))
{
MessageBox.Show("Invalid time format", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var task = new ScheduledTask
{
TaskName = txtTaskName.Text,
SourceFolder = txtFolder.Text,
EnableCleanup = chkCleanup.Checked,
EnableDuplicateFinder = chkDuplicates.Checked,
EnableEmptyFolderRemover = chkEmpty.Checked,
ScheduleDay = (DayOfWeek)cmbDay.SelectedItem,
ScheduleTime = time,
Enabled = true
};
await _databaseService.AddOrUpdateScheduledTaskAsync(task);
await RefreshTasks();
MessageBox.Show("✓ Task scheduled!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtTaskName.Clear();
txtFolder.Clear();
};
tasksList.SelectedIndexChanged += async (s, e) =>
{
if (tasksList.SelectedIndex >= 0)
{
var tasks = await _databaseService.GetAllScheduledTasksAsync();
var task = tasks[tasksList.SelectedIndex];
infoBox.Clear();
infoBox.AppendText($"Task: {task.TaskName}\n");
infoBox.AppendText(new string('=', 50) + "\n\n");
infoBox.AppendText($"Status: {(task.Enabled ? "✓ Enabled" : "✗ Disabled")}\n");
infoBox.AppendText($"Folder: {task.SourceFolder}\n");
infoBox.AppendText($"Schedule: {task.ScheduleDay} at {task.ScheduleTime:hh\\:mm}\n\n");
infoBox.AppendText("Operations:\n");
if (task.EnableCleanup) infoBox.AppendText(" ✓ Remove old files\n");
if (task.EnableDuplicateFinder) infoBox.AppendText(" ✓ Clean duplicates\n");
if (task.EnableEmptyFolderRemover) infoBox.AppendText(" ✓ Remove empty folders\n");
if (task.LastExecuted != DateTime.MinValue)
infoBox.AppendText($"\nLast Executed: {task.LastExecuted:yyyy-MM-dd HH:mm:ss}\n");
}
};
btnDeleteTask.Click += async (s, e) =>
{
if (tasksList.SelectedIndex >= 0)
{
var tasks = await _databaseService.GetAllScheduledTasksAsync();