Simplified directory and file discovery

Corrected namespace naming of Helpers
This commit is contained in:
Peter Kirmeier 2023-04-16 14:17:33 +02:00
parent 3c7a7a2aaf
commit 0158499a2c
19 changed files with 396 additions and 465 deletions

View file

@ -8,7 +8,7 @@ namespace SystemTrayMenu
using System.Windows;
using System.Windows.Threading;
using SystemTrayMenu.Business;
using SystemTrayMenu.Helper.Updater;
using SystemTrayMenu.Helpers.Updater;
using SystemTrayMenu.Properties;
using SystemTrayMenu.UserInterface;
using SystemTrayMenu.Utilities;

View file

@ -5,16 +5,12 @@
namespace SystemTrayMenu.Handler
{
using System;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows.Controls;
using System.Windows.Input;
using SystemTrayMenu.DataClasses;
using SystemTrayMenu.Helper;
using SystemTrayMenu.Helpers;
using SystemTrayMenu.Utilities;
using static System.Net.Mime.MediaTypeNames;
using ListView = System.Windows.Controls.ListView;
using Menu = SystemTrayMenu.UserInterface.Menu;

View file

@ -18,7 +18,6 @@ namespace SystemTrayMenu.Business
using SystemTrayMenu.DataClasses;
using SystemTrayMenu.DllImports;
using SystemTrayMenu.Handler;
using SystemTrayMenu.Helper;
using SystemTrayMenu.Helpers;
using SystemTrayMenu.Properties;
using SystemTrayMenu.Utilities;
@ -268,7 +267,7 @@ namespace SystemTrayMenu.Business
};
CreateWatcher(Config.Path, false);
foreach (var pathAndFlags in MenusHelpers.GetAddionalPathsForMainMenu())
foreach (var pathAndFlags in DirectoryHelpers.GetAddionalPathsForMainMenu())
{
CreateWatcher(pathAndFlags.Path, pathAndFlags.Recursive);
}
@ -347,37 +346,6 @@ namespace SystemTrayMenu.Business
}
}
internal static MenuData GetData(BackgroundWorker? worker, string path, int level)
{
MenuData menuData = new(level, null);
if (worker?.CancellationPending == true || string.IsNullOrEmpty(path))
{
return menuData;
}
MenusHelpers.GetItemsForMainMenu(worker, path, ref menuData);
if (worker?.CancellationPending == true)
{
return menuData;
}
MenusHelpers.GetAddionalItemsForMainMenu(ref menuData);
if (worker?.CancellationPending == true)
{
return menuData;
}
MenusHelpers.ReadHiddenAndReadIcons(worker, ref menuData);
if (worker?.CancellationPending == true)
{
return menuData;
}
MenusHelpers.CheckIfValid(ref menuData);
MenusHelpers.SortItemsWhenValid(ref menuData);
return menuData;
}
internal static void OpenFolder(string? path = null)
{
if (string.IsNullOrEmpty(path))
@ -498,8 +466,8 @@ namespace SystemTrayMenu.Business
path = Config.Path;
}
MenuData menuData = GetData((BackgroundWorker?)senderDoWork, path, level);
menuData.RowDataParent = rowData;
MenuData menuData = new(level, rowData);
DirectoryHelpers.DiscoverItems((BackgroundWorker?)senderDoWork, path, ref menuData);
eDoWork.Result = menuData;
}
@ -1293,7 +1261,7 @@ namespace SystemTrayMenu.Business
}
}
rowDatas = MenusHelpers.SortItems(rowDatas);
rowDatas = DirectoryHelpers.SortItems(rowDatas);
keyboardInput.ClearIsSelectedByKey();
AddItemsToMenu(rowDatas, menus[0], out _, out _);
@ -1376,7 +1344,7 @@ namespace SystemTrayMenu.Business
}
}
rowDatas = MenusHelpers.SortItems(rowDatas);
rowDatas = DirectoryHelpers.SortItems(rowDatas);
keyboardInput.ClearIsSelectedByKey();
AddItemsToMenu(rowDatas, menus[0], out _, out _);

View file

@ -2,7 +2,7 @@
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helper
namespace SystemTrayMenu.Helpers
{
using System;
using System.Windows.Threading;

View file

@ -1,276 +1,243 @@
// <copyright file="MenusHelpers.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Business
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using SystemTrayMenu.DataClasses;
using SystemTrayMenu.Helper;
using SystemTrayMenu.Utilities;
internal static class MenusHelpers
{
internal static void GetItemsForMainMenu(BackgroundWorker? worker, string path, ref MenuData menuData)
{
menuData.IsNetworkRoot = FileLnk.IsNetworkRoot(path);
if (menuData.IsNetworkRoot)
{
GetNetworkRootDirectories(path, ref menuData);
}
else
// <copyright file="DirectoryHelpers.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helpers
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using SystemTrayMenu.DataClasses;
using SystemTrayMenu.Utilities;
internal static class DirectoryHelpers
{
internal static void DiscoverItems(BackgroundWorker? worker, string path, ref MenuData menuData)
{
try
{
if (!Directory.Exists(path))
menuData.IsNetworkRoot = FileLnk.IsNetworkRoot(path);
if (menuData.IsNetworkRoot)
{
// Happens most likely when a shortcut is pointing to an absent target path
Log.Info($"path:'{path}' does not exist");
DiscoverNetworkRootDirectories(path, ref menuData);
}
else
{
DiscoverLocalDirectories(worker, path, ref menuData);
}
}
catch (Exception ex)
{
Log.Warn($"path:'{path}'", ex);
if (ex is UnauthorizedAccessException)
{
menuData.DirectoryState = MenuDataDirectoryState.NoAccess;
return;
}
GetDirectories(worker, path, ref menuData);
GetFiles(worker, path, ref menuData);
}
}
internal static void GetAddionalItemsForMainMenu(ref MenuData menuData)
{
if (menuData.Level != 0)
{
return;
}
foreach (var path in GetAddionalPathsForMainMenu())
{
GetDirectoriesAndFilesRecursive(ref menuData, path.Path, path.OnlyFiles, path.Recursive);
}
}
internal static IEnumerable<(string Path, bool Recursive, bool OnlyFiles)> GetAddionalPathsForMainMenu()
{
foreach (string pathAndRecursivString in Properties.Settings.Default.PathsAddToMainMenu.Split(@"|"))
{
if (string.IsNullOrEmpty(pathAndRecursivString))
{
continue;
}
string pathAddForMainMenu = pathAndRecursivString.Split("recursiv:")[0].Trim();
bool recursive = pathAndRecursivString.Split("recursiv:")[1].StartsWith("True");
bool onlyFiles = pathAndRecursivString.Split("onlyFiles:")[1].StartsWith("True");
yield return (Path: pathAddForMainMenu, Recursive: recursive, OnlyFiles: onlyFiles);
}
}
internal static void ReadHiddenAndReadIcons(BackgroundWorker? worker, ref MenuData menuData)
{
List<RowData> rowDatasToRemove = new();
foreach (RowData rowData in menuData.RowDatas)
{
if (worker?.CancellationPending == true)
{
return;
}
if (!menuData.IsNetworkRoot && FolderOptions.IsHidden(rowData))
{
rowDatasToRemove.Add(rowData);
continue;
}
rowData.ReadIcon(true);
}
menuData.RowDatas = menuData.RowDatas.Except(rowDatasToRemove).ToList();
}
internal static void CheckIfValid(ref MenuData menuData)
{
if (menuData.DirectoryState == MenuDataDirectoryState.Undefined)
{
if (menuData.RowDatas.Count == 0)
{
menuData.DirectoryState = MenuDataDirectoryState.Empty;
}
else
{
menuData.DirectoryState = MenuDataDirectoryState.Valid;
}
}
}
internal static void SortItemsWhenValid(ref MenuData menuData)
{
if (menuData.DirectoryState != MenuDataDirectoryState.Valid)
{
return;
}
menuData.RowDatas = SortItems(menuData.RowDatas);
}
internal static List<RowData> SortItems(List<RowData> rowDatas)
{
if (Properties.Settings.Default.SortByTypeAndNameWindowsExplorerSort)
{
rowDatas = rowDatas.OrderByDescending(x => x.IsFolder)
.ThenBy(x => x.Text, new WindowsExplorerSort()).ToList();
}
else if (Properties.Settings.Default.SortByTypeAndDate)
{
rowDatas = rowDatas.OrderByDescending(x => x.IsFolder)
.ThenByDescending(x => x.FileInfo?.LastWriteTime).ToList();
}
else if (Properties.Settings.Default.SortByFileExtensionAndName)
{
rowDatas = rowDatas.OrderBy(x => x.FileExtension).ThenBy(x => x.Text).ToList();
}
else if (Properties.Settings.Default.SortByName)
{
rowDatas = rowDatas.OrderBy(x => x.Text).ToList();
}
else if (Properties.Settings.Default.SortByDate)
{
rowDatas = rowDatas.OrderByDescending(x => x.FileInfo?.LastWriteTime).ToList();
}
return rowDatas;
}
private static void GetNetworkRootDirectories(string path, ref MenuData menuData)
{
Process cmd = new();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
try
{
bool resolvedSomething = false;
cmd.Start();
cmd.StandardInput.WriteLine($"net view {path}");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
string output = cmd.StandardOutput.ReadToEnd();
cmd.WaitForExit();
cmd.Close();
List<string> lines = output
.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
if (lines.Count > 8)
{
foreach (string line in lines.Skip(6).SkipLast(2))
{
int indexOfFirstSpace = line.IndexOf(" ", StringComparison.InvariantCulture);
if (indexOfFirstSpace > 0)
{
string directory = Path.Combine(path, line[..indexOfFirstSpace]);
menuData.RowDatas.Add(new RowData(true, false, true, menuData.Level, directory));
resolvedSomething = true;
}
}
}
if (!resolvedSomething)
{
Log.Info($"Could not resolve network root folder: {path} , output:{output}");
}
}
catch (Exception ex)
{
Log.Warn($"path:'{path}'", ex);
if (ex is UnauthorizedAccessException)
{
menuData.DirectoryState = MenuDataDirectoryState.NoAccess;
}
}
}
private static void GetDirectories(BackgroundWorker? worker, string path, ref MenuData menuData)
{
try
{
foreach (var directory in Directory.GetDirectories(path))
{
if (worker?.CancellationPending == true)
{
return;
}
menuData.RowDatas.Add(new RowData(true, false, false, menuData.Level, directory));
}
}
catch (Exception ex)
{
Log.Warn($"path:'{path}'", ex);
if (ex is UnauthorizedAccessException)
{
menuData.DirectoryState = MenuDataDirectoryState.NoAccess;
}
}
}
private static void GetFiles(BackgroundWorker? worker, string path, ref MenuData menuData)
{
try
{
foreach (string file in DirectoryBySearchPattern.GetFiles(path, Config.SearchPattern))
{
if (worker?.CancellationPending == true)
{
return;
}
menuData.RowDatas.Add(new RowData(false, false, false, menuData.Level, file));
}
}
catch (Exception ex)
{
Log.Warn($"path:'{path}'", ex);
if (ex is UnauthorizedAccessException)
{
menuData.DirectoryState = MenuDataDirectoryState.NoAccess;
}
}
}
private static void GetDirectoriesAndFilesRecursive(
ref MenuData menuData,
string path,
bool onlyFiles,
bool recursiv)
{
try
{
foreach (string file in DirectoryBySearchPattern.GetFiles(path, Config.SearchPattern))
{
menuData.RowDatas.Add(new RowData(false, true, false, menuData.Level, file));
}
foreach (string directory in Directory.GetDirectories(path))
{
if (!onlyFiles)
{
menuData.RowDatas.Add(new RowData(true, true, false, menuData.Level, directory));
}
if (recursiv)
{
GetDirectoriesAndFilesRecursive(ref menuData, directory, onlyFiles, recursiv);
}
}
}
catch (Exception ex)
{
Log.Warn($"GetDirectoriesAndFilesRecursive path:'{path}'", ex);
}
}
}
}
}
if (worker?.CancellationPending == true)
{
return;
}
if (menuData.Level == 0)
{
foreach (var additionalPath in GetAddionalPathsForMainMenu())
{
GetDirectoriesAndFilesRecursive(ref menuData, additionalPath.Path, additionalPath.OnlyFiles, additionalPath.Recursive);
}
}
RemoveHiddenOrReadIcons(worker, ref menuData);
if (menuData.RowDatas.Count == 0)
{
menuData.DirectoryState = MenuDataDirectoryState.Empty;
}
else
{
if (worker?.CancellationPending == true)
{
return;
}
menuData.RowDatas = SortItems(menuData.RowDatas);
menuData.DirectoryState = MenuDataDirectoryState.Valid;
}
}
internal static IEnumerable<(string Path, bool Recursive, bool OnlyFiles)> GetAddionalPathsForMainMenu()
{
foreach (string pathAndRecursivString in Properties.Settings.Default.PathsAddToMainMenu.Split(@"|"))
{
if (string.IsNullOrEmpty(pathAndRecursivString))
{
continue;
}
string pathAddForMainMenu = pathAndRecursivString.Split("recursiv:")[0].Trim();
bool recursive = pathAndRecursivString.Split("recursiv:")[1].StartsWith("True");
bool onlyFiles = pathAndRecursivString.Split("onlyFiles:")[1].StartsWith("True");
yield return (Path: pathAddForMainMenu, Recursive: recursive, OnlyFiles: onlyFiles);
}
}
internal static List<RowData> SortItems(List<RowData> rowDatas)
{
if (Properties.Settings.Default.SortByTypeAndNameWindowsExplorerSort)
{
rowDatas = rowDatas.OrderByDescending(x => x.IsFolder)
.ThenBy(x => x.Text, new WindowsExplorerSort()).ToList();
}
else if (Properties.Settings.Default.SortByTypeAndDate)
{
rowDatas = rowDatas.OrderByDescending(x => x.IsFolder)
.ThenByDescending(x => x.FileInfo?.LastWriteTime).ToList();
}
else if (Properties.Settings.Default.SortByFileExtensionAndName)
{
rowDatas = rowDatas.OrderBy(x => x.FileExtension).ThenBy(x => x.Text).ToList();
}
else if (Properties.Settings.Default.SortByName)
{
rowDatas = rowDatas.OrderBy(x => x.Text).ToList();
}
else if (Properties.Settings.Default.SortByDate)
{
rowDatas = rowDatas.OrderByDescending(x => x.FileInfo?.LastWriteTime).ToList();
}
return rowDatas;
}
private static void RemoveHiddenOrReadIcons(BackgroundWorker? worker, ref MenuData menuData)
{
List<RowData> rowDatasToRemove = new();
foreach (RowData rowData in menuData.RowDatas)
{
if (worker?.CancellationPending == true)
{
return;
}
if (!menuData.IsNetworkRoot && FolderOptions.IsHidden(rowData))
{
rowDatasToRemove.Add(rowData);
continue;
}
rowData.ReadIcon(true);
}
menuData.RowDatas = menuData.RowDatas.Except(rowDatasToRemove).ToList();
}
private static void DiscoverNetworkRootDirectories(string path, ref MenuData menuData)
{
Process cmd = new();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.Start();
cmd.StandardInput.WriteLine($"net view {path}");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
string output = cmd.StandardOutput.ReadToEnd();
cmd.WaitForExit();
cmd.Close();
bool resolvedSomething = false;
List<string> lines = output
.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
if (lines.Count > 8)
{
foreach (string line in lines.Skip(6).SkipLast(2))
{
int indexOfFirstSpace = line.IndexOf(" ", StringComparison.InvariantCulture);
if (indexOfFirstSpace > 0)
{
string directory = Path.Combine(path, line[..indexOfFirstSpace]);
menuData.RowDatas.Add(new RowData(true, false, true, menuData.Level, directory));
resolvedSomething = true;
}
}
}
if (!resolvedSomething)
{
Log.Info($"Could not resolve network root folder: {path} , output:{output}");
}
}
private static void DiscoverLocalDirectories(BackgroundWorker? worker, string path, ref MenuData menuData)
{
if (!Directory.Exists(path))
{
// Happens most likely when a shortcut is pointing to an absent target path
Log.Info($"path:'{path}' does not exist");
return;
}
foreach (var directory in Directory.GetDirectories(path))
{
if (worker?.CancellationPending == true)
{
return;
}
menuData.RowDatas.Add(new RowData(true, false, false, menuData.Level, directory));
}
foreach (string file in DirectoryBySearchPattern.GetFiles(path, Config.SearchPattern))
{
if (worker?.CancellationPending == true)
{
return;
}
menuData.RowDatas.Add(new RowData(false, false, false, menuData.Level, file));
}
}
private static void GetDirectoriesAndFilesRecursive(
ref MenuData menuData,
string path,
bool onlyFiles,
bool recursiv)
{
try
{
foreach (string file in DirectoryBySearchPattern.GetFiles(path, Config.SearchPattern))
{
menuData.RowDatas.Add(new RowData(false, true, false, menuData.Level, file));
}
foreach (string directory in Directory.GetDirectories(path))
{
if (!onlyFiles)
{
menuData.RowDatas.Add(new RowData(true, true, false, menuData.Level, directory));
}
if (recursiv)
{
GetDirectoriesAndFilesRecursive(ref menuData, directory, onlyFiles, recursiv);
}
}
}
catch (Exception ex)
{
Log.Warn($"GetDirectoriesAndFilesRecursive path:'{path}'", ex);
}
}
}
}

