將寫死改成活讀

This commit is contained in:
DangHome
2023-07-03 01:51:09 +08:00
parent a48d7b8d56
commit a8fd8f3f46
27 changed files with 703 additions and 546 deletions

View File

@@ -1,71 +1,79 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace CMM.Library.Helpers
namespace CMM.Library.Helpers;
internal class ConsoleHelper
{
internal class ConsoleHelper
const string cmdFileName = "cmd.exe";
private static Process CreatProcess(string fileName) =>
new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = fileName,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
}
};
public static async Task<string> ExecuteCommand(string command)
{
const string cmdFileName = "cmd.exe";
private static Process CreatProcess(string fileName) =>
new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = fileName,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
}
};
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = command;
p.Start();
var output = await p.StandardOutput.ReadToEndAsync();
await p.WaitForExitAsync();
public static async Task<string> CmdCommandAsync(params string[] cmds) =>
await CommandAsync(cmdFileName, cmds);
return output;
}
public static string CmdCommand(params string[] cmds) =>
Command(cmdFileName, cmds);
public static async Task<string> CmdCommandAsync(params string[] cmds) =>
await CommandAsync(cmdFileName, cmds);
public static async Task<string> CommandAsync(string fileName, params string[] cmds)
public static string CmdCommand(params string[] cmds) =>
Command(cmdFileName, cmds);
public static async Task<string> CommandAsync(string fileName, params string[] cmds)
{
var p = CreatProcess(fileName);
p.Start();
foreach (var cmd in cmds)
{
var p = CreatProcess(fileName);
p.Start();
foreach (var cmd in cmds)
{
p.StandardInput.WriteLine(cmd);
}
p.StandardInput.WriteLine("exit");
var result = await p.StandardOutput.ReadToEndAsync();
var error = await p.StandardError.ReadToEndAsync();
if (!string.IsNullOrWhiteSpace(error))
result = result + "\r\n<Error Message>:\r\n" + error;
await p.WaitForExitAsync();
p.Close();
Debug.WriteLine(result);
return result;
p.StandardInput.WriteLine(cmd);
}
p.StandardInput.WriteLine("exit");
var result = await p.StandardOutput.ReadToEndAsync();
var error = await p.StandardError.ReadToEndAsync();
if (!string.IsNullOrWhiteSpace(error))
result = result + "\r\n<Error Message>:\r\n" + error;
await p.WaitForExitAsync();
p.Close();
Debug.WriteLine(result);
return result;
}
public static string Command(string fileName, params string[] cmds)
public static string Command(string fileName, params string[] cmds)
{
var p = CreatProcess(fileName);
p.Start();
foreach (var cmd in cmds)
{
var p = CreatProcess(fileName);
p.Start();
foreach (var cmd in cmds)
{
p.StandardInput.WriteLine(cmd);
}
p.StandardInput.WriteLine("exit");
var result = p.StandardOutput.ReadToEnd();
var error = p.StandardError.ReadToEnd();
if (!string.IsNullOrWhiteSpace(error))
result = result + "\r\n<Error Message>:\r\n" + error;
p.WaitForExit();
p.Close();
Debug.WriteLine(result);
return result;
p.StandardInput.WriteLine(cmd);
}
p.StandardInput.WriteLine("exit");
var result = p.StandardOutput.ReadToEnd();
var error = p.StandardError.ReadToEnd();
if (!string.IsNullOrWhiteSpace(error))
result = result + "\r\n<Error Message>:\r\n" + error;
p.WaitForExit();
p.Close();
Debug.WriteLine(result);
return result;
}
}

View File

