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. 155
      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>
<userSettings>
<fileFinder.MainSettings>
<setting name="urlDirectory" serializeAs="String">
<setting name="fileUrl" serializeAs="String">
<value>C:\nextcloud\</value>
</setting>
<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.TabIndex = 1;
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);
//
// splitContainer
@ -105,7 +106,7 @@
this.handleSearchBtn.Name = "handleSearchBtn";
this.handleSearchBtn.Size = new System.Drawing.Size(120, 21);
this.handleSearchBtn.TabIndex = 5;
this.handleSearchBtn.Text = "Start/Pause";
this.handleSearchBtn.Text = "Start Task";
this.handleSearchBtn.UseVisualStyleBackColor = true;
this.handleSearchBtn.Click += new System.EventHandler(this.handleSearchBtn_Click);
//
@ -116,6 +117,7 @@
this.innerQueryTextBox.Size = new System.Drawing.Size(650, 20);
this.innerQueryTextBox.TabIndex = 4;
this.innerQueryTextBox.Tag = "";
this.innerQueryTextBox.TextChanged += new System.EventHandler(this.innerQueryTextBox_TextChanged);
//
// queryTextBox
//
@ -125,6 +127,7 @@
this.queryTextBox.TabIndex = 3;
this.queryTextBox.Tag = "";
this.queryTextBox.Text = "*.txt";
this.queryTextBox.TextChanged += new System.EventHandler(this.queryTextBox_TextChanged);
//
// waitOrPauseLabel
//

155
fileFinder/MainForm.cs

@ -17,6 +17,7 @@ namespace fileFinder
{
HintModel hints = new HintModel();
TaskController mainController;
SearchQueryModel searchQueryModel;
System.Timers.Timer updateInfoTimer = new System.Timers.Timer(1000);
public MainForm()
@ -26,6 +27,22 @@ namespace fileFinder
this.updateInfoTimer.Elapsed += refreshInfoByTimer;
this.updateInfoTimer.AutoReset = 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
{
ImageList iconList = new ImageList();
@ -36,7 +53,8 @@ namespace fileFinder
resultViewer.ImageList = iconList;
resultViewer.ImageIndex = 3;
resultViewer.SelectedImageIndex = 3;
} catch { }
}
catch { }
}
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)
{
if (!mainController.isPaused)
@ -146,58 +92,44 @@ namespace fileFinder
Progress<ProgressReportModel> progress = new Progress<ProgressReportModel>();
progress.ProgressChanged += reportProgress;
if (mainController.isStopped)
if (mainController.isStopped || mainController.isTaskChanged)
{
searchQueryModel = mainController.updateSearchQueryModel(curDirTextBox.Text,
queryTextBox.Text, innerQueryTextBox.Text);
handleSearchBtn.Text = "Pause Task";
waitOrPauseLabel.Visible = true;
resultViewer.Enabled = false;
mainController.beginTask();
TreeNode tN = await Task.Run(() => buildResultTree(mainController, progress));
TreeNode tN = await Task.Run(() => mainController.buildResultTree(searchQueryModel, progress));
updateResultViewer(tN);
changeVisibilityResultViewer();
handleSearchBtn.Text = "Start Task";
} else if (mainController.isPaused)
{
handleSearchBtn.Text = "Pause Task";
waitOrPauseLabel.Visible = true;
resultViewer.Enabled = false;
changeVisibilityResultViewer();
mainController.resumeTask();
} else
{
handleSearchBtn.Text = "Resume Task";
waitOrPauseLabel.Visible = false;
resultViewer.Enabled = true;
changeVisibilityResultViewer();
mainController.pauseTask();
}
}
public async Task fillChildNode (TreeNode node, String item)
private void changeVisibilityResultViewer()
{
int backSlashIndex = item.IndexOf("\\");
switch (backSlashIndex)
if (mainController.isStopped || mainController.isPaused)
{
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;
waitOrPauseLabel.Visible = false;
resultViewer.Enabled = true;
} else
{
waitOrPauseLabel.Visible = true;
resultViewer.Enabled = false;
}
}
public void updateInfoLabel (string fileUrl, int counter)
{
TimeSpan tS = mainController.elapsedTime();
@ -230,10 +162,25 @@ namespace fileFinder
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.fileInnerQuery = innerQueryTextBox.Text;
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.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("C:\\nextcloud\\")]
public string urlDirectory {
public string fileUrl {
get {
return ((string)(this["urlDirectory"]));
return ((string)(this["fileUrl"]));
}
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">
<Profiles />
<Settings>
<Setting Name="urlDirectory" Type="System.String" Scope="User">
<Setting Name="fileUrl" Type="System.String" Scope="User">
<Value Profile="(Default)">C:\nextcloud\</Value>
</Setting>
<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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
namespace fileFinder
{
@ -13,6 +16,7 @@ namespace fileFinder
public bool isPaused { get; private set; }
public bool isStopped { get; private set; }
public bool isFormUpdatedAfterPause { get; set; }
public bool isTaskChanged { get; set; }
private Stopwatch stopwatch = new Stopwatch();
public TaskController ()
@ -20,53 +24,158 @@ namespace fileFinder
isPaused = false;
isStopped = true;
isFormUpdatedAfterPause = true;
isTaskChanged = false;
}
public bool beginTask ()
public void beginTask ()
{
isPaused = false;
isStopped = false;
stopwatch.Restart();
return true;
}
public bool pauseTask ()
public void pauseTask ()
{
if (!isPaused && !isStopped)
{
isPaused = true;
isFormUpdatedAfterPause = false;
stopwatch.Stop();
return true;
} else
return false;
}
}
public bool resumeTask ()
public void resumeTask ()
{
if (isPaused && !isStopped)
{
isPaused = false;
stopwatch.Start();
return true;
} else
return false;
}
}
public bool stopTask ()
public void stopTask ()
{
if (!isStopped)
{
isStopped = true;
stopwatch.Stop();
return true;
} else
return false;
}
}
public TimeSpan elapsedTime ()
{
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="ProgressReportModel.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SearchQueryModel.cs" />
<Compile Include="TaskController.cs" />
<EmbeddedResource Include="MainForm.resx">
<DependentUpon>MainForm.cs</DependentUpon>

Loading…
Cancel
Save