View file

@ -2,7 +2,7 @@
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helper
namespace SystemTrayMenu.Helpers
{
using System;
using System.IO;

View file

@ -2,7 +2,7 @@
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helper
namespace SystemTrayMenu.Helpers
{
using System.Drawing;
using System.Drawing.Imaging;

View file

@ -2,7 +2,7 @@
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helper
namespace SystemTrayMenu.Helpers
{
using System;
using System.Windows.Input;

View file

@ -2,7 +2,7 @@
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helper
namespace SystemTrayMenu.Helpers
{
using System;
using System.Windows.Input;

View file

@ -1,21 +1,21 @@
// <copyright file="GitHubUpdate.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helper.Updater
{
using System;
using System.Collections.Generic;
using System.Net.Http;
// <copyright file="GitHubUpdate.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helpers.Updater
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Reflection;
using System.Windows;
using SystemTrayMenu.UserInterface;
using SystemTrayMenu.Utilities;
public class GitHubUpdate
{
private static List<Dictionary<string, object>> releases;
private static UpdateWindow newVersionForm;
using SystemTrayMenu.Utilities;
public class GitHubUpdate
{
private static List<Dictionary<string, object>> releases;
private static UpdateWindow newVersionForm;
/// <summary>
/// Gets the latest release version name .
@ -42,133 +42,133 @@ namespace SystemTrayMenu.Helper.Updater
return result;
}
}
}
/// <summary>
/// Opens the website on GitHub of the latest release version .
/// </summary>
public static void WebOpenLatestRelease() => Log.ProcessStart("https://github.com/Hofknecht/SystemTrayMenu/releases");
public static void ActivateNewVersionFormOrCheckForUpdates(bool showWhenUpToDate)
{
if (newVersionForm != null)
public static void ActivateNewVersionFormOrCheckForUpdates(bool showWhenUpToDate)
{
if (newVersionForm != null)
{
newVersionForm!.HandleInvoke(() => newVersionForm?.Activate());
}
else
{
CheckForUpdates(showWhenUpToDate);
}
}
private static void CheckForUpdates(bool showWhenUpToDate)
{
string urlGithubReleases = @"http://api.github.com/repos/Hofknecht/SystemTrayMenu/releases";
HttpClient client = new();
// https://developer.github.com/v3/#user-agent-required
client.DefaultRequestHeaders.Add("User-Agent", "SystemTrayMenu/" + Assembly.GetExecutingAssembly().GetName().Version.ToString());
// https://developer.github.com/v3/media/#request-specific-version
client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3.text+json");
try
{
using HttpResponseMessage response = client.GetAsync(urlGithubReleases).Result;
using HttpContent content = response.Content;
string responseString = content.ReadAsStringAsync().Result;
releases = responseString.FromJson<List<Dictionary<string, object>>>();
}
catch (Exception ex)
{
Log.Warn($"{nameof(CheckForUpdates)} failed", ex);
}
if (releases == null)
{
Log.Info($"{nameof(CheckForUpdates)} failed.");
}
else
{
RemoveCurrentAndOlderVersions();
ShowNewVersionOrUpToDateDialog(showWhenUpToDate);
}
}
private static void RemoveCurrentAndOlderVersions()
{
int releasesCount = releases.Count;
Version versionCurrent = Assembly.GetExecutingAssembly().GetName().Version;
for (int i = 0; i < releasesCount; i++)
{
string tagName = releases[i]["tag_name"].ToString();
Version versionGitHub = new(tagName.Replace("v", string.Empty));
if (versionGitHub.CompareTo(versionCurrent) < 1)
{
releases.RemoveRange(i, releasesCount - i);
break;
}
}
}
private static void ShowNewVersionOrUpToDateDialog(bool showWhenUpToDate)
{
if (releases.Count > 0)
newVersionForm!.HandleInvoke(() => newVersionForm?.Activate());
}
else
{
CheckForUpdates(showWhenUpToDate);
}
}
private static void CheckForUpdates(bool showWhenUpToDate)
{
string urlGithubReleases = @"http://api.github.com/repos/Hofknecht/SystemTrayMenu/releases";
HttpClient client = new();
// https://developer.github.com/v3/#user-agent-required
client.DefaultRequestHeaders.Add("User-Agent", "SystemTrayMenu/" + Assembly.GetExecutingAssembly().GetName().Version.ToString());
// https://developer.github.com/v3/media/#request-specific-version
client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3.text+json");
try
{
using HttpResponseMessage response = client.GetAsync(urlGithubReleases).Result;
using HttpContent content = response.Content;
string responseString = content.ReadAsStringAsync().Result;
releases = responseString.FromJson<List<Dictionary<string, object>>>();
}
catch (Exception ex)
{
Log.Warn($"{nameof(CheckForUpdates)} failed", ex);
}
if (releases == null)
{
Log.Info($"{nameof(CheckForUpdates)} failed.");
}
else
{
RemoveCurrentAndOlderVersions();
ShowNewVersionOrUpToDateDialog(showWhenUpToDate);
}
}
private static void RemoveCurrentAndOlderVersions()
{
int releasesCount = releases.Count;
Version versionCurrent = Assembly.GetExecutingAssembly().GetName().Version;
for (int i = 0; i < releasesCount; i++)
{
string tagName = releases[i]["tag_name"].ToString();
Version versionGitHub = new(tagName.Replace("v", string.Empty));
if (versionGitHub.CompareTo(versionCurrent) < 1)
{
releases.RemoveRange(i, releasesCount - i);
break;
}
}
}
private static void ShowNewVersionOrUpToDateDialog(bool showWhenUpToDate)
{
if (releases.Count > 0)
{
newVersionForm = new();
newVersionForm.textBox.Text = GetChangelog();
newVersionForm.Closed += (_, _) => newVersionForm = null;
newVersionForm.ShowDialog();
}
else if (showWhenUpToDate)
{
MessageBox.Show(Translator.GetText("You have the latest version of SystemTrayMenu!"));
}
}
/// <summary>
/// Returns the change log from current version up to the latest release version.
/// </summary>
/// <returns>Change log summary or error text.</returns>
private static string GetChangelog()
{
string result = string.Empty;
string errorstr = "An error occurred during update check!" + Environment.NewLine;
if (releases == null)
{
return errorstr + "Could not receive changelog!";
}
try
{
for (int i = 0; i < releases.Count; i++)
{
Dictionary<string, object> release = releases[i];
result += release["name"].ToString()
+ Environment.NewLine
+ release["body_text"].ToString()
.Replace("\n\n", Environment.NewLine)
.Replace("\n \n", Environment.NewLine)
+ Environment.NewLine + Environment.NewLine;
if (i < releases.Count)
{
result += "--------------------------------------------------" +
"-------------------------------------------------------"
+ Environment.NewLine;
}
}
result = result.Replace("\n", Environment.NewLine);
}
catch (Exception ex)
{
Log.Warn($"{nameof(GetChangelog)}", ex);
result = errorstr + ex.Message.ToString();
}
return result;
}
}
newVersionForm.ShowDialog();
}
else if (showWhenUpToDate)
{
MessageBox.Show(Translator.GetText("You have the latest version of SystemTrayMenu!"));
}
}
/// <summary>
/// Returns the change log from current version up to the latest release version.
/// </summary>
/// <returns>Change log summary or error text.</returns>
private static string GetChangelog()
{
string result = string.Empty;
string errorstr = "An error occurred during update check!" + Environment.NewLine;
if (releases == null)
{
return errorstr + "Could not receive changelog!";
}
try
{
for (int i = 0; i < releases.Count; i++)
{
Dictionary<string, object> release = releases[i];
result += release["name"].ToString()
+ Environment.NewLine
+ release["body_text"].ToString()
.Replace("\n\n", Environment.NewLine)
.Replace("\n \n", Environment.NewLine)
+ Environment.NewLine + Environment.NewLine;
if (i < releases.Count)
{
result += "--------------------------------------------------" +
"-------------------------------------------------------"
+ Environment.NewLine;
}
}
result = result.Replace("\n", Environment.NewLine);
}
catch (Exception ex)
{
Log.Warn($"{nameof(GetChangelog)}", ex);
result = errorstr + ex.Message.ToString();
}
return result;
}
}
}

