Skip to content

Instantly share code, notes, and snippets.

@haseeb-heaven
Last active May 26, 2022 15:05
Show Gist options
  • Save haseeb-heaven/717110c462c88b4fa755ce54e60c7e10 to your computer and use it in GitHub Desktop.
Save haseeb-heaven/717110c462c88b4fa755ce54e60c7e10 to your computer and use it in GitHub Desktop.
CSharp Utilities for UI,File Operations Handles,Web Connectsions and more.
//UI-Dialogs and MessageBox.
internal static void ShowWarning(string warnMsg, string caption = "WARNING") {
DialogMsgBox.ShowBox(caption, warnMsg, MsgBoxButtons.Ok);
}
internal static void ShowError(string errMsg, string caption = "ERROR") {
DialogMsgBox.ShowBox(caption, errMsg, MsgBoxButtons.Ok);
}
internal static void LogException(string methodName, Exception ex) {
methodName = methodName.Replace("Btn_Click", String.Empty).Replace("_SelectedIndexChanged", String.Empty).Replace("_SelectedValueChanged", String.Empty);
AddLog(methodName, "Exception MESSAGE: " + ex.Message + "\nREASON: " + ex.StackTrace);
}
internal static void ShowException(string methodName, Exception ex) {
ShowError("MESSAGE: " + ex.Message + "\nREASON: " + ex.StackTrace, methodName + " Exception");
}
internal static void ShowLogException(string methodName, Exception ex) {
methodName = methodName.Replace("Btn_Click", String.Empty).Replace("_SelectedIndexChanged", String.Empty).Replace("_SelectedValueChanged", String.Empty);
//Show and Log exception for method name.
ShowException(methodName, ex);
LogException(methodName, ex);
}
internal static void ShowLogError(string methodName, string errMsg, string caption = "ERROR") {
methodName = methodName.Replace("Btn_Click", String.Empty).Replace("_SelectedIndexChanged", String.Empty).Replace("_SelectedValueChanged", String.Empty);
//Show and Log error for method name.
ShowError(methodName + "(): " + errMsg, caption);
AddLog(methodName, errMsg);
}
internal static void ShowLogStatus(string methodName, string logMsg) {
IGIEditorUI.editorRef.SetStatusText(logMsg);
AddLog(methodName, logMsg);
}
internal static void ShowLogInfo(string methodName, string logMsg) {
ShowInfo(logMsg);
AddLog(methodName, logMsg);
}
internal static void ShowInfo(string infoMsg, string caption = "INFO") {
DialogMsgBox.ShowBox(caption, infoMsg, MsgBoxButtons.Ok);
}
internal static DialogResult ShowDialog(string infoMsg, string caption = "INFO") {
return DialogMsgBox.ShowBox(caption, infoMsg, MsgBoxButtons.YesNo);
}
internal static void ShowConfigError(string keyword) {
ShowError("Config has invalid property for '" + keyword + "'", CAPTION_CONFIG_ERR);
}
internal static void ShowSystemFatalError(string errMsg) {
ShowError(errMsg, CAPTION_FATAL_SYS_ERR);
Environment.Exit(1);
}
internal static bool ShowEditModeDialog() {
var editorDlg = ShowDialog("Edit Mode not enabled to edit the level\nDo you want to enable Edit mode now ?", EDITOR_LEVEL_ERR);
if (editorDlg == DialogResult.Yes)
return true;
return false;
}
private DialogResult ShowOptionInfo(string infoMsg) {
return DialogMsgBox.ShowBox("Edit Mode", infoMsg);
}
//Private method to get machine id.
private static string GetUUID() {
string uidArgs = "wmic csproduct get UUID";
string uuidOut = ShellExec(uidArgs);
string uid = uuidOut.Split(new [] {
Environment.NewLine
}, StringSplitOptions.None)[1];
return uid.Trim();
}
//Private method to get GUID.
private static string GetGUID() {
Guid guidObj = Guid.NewGuid();
string guid = guidObj.ToString();
return guid;
}
//Private method to get MAC/Physical address.
internal static string GetMACAddress() {
string macAddrArgs = "wmic nic get MACAddress";
string macAddressOut = ShellExec(macAddrArgs);
var macAddressList = macAddressOut.Split(new [] {
Environment.NewLine
}, StringSplitOptions.RemoveEmptyEntries);
string macAddress = null;
foreach(var address in macAddressList) {
if (!String.IsNullOrEmpty(address) && address.Count(c => c == ':') > 4) {
macAddress = address;
break;
}
}
return macAddress.Trim();
}
internal static string GetPrivateIP() {
string ipAddrArgs = "ipconfig /all | findstr /c:IPv4";
const string ipOut = " IPv4 Address. . . . . . . . . . . : ";
string ipAddressOut = ShellExec(ipAddrArgs);
string[] ips = ipAddressOut.Split(new [] {
Environment.NewLine
}, StringSplitOptions.RemoveEmptyEntries);
List < string > ipAddresses = new List < string > (ips);
int ipLens = ipAddresses.Count - 1;
string privateIp = ipAddresses[ipLens].Substring(ipOut.Length).Replace("(Preferred)", "").Trim();
return privateIp;
}
internal static FOpenIO ShowOpenFileDlg(string title, string defaultExt, string filter, bool initDir = false, string initialDirectory = "", bool openFileData = true, bool exceptionOnEmpty = true) {
var fopenIO = new FOpenIO();
try {
var fileBrowser = new OpenFileDialog();
fileBrowser.ValidateNames = false;
fileBrowser.CheckFileExists = false;
fileBrowser.CheckPathExists = true;
fileBrowser.Title = title;
fileBrowser.DefaultExt = defaultExt;
fileBrowser.Filter = filter;
if (initDir)
fileBrowser.InitialDirectory = initialDirectory;
if (fileBrowser.ShowDialog() == DialogResult.OK) {
fopenIO.FileName = fileBrowser.FileName;
fopenIO.FileLength = new FileInfo(fopenIO.FileName).Length;
fopenIO.FileSize = ((float) fopenIO.FileLength / (float) 1024);
if (openFileData) {
fopenIO.FileData = QUtils.LoadFile(fopenIO.FileName);
if (String.IsNullOrEmpty(fopenIO.FileData) && exceptionOnEmpty) throw new FileLoadException("File '" + fopenIO.FileName + "' is invalid or data is empty.");
}
}
} catch (Exception ex) {
QUtils.ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
return fopenIO;
}
internal class FOpenIO {
string fileName;
string fileData;
long fileLength;
float fileSize;
public FOpenIO() {
FileName = FileData = null;
FileLength = 0;
FileSize = 0;
}
public FOpenIO(string fileName, string fileData, long fileLength, float fileSize) {
this.FileName = fileName;
this.FileData = fileData;
this.FileLength = fileLength;
this.FileSize = fileSize;
}
public string FileName {
get => fileName;
set => fileName = value;
}
public string FileData {
get => fileData;
set => fileData = value;
}
public long FileLength {
get => fileLength;
set => fileLength = value;
}
public float FileSize {
get => fileSize;
set => fileSize = value;
}
}
//File Operation Utilities C# Version.
internal static void FileMove(string srcPath, string destPath) {
try {
if (File.Exists(srcPath)) File.Move(srcPath, destPath);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void FileCopy(string srcPath, string destPath, bool overwirte = true) {
try {
if (File.Exists(srcPath)) File.Copy(srcPath, destPath, overwirte);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void FileDelete(string path) {
try {
if (File.Exists(path)) File.Delete(path);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
//File Operation Utilities VB Version.
internal static void FileIOMove(string srcPath, string destPath, bool overwrite = true) {
try {
if (File.Exists(srcPath)) FileSystem.MoveFile(srcPath, destPath, overwrite);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void FileIOMove(string srcPath, string destPath, FileIO.UIOption showUI, FileIO.UICancelOption onUserCancel) {
try {
if (File.Exists(srcPath)) FileSystem.MoveFile(srcPath, destPath, showUI, onUserCancel);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void FileIOCopy(string srcPath, string destPath, bool overwrite = true) {
try {
if (File.Exists(srcPath)) FileSystem.CopyFile(srcPath, destPath, overwrite);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void FileIOCopy(string srcPath, string destPath, FileIO.UIOption showUI, FileIO.UICancelOption onUserCancel) {
try {
if (File.Exists(srcPath)) FileSystem.CopyFile(srcPath, destPath);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void FileIODelete(string path, FileIO.UIOption showUI = FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption recycle = FileIO.RecycleOption.SendToRecycleBin, FileIO.UICancelOption onUserCancel = FileIO.UICancelOption.ThrowException) {
try {
if (File.Exists(path)) FileSystem.DeleteFile(path, showUI, recycle, onUserCancel);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void FileRename(string oldName, string newName) {
try {
if (File.Exists(oldName)) FileSystem.RenameFile(oldName, newName);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
//Directory Operation Utilities C#.
internal static void DirectoryMove(string srcPath, string destPath) {
try {
if (Directory.Exists(srcPath)) Directory.Move(srcPath, destPath);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void DirectoryMove(string srcPath, string destPath, int __ignore) {
var mvCmd = "mv " + srcPath + " " + destPath;
var moveCmd = "move " + srcPath + " " + destPath + " /y";
try {
//#1 solution to move with same root directory.
Directory.Move(srcPath, destPath);
} catch (IOException ex) {
if (ex.Message.Contains("already exist")) {
DirectoryDelete(srcPath);
} else {
//#2 solution to move with POSIX 'mv' command.
ShellExec(mvCmd, true, true, "powershell.exe");
if (Directory.Exists(srcPath))
//#3 solution to move with 'move' command.
ShellExec(moveCmd, true);
}
}
}
internal static void DirectoryDelete(string dirPath) {
try {
if (Directory.Exists(dirPath)) {
DirectoryInfo di = new DirectoryInfo(dirPath);
foreach(FileInfo file in di.GetFiles())
file.Delete();
foreach(DirectoryInfo dir in di.GetDirectories())
dir.Delete(true);
Directory.Delete(dirPath);
}
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
//Directory Operation Utilities VB.
internal static void DirectoryIOMove(string srcPath, string destPath, bool overwrite = true) {
try {
if (Directory.Exists(srcPath)) FileSystem.MoveDirectory(srcPath, destPath, overwrite);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void DirectoryIOMove(string srcPath, string destPath, FileIO.UIOption showUI, FileIO.UICancelOption onUserCancel) {
try {
if (Directory.Exists(srcPath)) FileSystem.MoveDirectory(srcPath, destPath, showUI, onUserCancel);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void DirectoryIOCopy(string srcPath, string destPath, bool overwirte = true) {
try {
if (Directory.Exists(srcPath)) FileSystem.CopyDirectory(srcPath, destPath, overwirte);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void DirectoryIOCopy(string srcPath, string destPath, FileIO.UIOption showUI, FileIO.UICancelOption onUserCancel) {
try {
if (Directory.Exists(srcPath)) FileSystem.CopyDirectory(srcPath, destPath, showUI, onUserCancel);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void DirectoryIODelete(string path, FileIO.DeleteDirectoryOption deleteContents = FileIO.DeleteDirectoryOption.DeleteAllContents) {
try {
if (Directory.Exists(path)) FileSystem.DeleteDirectory(path, deleteContents);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static void DirectoryRename(string oldName, string newName) {
try {
if (File.Exists(oldName)) FileSystem.RenameDirectory(oldName, newName);
} catch (Exception ex) {
ShowLogException(MethodBase.GetCurrentMethod().Name, ex);
}
}
internal static bool IsDirectoryEmpty(string path) {
return !Directory.EnumerateFileSystemEntries(path).Any();
}
internal static string Reverse(string str) {
char[] charArray = str.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
internal static string WebReader(string url) {
string strContent = null;
try {
//Config for WebReader Class for .NET 4.0.
ServicePointManager.SecurityProtocol = (SecurityProtocolType) 3072;
var webRequest = WebRequest.Create(url);
using(var response = webRequest.GetResponse())
using(var content = response.GetResponseStream())
using(var reader = new StreamReader(content)) {
strContent = reader.ReadToEnd();
return strContent;
}
} catch (Exception ex) {
if (ex.Message.Contains("remote"))
ShowError("Please check your internet connection.");
else
ShowError(ex.Message, "WebReader Error");
}
return strContent;
}
internal static void WebDownload(string url, string fileName, string destPath) {
if (!editorOnline) return;
try {
WebClient webClient = new WebClient();
webClient.DownloadFile(url, fileName);
if (!Directory.Exists(destPath)) CreateCacheDir();
ShellExec("move /Y " + fileName + " " + destPath);
} catch (Exception ex) {
if (ex.Message.Contains("The remote name could not be resolved")) {
ShowError("Resource error Please check your internet connection and try Again");
} else
ShowError(ex.Message ?? ex.StackTrace);
}
}
internal static void ShowPathExplorer(string path) {
Process.Start(new ProcessStartInfo() {
FileName = path,
UseShellExecute = true,
Verb = "open"
});
}
//Execute shell command and get std-output.
internal static string ShellExec(string cmdArgs, bool runAsAdmin = false, bool waitForExit = true, string shell = "cmd.exe") {
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.CreateNoWindow = true;
startInfo.FileName = shell;
startInfo.Arguments = "/c " + cmdArgs;
startInfo.RedirectStandardOutput = !runAsAdmin;
startInfo.RedirectStandardError = !runAsAdmin;
startInfo.UseShellExecute = runAsAdmin;
process.StartInfo = startInfo;
if (runAsAdmin) process.StartInfo.Verb = "runas";
process.Start();
if (!waitForExit) return null;
string output = (runAsAdmin) ? String.Empty : process.StandardOutput.ReadToEnd();
process.WaitForExit();
return output;
}
internal static string LoadFile(string fileName) {
string data = null;
if (File.Exists(fileName))
data = File.ReadAllText(fileName);
return data;
}
internal static void SaveFile(string fileName, string data, bool appendData = false) {
if (appendData)
File.AppendAllText(fileName, data);
else
File.WriteAllText(fileName, data);
}
internal static bool IsNetworkAvailable() {
return IsNetworkAvailable(0);
}
internal static bool IsNetworkAvailable(long minimumSpeed) {
if (!NetworkInterface.GetIsNetworkAvailable())
return false;
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) {
// discard because of standard reasons
if ((ni.OperationalStatus != OperationalStatus.Up) ||
(ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
(ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel))
continue;
// this allow to filter modems, serial, etc.
// I use 10000000 as a minimum speed for most cases
if (ni.Speed < minimumSpeed)
continue;
// discard virtual cards (virtual box, virtual pc, etc.)
if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
// discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card.
if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase))
continue;
return true;
}
return false;
}
//Logging.
internal static void EnableLogs() {
if (!logEnabled)
logEnabled = true;
}
internal static void DisableLogs() {
if (logEnabled)
logEnabled = false;
}
internal static void AddLog(string methodName, string logMsg) {
if (logEnabled) {
methodName = methodName.Replace("Btn_Click", String.Empty).Replace("_SelectedIndexChanged", String.Empty).Replace("_SelectedValueChanged", String.Empty);
File.AppendAllText(logFile, "[" + DateTime.Now.ToString("yyyy-MM-dd - HH:mm:ss") + "] " + methodName + "(): " + logMsg + "\n");
}
}
internal static string GenerateRandStr(int length) {
const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[rand.Next(s.Length)]).ToArray());
}
internal static void Sleep(int seconds) {
Thread.Sleep(seconds * 1000);
}
internal static void Sleep(float seconds) {
Thread.Sleep((int) seconds * 1000);
}
}
internal static class Extensions {
internal static string Slice(this string source, int start, int end) {
if (end < 0) {
end = source.Length + end;
}
int len = end - start;
return source.Substring(start, len);
}
internal static string ReplaceFirst(this string text, string search, string replace) {
int pos = text.IndexOf(search);
if (pos < 0) {
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
internal static string ReplaceLast(this string text, string search, string replace) {
int place = text.LastIndexOf(search);
if (place == -1)
return text;
string result = text.Remove(place, search.Length).Insert(place, replace);
return result;
}
internal static bool IsNonASCII(this string str) {
return (Encoding.UTF8.GetByteCount(str) != str.Length);
}
internal static bool HasBinaryContent(this string content) {
return content.Any(ch => char.IsControl(ch) && ch != '\r' && ch != '\n');
}
internal static double ToRadians(this double angle) {
// Angle in 10th of a degree
return (angle * Math.PI) / 180;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment