Browse Source

Много рефакторинга. Теперь методы не влияющие на MainForm перенесены в TaskController. Добавлены обработчики _textChanged для TextBox'ов (отслеживание для запуска нового задания).

Добавлены методы restoreLastSession, changeVisibiltyResultViewer. Добавлен SearchQueryModel для хранения параметров поиска во время работы приложения.
release
Никита 6 years ago
parent
commit
7a7f3c8df2
  1. 2
      fileFinder/App.config
  2. 5
      fileFinder/MainForm.Designer.cs
  3. 153
      fileFinder/MainForm.cs
  4. 6
      fileFinder/MainSettings.Designer.cs
  5. 2
      fileFinder/MainSettings.settings
  6. 15
      fileFinder/SearchQueryModel.cs
  7. 137
      fileFinder/TaskController.cs
  8. 1
      fileFinder/fileFinder.csproj

2
fileFinder/App.config

@ -10,7 +10,7 @@
</startup> </startup>
<userSettings> <userSettings>
<fileFinder.MainSettings> <fileFinder.MainSettings>
<setting name="urlDirectory" serializeAs="String"> <setting name="fileUrl" serializeAs="String">
<value>C:\nextcloud\</value> <value>C:\nextcloud\</value>
</setting> </setting>
<setting name="fileNameQuery" serializeAs="String"> <setting name="fileNameQuery" serializeAs="String">

5
fileFinder/MainForm.Designer.cs

@ -72,6 +72,7 @@
this.curDirTextBox.Size = new System.Drawing.Size(650, 20); this.curDirTextBox.Size = new System.Drawing.Size(650, 20);
this.curDirTextBox.TabIndex = 1; this.curDirTextBox.TabIndex = 1;
this.curDirTextBox.Text = "C:\\Users\\itsmy_000\\Desktop\\a\\"; this.curDirTextBox.Text = "C:\\Users\\itsmy_000\\Desktop\\a\\";
this.curDirTextBox.TextChanged += new System.EventHandler(this.curDirTextBox_TextChanged);
this.curDirTextBox.Enter += new System.EventHandler(this.curDirTextBox_Enter); this.curDirTextBox.Enter += new System.EventHandler(this.curDirTextBox_Enter);
// //
// splitContainer // splitContainer
@ -105,7 +106,7 @@
this.handleSearchBtn.Name = "handleSearchBtn"; this.handleSearchBtn.Name = "handleSearchBtn";
this.handleSearchBtn.Size = new System.Drawing.Size(120, 21); this.handleSearchBtn.Size = new System.Drawing.Size(120, 21);
this.handleSearchBtn.TabIndex = 5; this.handleSearchBtn.TabIndex = 5;
this.handleSearchBtn.Text = "Start/Pause"; this.handleSearchBtn.Text = "Start Task";
this.handleSearchBtn.UseVisualStyleBackColor = true; this.handleSearchBtn.UseVisualStyleBackColor = true;
this.handleSearchBtn.Click += new System.EventHandler(this.handleSearchBtn_Click); this.handleSearchBtn.Click += new System.EventHandler(this.handleSearchBtn_Click);
// //
@ -116,6 +117,7 @@
this.innerQueryTextBox.Size = new System.Drawing.Size(650, 20); this.innerQueryTextBox.Size = new System.Drawing.Size(650, 20);
this.innerQueryTextBox.TabIndex = 4; this.innerQueryTextBox.TabIndex = 4;
this.innerQueryTextBox.Tag = ""; this.innerQueryTextBox.Tag = "";
this.innerQueryTextBox.TextChanged += new System.EventHandler(this.innerQueryTextBox_TextChanged);
// //
// queryTextBox // queryTextBox
// //
@ -125,6 +127,7 @@
this.queryTextBox.TabIndex = 3; this.queryTextBox.TabIndex = 3;
this.queryTextBox.Tag = ""; this.queryTextBox.Tag = "";
this.queryTextBox.Text = "*.txt"; this.queryTextBox.Text = "*.txt";
this.queryTextBox.TextChanged += new System.EventHandler(this.queryTextBox_TextChanged);
// //
// waitOrPauseLabel // waitOrPauseLabel
// //

153
fileFinder/MainForm.cs

@ -17,6 +17,7 @@ namespace fileFinder
{ {
HintModel hints = new HintModel(); HintModel hints = new HintModel();
TaskController mainController; TaskController mainController;
SearchQueryModel searchQueryModel;
System.Timers.Timer updateInfoTimer = new System.Timers.Timer(1000); System.Timers.Timer updateInfoTimer = new System.Timers.Timer(1000);
public MainForm() public MainForm()
@ -26,6 +27,22 @@ namespace fileFinder
this.updateInfoTimer.Elapsed += refreshInfoByTimer; this.updateInfoTimer.Elapsed += refreshInfoByTimer;
this.updateInfoTimer.AutoReset = true; this.updateInfoTimer.AutoReset = true;
this.updateInfoTimer.Enabled = true; this.updateInfoTimer.Enabled = true;
fillImagesToResultViewer();
restoreLastSession();
}
private void restoreLastSession()
{
MainSettings sets = MainSettings.Default;
curDirTextBox.Text = sets.fileUrl;
innerQueryTextBox.Text = sets.fileInnerQuery;
queryTextBox.Text = sets.fileNameQuery;
searchQueryModel = mainController.updateSearchQueryModel(sets.fileUrl,
sets.fileInnerQuery, sets.fileNameQuery);
}
private void fillImagesToResultViewer()
{
try try
{ {
ImageList iconList = new ImageList(); ImageList iconList = new ImageList();
@ -36,7 +53,8 @@ namespace fileFinder
resultViewer.ImageList = iconList; resultViewer.ImageList = iconList;
resultViewer.ImageIndex = 3; resultViewer.ImageIndex = 3;
resultViewer.SelectedImageIndex = 3; resultViewer.SelectedImageIndex = 3;
} catch { } }
catch { }
} }
private void dirSelectBtn_Click(object sender, EventArgs e) private void dirSelectBtn_Click(object sender, EventArgs e)
@ -61,78 +79,6 @@ namespace fileFinder
//} //}
} }
private async Task<TreeNode> buildResultTree(TaskController controller, IProgress<ProgressReportModel> report)
{
TreeNode itemsNode = new TreeNode();
ProgressReportModel _report = new ProgressReportModel();
List<string> foundFiles = getFileList(curDirTextBox.Text, queryTextBox.Text);
int counter = 0;
foreach (string item in foundFiles)
{
while (controller.isPaused)
{
Thread.Sleep(100);
if (!controller.isFormUpdatedAfterPause)
{
controller.isFormUpdatedAfterPause = true;
_report.progress = counter;
_report.currentFileUrl = item;
_report.currentTreeNode = (TreeNode) itemsNode.Clone();
report.Report(_report);
}
}
string[] fileLines = getFileContents(item);
_report.progress = counter;
_report.currentFileUrl = item;
report.Report(_report);
if ((fileLines.Length > 0) && (isFileContainQuery(fileLines, innerQueryTextBox.Text)))
{
counter++;
await fillChildNode(itemsNode, item.Replace(curDirTextBox.Text, ""));
}
}
controller.stopTask();
return itemsNode;
}
private List<string> getFileList (string directory, string nameQuery)
{
List<String> fileList = new List<String>();
try
{
fileList = Directory.GetFiles(directory, nameQuery, SearchOption.AllDirectories).ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Не удалось получить доступ к файлу/папке");
}
return fileList;
}
private string[] getFileContents (string fileUrl)
{
try
{
return File.ReadAllLines(fileUrl, Encoding.UTF8);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка поиска внутри файла!");
}
return null;
}
private bool isFileContainQuery (string[] fileLines, string query)
{
foreach (string item in fileLines)
if (item.IndexOf(query) != -1)
return true;
return false;
}
private void reportProgress(object sender, ProgressReportModel report) private void reportProgress(object sender, ProgressReportModel report)
{ {
if (!mainController.isPaused) if (!mainController.isPaused)
@ -146,55 +92,41 @@ namespace fileFinder
Progress<ProgressReportModel> progress = new Progress<ProgressReportModel>(); Progress<ProgressReportModel> progress = new Progress<ProgressReportModel>();
progress.ProgressChanged += reportProgress; progress.ProgressChanged += reportProgress;
if (mainController.isStopped) if (mainController.isStopped || mainController.isTaskChanged)
{ {
searchQueryModel = mainController.updateSearchQueryModel(curDirTextBox.Text,
queryTextBox.Text, innerQueryTextBox.Text);
handleSearchBtn.Text = "Pause Task"; handleSearchBtn.Text = "Pause Task";
waitOrPauseLabel.Visible = true; waitOrPauseLabel.Visible = true;
resultViewer.Enabled = false; resultViewer.Enabled = false;
mainController.beginTask(); mainController.beginTask();
TreeNode tN = await Task.Run(() => buildResultTree(mainController, progress)); TreeNode tN = await Task.Run(() => mainController.buildResultTree(searchQueryModel, progress));
updateResultViewer(tN); updateResultViewer(tN);
changeVisibilityResultViewer();
handleSearchBtn.Text = "Start Task"; handleSearchBtn.Text = "Start Task";
} else if (mainController.isPaused) } else if (mainController.isPaused)
{ {
handleSearchBtn.Text = "Pause Task"; handleSearchBtn.Text = "Pause Task";
waitOrPauseLabel.Visible = true; changeVisibilityResultViewer();
resultViewer.Enabled = false;
mainController.resumeTask(); mainController.resumeTask();
} else } else
{ {
handleSearchBtn.Text = "Resume Task"; handleSearchBtn.Text = "Resume Task";
waitOrPauseLabel.Visible = false; changeVisibilityResultViewer();
resultViewer.Enabled = true;
mainController.pauseTask(); mainController.pauseTask();
} }
} }
public async Task fillChildNode (TreeNode node, String item) private void changeVisibilityResultViewer()
{ {
int backSlashIndex = item.IndexOf("\\"); if (mainController.isStopped || mainController.isPaused)
switch (backSlashIndex) {
waitOrPauseLabel.Visible = false;
resultViewer.Enabled = true;
} else
{ {
case -1: waitOrPauseLabel.Visible = true;
node.Nodes.Add(item, item, 2, 2); resultViewer.Enabled = false;
break;
case 0:
item = item.Remove(0, 1);
await fillChildNode(node, item);
break;
default:
String currentNodeName = item.Substring(0, backSlashIndex);
int nodeIndex = node.Nodes.IndexOfKey(currentNodeName);
if (nodeIndex != -1)
await fillChildNode(node.Nodes[nodeIndex], item.Remove(0, backSlashIndex + 1));
else
{
node.Nodes.Add(currentNodeName, currentNodeName, 0, 0);
nodeIndex = node.Nodes.IndexOfKey(currentNodeName);
await fillChildNode(node.Nodes[nodeIndex], item.Remove(0, backSlashIndex + 1));
}
break;
} }
} }
@ -230,10 +162,25 @@ namespace fileFinder
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{ {
MainSettings.Default.urlDirectory = curDirTextBox.Text; MainSettings.Default.fileUrl = curDirTextBox.Text;
MainSettings.Default.fileNameQuery = queryTextBox.Text; MainSettings.Default.fileNameQuery = queryTextBox.Text;
MainSettings.Default.fileInnerQuery = innerQueryTextBox.Text; MainSettings.Default.fileInnerQuery = innerQueryTextBox.Text;
MainSettings.Default.Save(); MainSettings.Default.Save();
} }
private void curDirTextBox_TextChanged(object sender, EventArgs e)
{
mainController.isTaskChanged = true;
}
private void queryTextBox_TextChanged(object sender, EventArgs e)
{
mainController.isTaskChanged = true;
}
private void innerQueryTextBox_TextChanged(object sender, EventArgs e)
{
mainController.isTaskChanged = true;
}
} }
} }

