Files
elwig/WGneu/Helpers/Utils.cs

109 lines
3.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.Diagnostics;
namespace WGneu.Helpers {
public static class Utils {
public static void SetInputChanged(Control input) {
input.BorderBrush = Brushes.Orange;
}
public static void SetInputInvalid(Control input) {
input.BorderBrush = Brushes.Red;
}
public static void ClearInputState(Control input) {
input.ClearValue(Control.BorderBrushProperty);
}
public static IEnumerable<T> FindVisualChilds<T>(DependencyObject depObj) where T : DependencyObject {
if (depObj == null)
yield return (T)Enumerable.Empty<T>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) {
DependencyObject ithChild = VisualTreeHelper.GetChild(depObj, i);
if (ithChild == null)
continue;
if (ithChild is T t)
yield return t;
foreach (T childOfChild in FindVisualChilds<T>(ithChild))
yield return childOfChild;
}
}
public static IEnumerable<T> FindVisualChilds<T>(DependencyObject depObj, IEnumerable<DependencyObject> exempt) where T : DependencyObject {
return FindVisualChilds<T>(depObj).Where(c => !exempt.Contains(c));
}
public static int Modulo(string a, int b) {
if (!a.All(char.IsDigit))
throw new ArgumentException("First argument has to be a decimal string");
return a.Select(ch => ch - '0').Aggregate((sum, n) => (sum * 10 + n) % b);
}
public static void RunBackground(string title, Func<Task> a) {
Task.Run(async () => {
try {
await a();
} catch (Exception e) {
MessageBox.Show(e.ToString(), title, MessageBoxButton.OK, MessageBoxImage.Error);
}
});
}
public static void MailTo(string emailAddress) {
Process.Start(new ProcessStartInfo() {
FileName = $"mailto:{emailAddress}",
UseShellExecute = true,
});
}
public sealed class TemporaryFile : IDisposable {
private int Usages = 0;
public string FilePath { get; private set; }
public TemporaryFile() : this(null) { }
public TemporaryFile(string? ext) : this(Path.Combine(Path.GetTempPath(), "Kelwin"), ext) { }
public TemporaryFile(string dir, string? ext) {
FilePath = Path.Combine(dir, Path.GetRandomFileName().Replace(".", "") + (ext != null ? $".{ext}" : ""));
Usages++;
Create();
}
~TemporaryFile() {
Delete();
}
public void Dispose() {
if (--Usages == 0) {
Delete();
GC.SuppressFinalize(this);
}
}
public TemporaryFile NewReference() {
Usages++;
return this;
}
private void Create() {
using (File.Create(FilePath)) { };
}
private void Delete() {
if (FilePath == null) return;
File.Delete(FilePath);
FilePath = null;
}
}
}
}