View file

@ -2,7 +2,7 @@
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helper.Updater
namespace SystemTrayMenu.Helpers.Updater
{
// Copyright (c) 2018 Alex Parker
// Copyright (c) 2018-2019 Peter Kirmeier

View file

@ -2,7 +2,7 @@
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helper
namespace SystemTrayMenu.Helpers
{
using System.Collections.Generic;
using SystemTrayMenu.DllImports;

View file

@ -2,7 +2,7 @@
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helper
namespace SystemTrayMenu.Helpers
{
using System;
using System.Drawing;

View file

@ -2,14 +2,14 @@
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helper
namespace SystemTrayMenu.Helpers
{
using System;
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using SystemTrayMenu.Helper.Updater;
using SystemTrayMenu.Helpers.Updater;
using SystemTrayMenu.UserInterface;
using SystemTrayMenu.Utilities;
using SystemColors = System.Windows.SystemColors;

View file

@ -7,7 +7,7 @@ namespace SystemTrayMenu.UserInterface
using System;
using System.Windows;
using Hardcodet.Wpf.TaskbarNotification;
using SystemTrayMenu.Helper;
using SystemTrayMenu.Helpers;
using SystemTrayMenu.Utilities;
internal class AppNotifyIcon : IDisposable

View file

@ -10,7 +10,7 @@ namespace SystemTrayMenu.Utilities
using System.Text;
using System.Windows;
using System.Windows.Input;
using SystemTrayMenu.Helper;
using SystemTrayMenu.Helpers;
using static SystemTrayMenu.Utilities.FormsExtensions;
/// <summary>

View file

@ -2,7 +2,7 @@
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helper
namespace SystemTrayMenu.Helpers
{
using System;
using System.Runtime.Serialization;

View file

@ -2,7 +2,7 @@
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Helper
namespace SystemTrayMenu.Helpers
{
using System;

View file

@ -2,7 +2,7 @@
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
//
// Copyright (c) 2022-2022 Peter Kirmeier
// Copyright (c) 2022-2023 Peter Kirmeier
namespace SystemTrayMenu.UserInterface
{
@ -10,7 +10,7 @@ namespace SystemTrayMenu.UserInterface
using System.Reflection;
using System.Windows;
using System.Windows.Media.Imaging;
using SystemTrayMenu.Helper.Updater;
using SystemTrayMenu.Helpers.Updater;
/// <summary>
/// Logic of Update window.