6
fileFinder/MainSettings.Designer.cs

@ -26,12 +26,12 @@ namespace fileFinder {
[global::System.Configuration.UserScopedSettingAttribute()] [global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("C:\\nextcloud\\")] [global::System.Configuration.DefaultSettingValueAttribute("C:\\nextcloud\\")]
public string urlDirectory { public string fileUrl {
get { get {
return ((string)(this["urlDirectory"])); return ((string)(this["fileUrl"]));
} }
set { set {
this["urlDirectory"] = value; this["fileUrl"] = value;
} }
} }

2
fileFinder/MainSettings.settings

@ -2,7 +2,7 @@
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="fileFinder" GeneratedClassName="MainSettings"> <SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="fileFinder" GeneratedClassName="MainSettings">
<Profiles /> <Profiles />
<Settings> <Settings>
<Setting Name="urlDirectory" Type="System.String" Scope="User"> <Setting Name="fileUrl" Type="System.String" Scope="User">
<Value Profile="(Default)">C:\nextcloud\</Value> <Value Profile="(Default)">C:\nextcloud\</Value>
</Setting> </Setting>
<Setting Name="fileNameQuery" Type="System.String" Scope="User"> <Setting Name="fileNameQuery" Type="System.String" Scope="User">

15
fileFinder/SearchQueryModel.cs

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace fileFinder
{
class SearchQueryModel
{
public string fileUrl { get; set; }
public string fileNameQuery { get; set; }
public string fileInnerQuery { get; set; }
}
}

137
fileFinder/TaskController.cs

@ -1,10 +1,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Timers; using System.Timers;
using System.Windows.Forms;
namespace fileFinder namespace fileFinder
{ {
@ -13,6 +16,7 @@ namespace fileFinder
public bool isPaused { get; private set; } public bool isPaused { get; private set; }
public bool isStopped { get; private set; } public bool isStopped { get; private set; }
public bool isFormUpdatedAfterPause { get; set; } public bool isFormUpdatedAfterPause { get; set; }
public bool isTaskChanged { get; set; }
private Stopwatch stopwatch = new Stopwatch(); private Stopwatch stopwatch = new Stopwatch();
public TaskController () public TaskController ()
@ -20,53 +24,158 @@ namespace fileFinder
isPaused = false; isPaused = false;
isStopped = true; isStopped = true;
isFormUpdatedAfterPause = true; isFormUpdatedAfterPause = true;
isTaskChanged = false;
} }
public bool beginTask () public void beginTask ()
{ {
isPaused = false; isPaused = false;
isStopped = false; isStopped = false;
stopwatch.Restart(); stopwatch.Restart();
return true;
} }
public bool pauseTask () public void pauseTask ()
{ {
if (!isPaused && !isStopped) if (!isPaused && !isStopped)
{ {
isPaused = true; isPaused = true;
isFormUpdatedAfterPause = false; isFormUpdatedAfterPause = false;
stopwatch.Stop(); stopwatch.Stop();
return true; }
} else
return false;
} }
public bool resumeTask () public void resumeTask ()
{ {
if (isPaused && !isStopped) if (isPaused && !isStopped)
{ {
isPaused = false; isPaused = false;
stopwatch.Start(); stopwatch.Start();
return true; }
} else
return false;
} }
public bool stopTask () public void stopTask ()
{ {
if (!isStopped) if (!isStopped)
{ {
isStopped = true; isStopped = true;
stopwatch.Stop(); stopwatch.Stop();
return true; }
} else
return false;
} }
public TimeSpan elapsedTime () public TimeSpan elapsedTime ()
{ {
return stopwatch.Elapsed; return stopwatch.Elapsed;
} }
public async Task<TreeNode> buildResultTree(SearchQueryModel query, IProgress <ProgressReportModel> report)
{
TaskController controller = this;
TreeNode itemsNode = new TreeNode();
ProgressReportModel _report = new ProgressReportModel();
List<string> foundFiles = getFileList(query.fileUrl, query.fileNameQuery);
int counter = 0;
foreach (string item in foundFiles)
{
while (controller.isPaused)
{
Thread.Sleep(100);
if (!controller.isFormUpdatedAfterPause)
{
controller.isFormUpdatedAfterPause = true;
_report.progress = counter;
_report.currentFileUrl = item;
_report.currentTreeNode = (TreeNode)itemsNode.Clone();
report.Report(_report);
}
}
string[] fileLines = getFileContents(item);
_report.progress = counter;
_report.currentFileUrl = item;
report.Report(_report);
if ((fileLines.Length > 0) && (isFileContainQuery(fileLines, query.fileInnerQuery)))
{
counter++;
await fillChildNode(itemsNode, item.Replace(query.fileUrl, ""));
}
}
controller.stopTask();
return itemsNode;
}
private List<string> getFileList(string directory, string nameQuery)
{
List<String> fileList = new List<String>();
try
{
fileList = Directory.GetFiles(directory, nameQuery, SearchOption.AllDirectories).ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Не удалось получить доступ к файлу/папке");
}
return fileList;
}
private string[] getFileContents(string fileUrl)
{
try
{
return File.ReadAllLines(fileUrl, Encoding.UTF8);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка поиска внутри файла!");
}
return null;
}
private bool isFileContainQuery(string[] fileLines, string query)
{
foreach (string item in fileLines)
if (item.IndexOf(query) != -1)
return true;
return false;
}
public async Task fillChildNode(TreeNode node, String item)
{
int backSlashIndex = item.IndexOf("\\");
switch (backSlashIndex)
{
case -1:
node.Nodes.Add(item, item, 2, 2);
break;
case 0:
item = item.Remove(0, 1);
await fillChildNode(node, item);
break;
default:
String currentNodeName = item.Substring(0, backSlashIndex);
int nodeIndex = node.Nodes.IndexOfKey(currentNodeName);
if (nodeIndex != -1)
await fillChildNode(node.Nodes[nodeIndex], item.Remove(0, backSlashIndex + 1));
else
{
node.Nodes.Add(currentNodeName, currentNodeName, 0, 0);
nodeIndex = node.Nodes.IndexOfKey(currentNodeName);
await fillChildNode(node.Nodes[nodeIndex], item.Remove(0, backSlashIndex + 1));
}
break;
}
}
public SearchQueryModel updateSearchQueryModel(string fileUrl, string fileNameQuery, string fileInnerQuery)
{
SearchQueryModel sqModel = new SearchQueryModel();
sqModel.fileUrl = fileUrl;
sqModel.fileNameQuery = fileNameQuery;
sqModel.fileInnerQuery = fileInnerQuery;
return sqModel;
}
} }
} }

1
fileFinder/fileFinder.csproj

@ -61,6 +61,7 @@
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="ProgressReportModel.cs" /> <Compile Include="ProgressReportModel.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SearchQueryModel.cs" />
<Compile Include="TaskController.cs" /> <Compile Include="TaskController.cs" />
<EmbeddedResource Include="MainForm.resx"> <EmbeddedResource Include="MainForm.resx">
<DependentUpon>MainForm.cs</DependentUpon> <DependentUpon>MainForm.cs</DependentUpon>

Loading…
Cancel
Save