@@ -1,131 +1,126 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading.Tasks;
namespace CMM.Library.Helpers
namespace CMM.Library.Helpers;
static class JsonSerializerExtensions
{
static class JsonSerializerExtensions
public static JsonSerializerOptions defaultSettings = new JsonSerializerOptions()
{
public static JsonSerializerOptions defaultSettings = new JsonSerializerOptions()
WriteIndented = true,
IgnoreNullValues = true,
PropertyNamingPolicy = null,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
}
public static class JsonHelper
{
/// <summary>
/// 複製整個obj全部結構
/// </summary>
public static T DeepCopy<T>(T RealObject) =>
JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(RealObject, JsonSerializerExtensions.defaultSettings));
public static string JsonFormResource(this string fileName)
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName =
assembly.GetManifestResourceNames().
Where(str => str.Contains(fileName)).FirstOrDefault();
if (resourceName == null) return "";
using (var stream = assembly.GetManifestResourceStream(resourceName))
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
WriteIndented = true,
IgnoreNullValues = true,
PropertyNamingPolicy = null,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
return reader.ReadToEnd();
}
}
internal static class JsonHelper
public static T JsonFormResource<T>(this string fileName) =>
JsonFormString<T>(JsonFormResource(fileName));
public static T JsonFormFile<T>(this string fileName) =>
JsonFormString<T>(Load(fileName));
public static T JsonFormString<T>(this string json) =>
JsonSerializer.Deserialize<T>(json);
public static void FileToJson<T>(this T payload, string savePath) =>
Save(savePath, payload.ToJson());
public static string ToJson<T>(this T payload) =>
JsonSerializer.Serialize(payload, JsonSerializerExtensions.defaultSettings);
/// <summary>
/// 從Embedded resource讀string
/// </summary>
/// <param name="aFileName">resource位置不含副檔名</param>
public static string GetResource(this Assembly assembly, string aFileName)
{
/// <summary>
/// 複製整個obj全部結構
/// </summary>
public static T DeepCopy<T>(T RealObject) =>
JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(RealObject, JsonSerializerExtensions.defaultSettings));
var resourceName = assembly
.GetManifestResourceNames()
.Where(str => str.Contains(aFileName))
.FirstOrDefault();
if (resourceName == null) return "";
public static string JsonFormResource(this string fileName)
using (var stream = assembly.GetManifestResourceStream(resourceName))
using (var sr = new StreamReader(stream, Encoding.UTF8))
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName =
assembly.GetManifestResourceNames().
Where(str => str.Contains(fileName)).FirstOrDefault();
if (resourceName == null) return "";
using (var stream = assembly.GetManifestResourceStream(resourceName))
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
return sr.ReadToEnd();
}
}
public static T JsonFormResource<T>(this string fileName) =>
JsonFormString<T>(JsonFormResource(fileName));
public static string Load(string aFileName) =>
Load(new FileInfo(aFileName));
public static T JsonFormFile<T>(this string fileName) =>
JsonFormString<T>(Load(fileName));
public static T JsonFormString<T>(this string json) =>
JsonSerializer.Deserialize<T>(json);
public static void FileToJson<T>(this T payload, string savePath) =>
Save(savePath, payload.ToJson());
public static string ToJson<T>(this T payload) =>
JsonSerializer.Serialize(payload, JsonSerializerExtensions.defaultSettings);
/// <summary>
/// 從Embedded resource讀string
/// </summary>
/// <param name="aFileName">resource位置不含副檔名</param>
public static string GetResource(this Assembly assembly, string aFileName)
public static string Load(FileInfo aFi)
{
if (aFi.Exists)
{
var resourceName = assembly
.GetManifestResourceNames()
.Where(str => str.Contains(aFileName))
.FirstOrDefault();
if (resourceName == null) return "";
using (var stream = assembly.GetManifestResourceStream(resourceName))
using (var sr = new StreamReader(stream, Encoding.UTF8))
{
return sr.ReadToEnd();
}
}
public static string Load(string aFileName) =>
Load(new FileInfo(aFileName));
public static string Load(FileInfo aFi)
{
if (aFi.Exists)
{
string _Json = string.Empty;
try
{
var sr = new StreamReader(aFi.FullName);
_Json = sr.ReadToEnd();
sr.Close();
}
catch (IOException) { throw; }
catch (Exception) { throw; }
return _Json;
}
throw new Exception("開檔失敗。");
}
public static void Save(string filePath, string content) =>
Save(new FileInfo(filePath), content);
public static void Save(FileInfo aFi, string aContent)
{
if (!aFi.Directory.Exists)
{
aFi.Directory.Create();
}
if (aFi.Exists)
{
aFi.Delete();
}
aFi.Refresh();
if (aFi.Exists) throw new Exception("寫檔失敗,檔案已存在或已開啟。");
string _Json = string.Empty;
try
{
File.WriteAllText(aFi.FullName, aContent);
var sr = new StreamReader(aFi.FullName);
_Json = sr.ReadToEnd();
sr.Close();
}
catch (IOException) { throw; }
catch (Exception) { throw; }
return _Json;
}
throw new Exception("開檔失敗。");
}
public static void Save(string filePath, string content) =>
Save(new FileInfo(filePath), content);
public static void Save(FileInfo aFi, string aContent)
{
if (!aFi.Directory.Exists)
{
aFi.Directory.Create();
}
if (aFi.Exists)
{
aFi.Delete();
}
aFi.Refresh();
if (aFi.Exists) throw new Exception("寫檔失敗,檔案已存在或已開啟。");
try
{
File.WriteAllText(aFi.FullName, aContent);
}
catch (IOException) { throw; }
catch (Exception) { throw; }
}
}

View File

@@ -1,18 +1,16 @@
using System;
using System.Security.Principal;
using System.Security.Principal;
namespace CMM.Library.Helpers
namespace CMM.Library.Helpers;
public class UAC
{
public class UAC
public static void Check()
{
public static void Check()
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
throw new Exception($"Cannot delete task with your current identity '{identity.Name}' permissions level." +
"You likely need to run this application 'as administrator' even if you are using an administrator account.");
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
throw new Exception($"Cannot delete task with your current identity '{identity.Name}' permissions level." +
"You likely need to run this application 'as administrator' even if you are using an administrator account.");
}
}
}