initial checkin of yaulw (locally)
This commit is contained in:
423
Other/CMDLine.cs
Normal file
423
Other/CMDLine.cs
Normal file
@@ -0,0 +1,423 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Collections.Specialized;
|
||||
|
||||
using Yaulw.Tools;
|
||||
|
||||
namespace Yaulw.Other
|
||||
{
|
||||
/// <remarks>
|
||||
/// CommandLine Arguments Parser for an Application
|
||||
/// <example>
|
||||
/// <code>
|
||||
/// internal CMDline cmdline = new CMDline(typeof(App.CommandLine_Option), typeof(App.CommandLine_Flag));
|
||||
///
|
||||
/// public enum CommandLine_Flag
|
||||
/// {
|
||||
/// START,
|
||||
/// STOP,
|
||||
/// SHOW,
|
||||
/// }
|
||||
///
|
||||
/// public enum CommandLine_Option
|
||||
/// {
|
||||
/// ADD_SOMETHING,
|
||||
/// REMOVE_SOMETHING,
|
||||
/// }
|
||||
///
|
||||
/// cmdline.Parse(e.Args);
|
||||
///
|
||||
/// if (cmdline.HasParams)
|
||||
/// {
|
||||
/// if (App.cmdline.ShowHelp || !App.cmdline.ParamsValid)
|
||||
/// {
|
||||
/// ShowCommandLineHelp();
|
||||
/// return;
|
||||
/// }
|
||||
///
|
||||
/// string AddSomething = cmdline.GetOptionValue<string>(CommandLine_Option.ADD_SOMETHING, ""); //</string>
|
||||
/// }
|
||||
/// </code>
|
||||
/// </example>
|
||||
/// </remarks>
|
||||
public class CMDline
|
||||
{
|
||||
#region private Variables
|
||||
|
||||
// Flag or Option Specifiers CONSTS
|
||||
private const String FLAG_OR_OPTION_SPECIFIER = "-/";
|
||||
private const String HELP_FLAG_SPECIFIER = "?";
|
||||
|
||||
// Private Parsing Enums
|
||||
private Type _CMDLineOptions = null;
|
||||
private Type _CMDLineFlags = null;
|
||||
|
||||
// Private Parsing Data Structures
|
||||
private Stack<String> _stringStack = new Stack<String>();
|
||||
private StringDictionary _stringDictionary = new StringDictionary();
|
||||
|
||||
// Keep track of the last parsed args as an array
|
||||
private string[] _lastparsedArgs = null;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Construction
|
||||
|
||||
/// <summary>
|
||||
/// The Command Line Class needs to know what Options and Flags to Parse for
|
||||
/// </summary>
|
||||
/// <param name="CMDLineOptions">Pass an Enum used to determine CommandLine Options</param>
|
||||
/// <param name="CMDLineFlags">Pass an Enum used to determine CommandLine Flags</param>
|
||||
public CMDline(Type Enum_CMDLineOptions, Type Enum_CMDLineFlags)
|
||||
{
|
||||
if (Enum_CMDLineOptions.IsEnum && Enum_CMDLineFlags.IsEnum)
|
||||
{
|
||||
_CMDLineOptions = Enum_CMDLineOptions;
|
||||
_CMDLineFlags = Enum_CMDLineFlags;
|
||||
}
|
||||
else
|
||||
throw new ArgumentException("Both CMDLineOptions and CMDLineFlags must be Enums");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// True if User Passed in any Parameters
|
||||
/// </summary>
|
||||
public bool HasParams { get { return (_stringDictionary.Count >= 1); } }
|
||||
|
||||
/// <summary>
|
||||
/// True if User requested Command-Line Help
|
||||
/// </summary>
|
||||
public bool ShowHelp { get { return GetFlagOrOptionValueBool(HELP_FLAG_SPECIFIER); } }
|
||||
|
||||
/// <summary>
|
||||
/// True if all Parameters parsed are valid, False otherwise
|
||||
/// </summary>
|
||||
public bool ParamsValid
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!HasParams)
|
||||
return true;
|
||||
|
||||
string[] OptionNames = Enum.GetNames(_CMDLineOptions);
|
||||
string[] FlagNames = Enum.GetNames(_CMDLineFlags);
|
||||
|
||||
// Get All Flags and Options
|
||||
List<String> AllFlagsAndOptions = new List<String>();
|
||||
foreach (string Option in OptionNames)
|
||||
AllFlagsAndOptions.Add(Option.ToLower());
|
||||
foreach (string Flag in FlagNames)
|
||||
AllFlagsAndOptions.Add(Flag.ToLower());
|
||||
|
||||
// Verify the Parameters
|
||||
bool InvalidParamFound = false;
|
||||
foreach (string key in _stringDictionary.Keys)
|
||||
{
|
||||
InvalidParamFound = (key != HELP_FLAG_SPECIFIER) && !AllFlagsAndOptions.Contains(key);
|
||||
if (InvalidParamFound)
|
||||
break;
|
||||
}
|
||||
return !InvalidParamFound;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Main Entry Function to Retrieve an Option Value
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Should be a System Type like string, bool, int32, double, decimal, etc...</typeparam>
|
||||
/// <param name="option">option to retrieve (From CMDLineOptions Enum)</param>
|
||||
/// <param name="DefaultValue">Default value to use if nothing was retrieved * Error occured *</param>
|
||||
/// <returns>value or default value, if not found</returns>
|
||||
public T GetOptionValue<T>(Enum option, T DefaultValue)
|
||||
{
|
||||
T RetVal = DefaultValue;
|
||||
string StringVal = GetFlagOrOptionValueStr(option.ToString());
|
||||
try
|
||||
{
|
||||
if (ObjTool.IsNotNullAndNotEmpty(StringVal))
|
||||
{
|
||||
RetVal = ObjTool.ConvertStringToObj<T>(StringVal);
|
||||
}
|
||||
}
|
||||
catch (Exception) { /* ignore */ }
|
||||
return RetVal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Main Entry Function to Retrieve a Flag Value
|
||||
/// </summary>
|
||||
/// <param name="flag">flag enum to retrieve (From CMDLineFlags Enum)</param>
|
||||
/// <returns>Bool Value found or false if not found</returns>
|
||||
public bool GetFlagValue(Enum flag)
|
||||
{
|
||||
return GetFlagOrOptionValueBool(flag.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the Last Parsed Arguments as a string
|
||||
/// </summary>
|
||||
/// <returns>returns last parsed args or String.Empty if none</returns>
|
||||
public string ParsedArgs()
|
||||
{
|
||||
if (_lastparsedArgs != null && _lastparsedArgs.Length > 0)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
foreach (string s in _lastparsedArgs)
|
||||
{
|
||||
sb.Append(s);
|
||||
sb.Append(" ");
|
||||
}
|
||||
|
||||
sb.Remove(sb.Length - 1, 1); // remove trailing " "
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Private Helper Functions
|
||||
|
||||
/// <summary>
|
||||
/// Main Function used to Retrieve a String Value
|
||||
/// </summary>
|
||||
/// <param name="FlagOrOption">Flag or Option to get Value for</param>
|
||||
/// <returns>Value or Empty if not found</returns>
|
||||
private string GetFlagOrOptionValueStr(string FlagOrOption)
|
||||
{
|
||||
// If there is a FLAG_OR_OPTION_CHARS, stripe it
|
||||
if (IsFlagOrOption(FlagOrOption))
|
||||
FlagOrOption = GetFlagOrOption(FlagOrOption);
|
||||
|
||||
FlagOrOption = FlagOrOption.ToLower();
|
||||
if (_stringDictionary.ContainsKey(FlagOrOption))
|
||||
return _stringDictionary[FlagOrOption];
|
||||
return String.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Main Function used to Retrieve a Bool Value
|
||||
/// </summary>
|
||||
/// <param name="FlagOrOption">Flag or Option to get Value for</param>
|
||||
/// <returns>True or False if not found</returns>
|
||||
private bool GetFlagOrOptionValueBool(string FlagOrOption)
|
||||
{
|
||||
try
|
||||
{
|
||||
string Value = GetFlagOrOptionValueStr(FlagOrOption);
|
||||
if (!String.IsNullOrEmpty(Value))
|
||||
{
|
||||
bool bValue = bool.Parse(Value);
|
||||
return bValue;
|
||||
}
|
||||
}
|
||||
catch (Exception) { /*Ignore*/ }
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Parsing Methods
|
||||
|
||||
/// <returns>true if the param is a flag or option</returns>
|
||||
private bool IsFlagOrOption(string arg)
|
||||
{
|
||||
return (FLAG_OR_OPTION_SPECIFIER.Contains(arg[0].ToString()));
|
||||
}
|
||||
|
||||
/// <returns>the Value of a Param</returns>
|
||||
private string GetFlagOrOption(string arg)
|
||||
{
|
||||
return arg.Substring(1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Main Entry Function used to Parse CommandLine parameters
|
||||
/// </summary>
|
||||
/// <param name="args">command line arguments</param>
|
||||
/// <returns>true if any parsing occured, false otherwise</returns>
|
||||
public bool Parse(string[] args)
|
||||
{
|
||||
return Parse(args, true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Main Entry Function used to Parse CommandLine parameters
|
||||
/// </summary>
|
||||
/// <param name="args">command line arguments</param>
|
||||
/// <param name="bAlwaysParseOptionsAsTrue">Allows you to not parse Options as True, if in case the option is blank it will just be considered a blank option/flag</param>
|
||||
/// <returns>true if any parsing occured, false otherwise</returns>
|
||||
public bool Parse(string[] args, bool bAlwaysParseOptionsAsTrue)
|
||||
{
|
||||
if (args == null || args.Length <= 0)
|
||||
return false;
|
||||
|
||||
_stringDictionary.Clear();
|
||||
_stringStack.Clear();
|
||||
_lastparsedArgs = args;
|
||||
foreach (string arg in args)
|
||||
{
|
||||
if (!String.IsNullOrEmpty(arg))
|
||||
{
|
||||
if (IsFlagOrOption(arg))
|
||||
{
|
||||
_stringStack.Push(GetFlagOrOption(arg).ToLower());
|
||||
if (bAlwaysParseOptionsAsTrue)
|
||||
_stringDictionary[GetFlagOrOption(arg).ToLower()] = "TRUE";
|
||||
}
|
||||
else
|
||||
{
|
||||
// must have a flag or option on the stack,
|
||||
// if it does we use it
|
||||
if (_stringStack.Count >= 1)
|
||||
{
|
||||
_stringDictionary[_stringStack.Pop()] = Parse_ArgCleanup(arg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_stringStack.Clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Used only when cmd is constructed with (null, null),
|
||||
/// and the cmd.Parse function is called. will iterate thru the internal
|
||||
/// dictionary and stack and make sure that the command string / line items
|
||||
/// are valid
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string MakeValidCmdStrFromNewlyParsedCmdLine()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
foreach (string key in _stringDictionary.Keys)
|
||||
{
|
||||
sb.Append(FLAG_OR_OPTION_SPECIFIER[0]);
|
||||
sb.Append(MakeValidCmdStr(key));
|
||||
sb.Append("=");
|
||||
sb.Append(_stringDictionary[key]);
|
||||
sb.Append("");
|
||||
}
|
||||
|
||||
foreach (string flag in _stringStack)
|
||||
{
|
||||
sb.Append(FLAG_OR_OPTION_SPECIFIER[0]);
|
||||
sb.Append(MakeValidCmdStr(flag));
|
||||
sb.Append("");
|
||||
}
|
||||
|
||||
// remove trailing space
|
||||
sb = sb.Remove(sb.Length - 1, 1);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// It appears that the Command-Line can foul us up sometimes when passing
|
||||
/// certain arguments. This function deals with these special cases.
|
||||
/// </summary>
|
||||
/// <param name="arg">arg to check/poss.clean up</param>
|
||||
/// <returns>cleaned up arg, if needed</returns>
|
||||
private string Parse_ArgCleanup(string arg)
|
||||
{
|
||||
if (!String.IsNullOrEmpty(arg) &&
|
||||
(arg.Length > 2) &&
|
||||
(arg[arg.Length - 1] == '"')) // when passing a \ at the end of the command-line with a "
|
||||
{
|
||||
arg = arg.Remove(arg.Length - 1);
|
||||
arg += "\\";
|
||||
}
|
||||
return arg;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Static Generate CmdLine Method
|
||||
|
||||
/// <summary>
|
||||
/// Generates a CommandLine Parameter String from the Options/Flags Given
|
||||
/// </summary>
|
||||
/// <param name="Options">StringDictionary that contains all the Options, to use</param>
|
||||
/// <param name="Flags">List that contains all the Flags to use</param>
|
||||
/// <returns>a string that can be passed via the commandLine</returns>
|
||||
public static string GenerateCmdLine(StringDictionary Options, List<String> Flags)
|
||||
{
|
||||
string CmdLine = String.Empty;
|
||||
|
||||
// Iterate Options, and add them
|
||||
if (Options != null && Options.Count > 0)
|
||||
{
|
||||
foreach (string Key in Options.Keys)
|
||||
{
|
||||
string cmdKey = MakeValidCmdStr(Key);
|
||||
string cmdValue = Options[Key];
|
||||
CmdLine = CmdLine + FLAG_OR_OPTION_SPECIFIER[0] + cmdKey + " " + "\"" + cmdValue + "\"" + " ";
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate Flags, and add them
|
||||
if (Flags != null && Flags.Count > 0)
|
||||
{
|
||||
foreach (string Flag in Flags)
|
||||
{
|
||||
string cmdFlag = MakeValidCmdStr(Flag);
|
||||
CmdLine = CmdLine + FLAG_OR_OPTION_SPECIFIER[0] + cmdFlag + " ";
|
||||
}
|
||||
}
|
||||
|
||||
// Return the generated Commmand Line
|
||||
return CmdLine;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ensures Integrity with the Generated CMDLine string that Keys don't
|
||||
/// contain Illegal Characters
|
||||
/// </summary>
|
||||
/// <param name="Key">a Key to make sure it is valid</param>
|
||||
/// <returns>a valid Key</returns>
|
||||
private static string MakeValidCmdStr(string Key)
|
||||
{
|
||||
if (!String.IsNullOrEmpty(Key))
|
||||
{
|
||||
//":\\ _!@#$%^&()-+{}[],.;`~";
|
||||
Key = Key.Replace(" ", "_");
|
||||
Key = Key.Replace(":", "_");
|
||||
Key = Key.Replace("\\", "_");
|
||||
Key = Key.Replace("/", "_");
|
||||
Key = Key.Replace("!", "_");
|
||||
Key = Key.Replace("@", "_");
|
||||
Key = Key.Replace("#", "_");
|
||||
Key = Key.Replace("$", "_");
|
||||
Key = Key.Replace("%", "_");
|
||||
Key = Key.Replace("^", "_");
|
||||
Key = Key.Replace("&", "_");
|
||||
Key = Key.Replace("(", "_");
|
||||
Key = Key.Replace(")", "_");
|
||||
Key = Key.Replace("-", "_");
|
||||
Key = Key.Replace("+", "_");
|
||||
Key = Key.Replace("{", "_");
|
||||
Key = Key.Replace("}", "_");
|
||||
Key = Key.Replace("[", "_");
|
||||
Key = Key.Replace("]", "_");
|
||||
Key = Key.Replace(",", "_");
|
||||
Key = Key.Replace(".", "_");
|
||||
Key = Key.Replace(";", "_");
|
||||
Key = Key.Replace("'", "_");
|
||||
Key = Key.Replace("~", "_");
|
||||
return Key;
|
||||
}
|
||||
return String.Empty;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
102
Other/CMDcommands.cs
Normal file
102
Other/CMDcommands.cs
Normal file
@@ -0,0 +1,102 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Yaulw.Other
|
||||
{
|
||||
/// <remarks>
|
||||
/// Commonly used Batch/CMD command Line Command
|
||||
/// </remarks>
|
||||
public static class CMDcommands
|
||||
{
|
||||
#region CMDCommands
|
||||
|
||||
/// <summary>
|
||||
/// map a credential to a network path
|
||||
/// </summary>
|
||||
/// <param name="path">network path</param>
|
||||
/// <param name="user">user</param>
|
||||
/// <param name="pwd">password</param>
|
||||
/// <returns>Command-Line Command</returns>
|
||||
static public string net_use(string path, string user, string pwd)
|
||||
{
|
||||
return ("net use " + path + " /User:" + user + " " + pwd);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// map a credential and drive letter to a network path
|
||||
/// </summary>
|
||||
/// <param name="path">network path</param>
|
||||
/// <param name="driveletter">drive letter to map</param>
|
||||
/// <param name="user">user</param>
|
||||
/// <param name="pwd">password</param>
|
||||
/// <param name="path"></param>
|
||||
/// <returns>Command-Line Command</returns>
|
||||
static public string net_use_persist(string path, string driveletter, string user, string pwd)
|
||||
{
|
||||
return ("net use " + driveletter + ": " + path + " /User:" + user + " " + pwd + " PERSISTENT:YES");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete a Network Credential from a network path
|
||||
/// </summary>
|
||||
/// <param name="path">network path</param>
|
||||
/// <returns>Command-Line Command</returns>
|
||||
static public string net_delete(string path)
|
||||
{
|
||||
return ("net use /delete " + path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete a Drive Letter and Network Credential from a network path
|
||||
/// </summary>
|
||||
/// <param name="driveletter"></param>
|
||||
/// <returns>Command-Line Command</returns>
|
||||
static public string net_delete_persist(string driveletter)
|
||||
{
|
||||
return ("net use /delete " + driveletter + ":");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region PSTools
|
||||
|
||||
/// <remarks>
|
||||
/// Commands for System Internals PSExec Tools
|
||||
/// </remarks>
|
||||
public static class PSTools
|
||||
{
|
||||
/// <summary>
|
||||
/// PSExec is a System Internals Remote Execution CommandLine tool.
|
||||
/// Use this to execute a .bat/.cmd file on the other computer
|
||||
/// </summary>
|
||||
/// <param name="computer">Name of computer</param>
|
||||
/// <param name="file">.bat or .cmd file to execute</param>
|
||||
/// <param name="user">user</param>
|
||||
/// <param name="pwd">password</param>
|
||||
/// <param name="interactive">true to allow remote process to interact with desktop</param>
|
||||
/// <returns>Command-Line Command</returns>
|
||||
static public string ps_exec(string computer, string file, string user, string pwd, bool interactive)
|
||||
{
|
||||
string Show = "";
|
||||
if (interactive)
|
||||
Show = "-i ";
|
||||
|
||||
if (file.ToLower().Contains(".bat") || file.ToLower().Contains(".cmd"))
|
||||
{
|
||||
// copy .bat or .cmd file over
|
||||
return (@"psexec.exe \\" + computer + " -u " + user + " -p " + pwd + " -c -f -e -d " + Show + "/accepteula " + '\"' + file + '\"');
|
||||
}
|
||||
else
|
||||
{
|
||||
// doesn't copy over, executes command from location, don't wait for process to terminate
|
||||
return (@"psexec.exe \\" + computer + " -u " + user + " -p " + pwd + " -d -e " + Show + "/accepteula " + '\"' + file + '\"');
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
83
Other/CMDexecute.cs
Normal file
83
Other/CMDexecute.cs
Normal file
@@ -0,0 +1,83 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.IO;
|
||||
|
||||
using Yaulw.File;
|
||||
|
||||
namespace Yaulw.Other
|
||||
{
|
||||
/// <remarks>
|
||||
/// Usefull for quickly generating a .bat file and executing it (without a command window)
|
||||
/// </remarks>
|
||||
public static class CMDexecute
|
||||
{
|
||||
#region Public Static Methods
|
||||
|
||||
/// <summary>
|
||||
/// Executes the passed in command on the command line * No Command Window Created *
|
||||
/// </summary>
|
||||
/// <param name="command">a command-line command</param>
|
||||
/// <param name="bWait">true to wait till process ends, false otherwise</param>
|
||||
/// <param name="bUseRunAs">If true, will set "RunAs" For the Process, to Run as Administrator</param>
|
||||
public static void cmd(string command, bool bWait = true, bool bRunAs = false)
|
||||
{
|
||||
FileWriter fileW = new FileWriter(String.Empty, "bat");
|
||||
fileW.DeleteFile();
|
||||
fileW.WriteLineUTF8(command);
|
||||
execBatFile(fileW.FileNameNPath, bWait, bRunAs);
|
||||
fileW.DeleteFile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the passed in commands on the command line * No Command Window Created *
|
||||
/// </summary>
|
||||
/// <param name="commands">command-line commands</param>
|
||||
/// <param name="bWait">true to wait till process ends, false otherwise</param>
|
||||
/// <param name="bUseRunAs">If true, will set "RunAs" For the Process, to Run as Administrator</param>
|
||||
public static void cmd(string[] commands, bool bWait = true, bool bRunAs = false)
|
||||
{
|
||||
FileWriter fileW = new FileWriter(String.Empty, "bat");
|
||||
fileW.DeleteFile();
|
||||
foreach (string command in commands)
|
||||
fileW.WriteLineUTF8(command);
|
||||
execBatFile(fileW.FileNameNPath, bWait, bRunAs);
|
||||
fileW.DeleteFile();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Static Helpers
|
||||
|
||||
/// <summary>
|
||||
/// Executes the Batch file via CMD.exe, by starting the CMD.exe Process with no Window
|
||||
/// </summary>
|
||||
/// <param name="FileNameNPath">File (.bat) scrip to execute</param>
|
||||
/// <param name="bWait">true to wait till process ends, false otherwise</param>
|
||||
private static void execBatFile(string FileNameNPath, bool bWait = true, bool bUseRunAs = false)
|
||||
{
|
||||
if (!String.IsNullOrEmpty(FileNameNPath) && System.IO.File.Exists(FileNameNPath))
|
||||
{
|
||||
//The "/C" Tells Windows to Run The Command then Terminate
|
||||
string strCmdLine = "/C " + '\"' + FileNameNPath + '\"';
|
||||
string WindowsSystem32Folder = System.Environment.GetFolderPath(Environment.SpecialFolder.System);
|
||||
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo((WindowsSystem32Folder + "\\" + "CMD.exe"), strCmdLine);
|
||||
//startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
|
||||
startInfo.CreateNoWindow = true;
|
||||
startInfo.UseShellExecute = false;
|
||||
startInfo.WorkingDirectory = Path.GetDirectoryName(FileNameNPath);
|
||||
if (bUseRunAs)
|
||||
startInfo.Verb = "runas";
|
||||
|
||||
// Start the Cmd.exe Process
|
||||
System.Diagnostics.Process p1;
|
||||
p1 = System.Diagnostics.Process.Start(startInfo);
|
||||
if(bWait)
|
||||
p1.WaitForExit();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
36
Other/DelegateCollection.cs
Normal file
36
Other/DelegateCollection.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Windows;
|
||||
|
||||
namespace Yaulw.Other
|
||||
{
|
||||
/// <remarks>
|
||||
/// Common Delegates * Useful for Dispatching *
|
||||
/// </remarks>
|
||||
public static class DelegateCollection
|
||||
{
|
||||
// 0 Params Functions
|
||||
public delegate void Void_Func();
|
||||
public delegate bool Bool_Func();
|
||||
public delegate int Int_Func();
|
||||
public delegate object Obj_Func();
|
||||
public delegate DateTime DateTime_Func();
|
||||
|
||||
// Void Ret - 1 Params Functions
|
||||
public delegate void Void_Param1_String_Func(string str1);
|
||||
public delegate void Void_Param1_Int_Func(int int1);
|
||||
public delegate void Void_Param1_DateTime_Func(DateTime dt1);
|
||||
public delegate void Void_Param1_Exception_Func(Exception ex1);
|
||||
|
||||
// Bool Ret - 1 Params Functions
|
||||
public delegate bool Bool_Param1_String_Func(string str1);
|
||||
public delegate bool Bool_Param1_Window_Func(Window window);
|
||||
|
||||
// String Ret - 1 Params Functions
|
||||
public delegate string String_Param1_Bool_Func(bool bool1);
|
||||
public delegate string String_Param1_String_Func(string str1);
|
||||
|
||||
}
|
||||
}
|
||||
43
Other/Installer.cs
Normal file
43
Other/Installer.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.IO;
|
||||
using Yaulw.Process;
|
||||
|
||||
namespace Yaulw.Other
|
||||
{
|
||||
public static class Installer
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Run a command on the commandline * Hidden *
|
||||
/// </summary>
|
||||
/// <param name="cmdline">cmd to run</param>
|
||||
public static string RunCmdLine(string cmdline)
|
||||
{
|
||||
string result = PStarter.RunDosCommand(cmdline);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// To grant the specified User or group Full Control permissions to the folder and its contents
|
||||
/// </summary>
|
||||
/// <param name="FolderNPath">full path to folder/directory</param>
|
||||
/// <param name="UserOrGroup">domainname\administrator, any windows user or group</param>
|
||||
/// <returns></returns>
|
||||
public static bool GrantFullPermissionToFolderForUserOrGroup(string FolderNPath, string UserOrGroup)
|
||||
{
|
||||
if (Directory.Exists(FolderNPath))
|
||||
{
|
||||
string command = String.Format("cacls \"{0}\" /t /e /g {1}:f", FolderNPath, UserOrGroup);
|
||||
string strResult = RunCmdLine(command);
|
||||
if (strResult.Contains("Invalid arguments."))
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
116
Other/OSInfo.cs
Normal file
116
Other/OSInfo.cs
Normal file
@@ -0,0 +1,116 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Yaulw.Win32;
|
||||
|
||||
namespace Yaulw.Other
|
||||
{
|
||||
#region OSInfo Enums
|
||||
|
||||
/// <summary>
|
||||
/// Windows OS Types
|
||||
/// </summary>
|
||||
public enum OStype
|
||||
{
|
||||
WIN_2000 = 4,
|
||||
WIN_2003 = 5,
|
||||
WIN_VISTA = 6,
|
||||
WIN_7 = 7,
|
||||
WIN_8 = 8,
|
||||
WIN_UNKNOWN = -1,
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <remarks>
|
||||
/// This class provides OS Specific and Version information to the caller
|
||||
/// </remarks>
|
||||
public static class OSInfo
|
||||
{
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// Get OSType and Version Information
|
||||
/// </summary>
|
||||
public static int Major { get; private set; }
|
||||
public static int Minor { get; private set; }
|
||||
public static OStype OS { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Set Supported Version for an Application
|
||||
/// </summary>
|
||||
public static OStype MinVersionSupported { get; set; }
|
||||
public static OStype MaxVersionSupported { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Is this OS Version Supported * Min/Max Should be set by Application *
|
||||
/// </summary>
|
||||
public static bool IsSupportedOS
|
||||
{
|
||||
get
|
||||
{
|
||||
if (MinVersionSupported != OStype.WIN_UNKNOWN && MaxVersionSupported != OStype.WIN_UNKNOWN)
|
||||
return ((int) OS >= (int)MinVersionSupported) && ((int) OS <= (int)MaxVersionSupported);
|
||||
else
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Is Vista/Win7's Aero Enabled
|
||||
/// </summary>
|
||||
public static bool IsAero
|
||||
{
|
||||
get
|
||||
{
|
||||
if (((int)OS >= (int)OStype.WIN_VISTA) || ((int)OS <= (int)OStype.WIN_7))
|
||||
{
|
||||
bool IsAero = false;
|
||||
if (uxDwm.DwmIsCompositionEnabled(ref IsAero) < 0)
|
||||
return false;
|
||||
else
|
||||
return IsAero;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Is WindowsXP/2003 Composition Enabled
|
||||
/// </summary>
|
||||
public static bool IsXPComposition
|
||||
{
|
||||
get
|
||||
{
|
||||
if ((int)OS == (int)OStype.WIN_2003)
|
||||
return uxDwm.IsAppThemed();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Construction
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
static OSInfo()
|
||||
{
|
||||
// Get the OS Version
|
||||
Major = System.Environment.OSVersion.Version.Major;
|
||||
Minor = System.Environment.OSVersion.Version.Minor;
|
||||
|
||||
// Parse the OS Version
|
||||
try { OSInfo.OS = (OStype)Enum.Parse(typeof(OStype), Major.ToString()); }
|
||||
catch (Exception) { OSInfo.OS = OStype.WIN_UNKNOWN; }
|
||||
|
||||
// Set Min/Max to Unknown
|
||||
MinVersionSupported = OStype.WIN_UNKNOWN;
|
||||
MaxVersionSupported = OStype.WIN_UNKNOWN;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
57
Other/StackWalker.cs
Normal file
57
Other/StackWalker.cs
Normal file
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Yaulw.Other
|
||||
{
|
||||
/// <remarks>
|
||||
/// Use the StackWalker to Find out what Method/Type Called you.
|
||||
/// This is useful for logging functions to know what method/type called the Logging Method.
|
||||
/// </remarksy>
|
||||
public static class StackWalker
|
||||
{
|
||||
/// <summary>
|
||||
/// Hard-Coded in Stack Frame count depending on how this Class is getting called,
|
||||
/// and how many frames we have to go up / down (use nPlusMinus)
|
||||
/// </summary>
|
||||
public const int DEFAULT_STACK_FRAME_COUNT = 3;
|
||||
|
||||
/// <summary>
|
||||
/// Use this to get the MethodName from the CallStack.
|
||||
/// This allows the calling method to know which method called it
|
||||
/// </summary>
|
||||
/// <param name="nPlusMinus">Use this to add/substract from the base stack level you want to retrieve</param>
|
||||
/// <returns>Returns the MethodName as specified by the CallStack</returns>
|
||||
public static string GetMethodNameFromStack(int nPlusMinus = 0)
|
||||
{
|
||||
StackTrace stackTrace = new StackTrace();
|
||||
StackFrame stackFrame;
|
||||
MethodBase stackFrameMethod;
|
||||
|
||||
stackFrame = stackTrace.GetFrame(DEFAULT_STACK_FRAME_COUNT + nPlusMinus);
|
||||
stackFrameMethod = stackFrame.GetMethod();
|
||||
return stackFrameMethod.Name;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use this to get the Type from the CallStack.
|
||||
/// This allows the calling method to know which type called it.
|
||||
/// </summary>
|
||||
/// <param name="nPlusMinus">Use this to add/substract from the base stack level you want to retrieve</param>
|
||||
/// <returns>Returns the Type as specified by the CallStack</returns>
|
||||
public static Type GetTypeFromStack(int nPlusMinus = 0)
|
||||
{
|
||||
StackTrace stackTrace = new StackTrace();
|
||||
StackFrame stackFrame;
|
||||
MethodBase stackFrameMethod;
|
||||
|
||||
stackFrame = stackTrace.GetFrame(DEFAULT_STACK_FRAME_COUNT + nPlusMinus);
|
||||
stackFrameMethod = stackFrame.GetMethod();
|
||||
return stackFrameMethod.ReflectedType;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
255
Other/StateM.cs
Normal file
255
Other/StateM.cs
Normal file
@@ -0,0 +1,255 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Collections.Specialized;
|
||||
using Yaulw.Tools;
|
||||
|
||||
namespace Yaulw.Other
|
||||
{
|
||||
/// <remarks>
|
||||
/// Easy StateManager to store and retrieve various Application States using an Enum
|
||||
/// <example>
|
||||
/// <code>
|
||||
/// internal enum State
|
||||
/// {
|
||||
/// App_Started_bool,
|
||||
/// App_ErrorsOccured_bool,
|
||||
/// SpecialMode_CommandLine_Mode_bool,
|
||||
/// }
|
||||
///
|
||||
/// internal static StateM AppState = new StateM(typeof(State));
|
||||
/// </code>
|
||||
/// </example>
|
||||
/// </remarks>
|
||||
public class StateM : IDisposable
|
||||
{
|
||||
#region Private Members
|
||||
|
||||
// Private Parsing Enums
|
||||
private Type _StateKeys = null;
|
||||
private StringDictionary _sdCurrentState = new StringDictionary(); // For State String Convertible Types
|
||||
private Dictionary<String, Object> _sdCurrentStateObj = new Dictionary<string, object>(); // For State Object Types
|
||||
private bool _disposed = false;
|
||||
private object _lock = new object();
|
||||
|
||||
#endregion
|
||||
|
||||
#region Construction
|
||||
|
||||
/// <summary>
|
||||
/// The StateM needs to know what Keys to Get/Set
|
||||
/// </summary>
|
||||
/// <param name="Enum_StateKeys">Pass an Enum used to determine StateKeys</param>
|
||||
public StateM(Type Enum_StateKeys)
|
||||
{
|
||||
if (Enum_StateKeys.IsEnum)
|
||||
{
|
||||
_StateKeys = Enum_StateKeys;
|
||||
}
|
||||
else
|
||||
throw new ArgumentException("StateKeys must be an Enum");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finalizer
|
||||
/// </summary>
|
||||
~StateM()
|
||||
{
|
||||
Dispose(true);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// True if User Has passed in State Values
|
||||
/// </summary>
|
||||
public bool HasStates { get { return (_sdCurrentState.Count >= 1 || _sdCurrentStateObj.Count >= 1); } }
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Main Entry Function to Retrieve an State Value
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Should be a System Type like string, bool, int32, double, decimal, etc...</typeparam>
|
||||
/// <param name="stateKey">State Value you want to retrieve</param>
|
||||
/// <param name="DefaultValue">Default value to use if nothing was retrieved * Error occured *</param>
|
||||
/// <returns>value or default value, if not found</returns>
|
||||
public T GetStateValue<T>(Enum stateKey, T DefaultValue)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
T RetVal = DefaultValue;
|
||||
if (ObjTool.IsOfTypeConvertibleToString<T>(DefaultValue))
|
||||
{
|
||||
string Value = String.Empty;
|
||||
if (GetStateValue(stateKey, out Value) && !String.IsNullOrEmpty(Value))
|
||||
RetVal = ObjTool.ConvertStringToObj<T>(Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
object o = null;
|
||||
if (GetStateValue(stateKey, out o) && (o != null))
|
||||
RetVal = (T)o;
|
||||
}
|
||||
return RetVal;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Main Entry Function to Set a State Value
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Should be a System Type like string, bool, int32, double, decimal, etc...</typeparam>
|
||||
/// <param name="stateKey">State Value you want to set</param>
|
||||
/// <param name="Value">Value you want to set</param>
|
||||
/// <returns>true if successful, false otherwise</returns>
|
||||
public bool SetStateValue<T>(Enum stateKey, T Value)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
bool bSuccess = false;
|
||||
if (ObjTool.IsOfTypeConvertibleToString<T>(Value))
|
||||
{
|
||||
string strValue = ObjTool.ConvertObjToString<T>(Value);
|
||||
bSuccess = SetStateValue(stateKey, strValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
bSuccess = SetStateValue(stateKey, (object)Value);
|
||||
}
|
||||
return bSuccess;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Helper Methods
|
||||
|
||||
/// <summary>
|
||||
/// Private GetStateValue Getter Function
|
||||
/// </summary>
|
||||
/// <param name="stateKey">pass in the State to look for</param>
|
||||
/// <param name="Value">Returns the value or String.Empty, if none</param>
|
||||
/// <returns>true if the State Value Exists, false otherwise</returns>
|
||||
private bool GetStateValue(Enum stateKey, out string Value)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
Value = String.Empty;
|
||||
if (_sdCurrentState.ContainsKey(stateKey.ToString()))
|
||||
{
|
||||
Value = _sdCurrentState[stateKey.ToString()];
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Private GetStateValue Getter Function
|
||||
/// </summary>
|
||||
/// <param name="stateKey">pass in the State to look for</param>
|
||||
/// <param name="o">Returns the object or null, if noone</param>
|
||||
/// <returns>true if the State Value Exists, false otherwise</returns>
|
||||
private bool GetStateValue(Enum stateKey, out object o)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
o = null;
|
||||
if (_sdCurrentStateObj.ContainsKey(stateKey.ToString()))
|
||||
{
|
||||
o = _sdCurrentStateObj[stateKey.ToString()];
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Private SetStateValue Setter Function
|
||||
/// </summary>
|
||||
/// <param name="stateKey">pass in the State to Set</param>
|
||||
/// <param name="Value">The Value to Set</param>
|
||||
/// <returns>true if the State Value was set, false otherwise</returns>
|
||||
private bool SetStateValue(Enum stateKey, string Value)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
try
|
||||
{
|
||||
_sdCurrentState[stateKey.ToString()] = Value;
|
||||
return true;
|
||||
}
|
||||
catch (Exception) { /* ignore */ }
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Private SetStateValue Setter Function
|
||||
/// </summary>
|
||||
/// <param name="stateKey">pass in the State to Set</param>
|
||||
/// <param name="o">The Object to Set</param>
|
||||
/// <returns>true if the State Value was set, false otherwise</returns>
|
||||
private bool SetStateValue(Enum stateKey, object o)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
try
|
||||
{
|
||||
_sdCurrentStateObj[stateKey.ToString()] = o;
|
||||
return true;
|
||||
}
|
||||
catch (Exception) { /* ignore */ }
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IDisposable Members
|
||||
|
||||
/// <summary>
|
||||
/// Dispose the State Object
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
|
||||
// Use SupressFinalize in case a subclass
|
||||
// of this type implements a finalizer
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose the State Object
|
||||
/// </summary>
|
||||
/// <param name="disposing">true, if called from within</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
foreach (object o in _sdCurrentStateObj)
|
||||
{
|
||||
if (o is IDisposable)
|
||||
((IDisposable)o).Dispose();
|
||||
}
|
||||
_sdCurrentStateObj.Clear();
|
||||
}
|
||||
|
||||
// Indicate that the instance has been disposed.
|
||||
_sdCurrentState = null;
|
||||
_sdCurrentStateObj = null;
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
78
Other/TraceM.cs
Normal file
78
Other/TraceM.cs
Normal file
@@ -0,0 +1,78 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Threading = System.Threading;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Yaulw.Other
|
||||
{
|
||||
/// <remarks>
|
||||
/// Wrapper Class arround Tracing, designed to measure performance.
|
||||
/// Use this class to measure performance arround your calls.
|
||||
/// <example>
|
||||
/// TraceM.TraceBegin()
|
||||
/// ... Some Code....
|
||||
/// ... Some More Code...
|
||||
/// TraceM.TraceEnd("Custom Message");
|
||||
/// </example>
|
||||
/// </remarks>
|
||||
public static class TraceM
|
||||
{
|
||||
#region Private Statics
|
||||
|
||||
private static Dictionary<uint, Stack<DateTime>> s_ThreadTraceBeginTSMap = new Dictionary<uint, Stack<DateTime>>();
|
||||
public static bool EnableTracing { get; set; }
|
||||
|
||||
#endregion
|
||||
|
||||
#region Construction
|
||||
|
||||
/// <summary>
|
||||
/// Construction * Tracing by default is disabled *
|
||||
/// </summary>
|
||||
static TraceM()
|
||||
{
|
||||
EnableTracing = false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Statics
|
||||
|
||||
/// <summary>
|
||||
/// Call this to Start the Performance Trace
|
||||
/// </summary>
|
||||
public static void TraceBegin()
|
||||
{
|
||||
if (EnableTracing)
|
||||
{
|
||||
uint curThreadId = (uint)Threading.Thread.CurrentThread.ManagedThreadId;
|
||||
if (!s_ThreadTraceBeginTSMap.ContainsKey(curThreadId))
|
||||
s_ThreadTraceBeginTSMap[curThreadId] = new Stack<DateTime>();
|
||||
|
||||
s_ThreadTraceBeginTSMap[curThreadId].Push(DateTime.Now);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Us this to End the Performance Trace
|
||||
/// </summary>
|
||||
/// <param name="CustomMessage">Custom Message you want displayed in the Trace Window</param>
|
||||
public static void TraceEnd(string CustomMessage = "")
|
||||
{
|
||||
if (EnableTracing)
|
||||
{
|
||||
uint curThreadId = (uint)Threading.Thread.CurrentThread.ManagedThreadId;
|
||||
if (s_ThreadTraceBeginTSMap.ContainsKey(curThreadId))
|
||||
{
|
||||
DateTime orgTime = s_ThreadTraceBeginTSMap[curThreadId].Pop();
|
||||
TimeSpan ts = DateTime.Now - orgTime;
|
||||
Trace.WriteLine((CustomMessage + " (Time Taken in ms " + ts.TotalMilliseconds.ToString() + ")"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
550
Other/Versioning.cs
Normal file
550
Other/Versioning.cs
Normal file
@@ -0,0 +1,550 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Yaulw.Other
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface of Versioning, to check if the passed in version is supported by the Versioning Object
|
||||
/// </summary>
|
||||
public interface IVersionSupported
|
||||
{
|
||||
bool IsSupported(string Version);
|
||||
bool IsSupported(Versioning Version);
|
||||
bool IsSupported(Version Version);
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// Allows us to easily wrap Versioning Functionallity,
|
||||
/// into Objects. Similar to Assembly.Version Class, however,
|
||||
/// it allows the * character. This character specifies all and
|
||||
/// allows for wildchar versioning schemes useful for certain
|
||||
/// scenarios via IVersionSupported.
|
||||
/// ---------------------------------------------------
|
||||
/// [Major version].[Minor version].[Build number].[Revision number]
|
||||
/// ---------------------------------------------------
|
||||
/// Major version can be any valid uint as well as *
|
||||
/// Minor version can be any valid uint as well as *
|
||||
/// Build number can be any valid uint as well as *
|
||||
/// Revision number can be any valid uint as well as *
|
||||
/// </remarks>
|
||||
public class Versioning : ICloneable, IComparable, IVersionSupported
|
||||
{
|
||||
#region Public consts
|
||||
|
||||
/// <summary>
|
||||
/// Int value indicating a * (wildcard) character
|
||||
/// </summary>
|
||||
public const int STAR_ALL = -1;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Members
|
||||
|
||||
private int _MajorVersion = STAR_ALL;
|
||||
private int _MinorVersion = STAR_ALL;
|
||||
private int _BuildNumber = STAR_ALL;
|
||||
private int _RevisionNumber = STAR_ALL;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Construction
|
||||
|
||||
/// <summary>
|
||||
/// Use this to initialize the class with a version string, can not contain multiple versions seperated by ";"
|
||||
/// </summary>
|
||||
/// <param name="strVersion">any version string in the format [Major].[Minor].[Build].[Revision], like 5.3.3.1 or 5.4.*.*</param>
|
||||
/// <exception cref="ArgumentException">if Major,Minor,Build, or Revision < -1</exception>
|
||||
public Versioning(string strVersion)
|
||||
{
|
||||
if (!IsValidVersionStr(strVersion) || strVersion.Contains(";"))
|
||||
throw new ArgumentException("Invalid Version String");
|
||||
ParseVersion(strVersion, out this._MajorVersion, out this._MinorVersion, out this._BuildNumber, out this._RevisionNumber);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize Versioning with a single MajorVersion and MinorVersion.
|
||||
/// </summary>
|
||||
/// <param name="MajorVersion">Major Version</param>
|
||||
/// <param name="MinorVersion">Minor Version</param>
|
||||
/// <exception cref="ArgumentException">if Major,Minor,Build, or Revision < -1</exception>
|
||||
public Versioning(int MajorVersion, int MinorVersion)
|
||||
{
|
||||
if (MajorVersion >= STAR_ALL && MinorVersion >= STAR_ALL)
|
||||
{
|
||||
_MajorVersion = MajorVersion;
|
||||
_MinorVersion = MinorVersion;
|
||||
}
|
||||
else
|
||||
throw new ArgumentException("MajorVersion or MinorVersion is invalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize Versioning with a single MajorVersion,MinorVersion, and BuildNumber.
|
||||
/// </summary>
|
||||
/// <param name="MajorVersion">Major Version</param>
|
||||
/// <param name="MinorVersion">Minor Version</param>
|
||||
/// <param name="BuildNumber">Build Number</param>
|
||||
/// <exception cref="ArgumentException">if Major,Minor,Build, or Revision < -1</exception>
|
||||
public Versioning(int MajorVersion, int MinorVersion, int BuildNumber)
|
||||
{
|
||||
if (MajorVersion >= STAR_ALL && MinorVersion >= STAR_ALL && _BuildNumber >= STAR_ALL)
|
||||
{
|
||||
_MajorVersion = MajorVersion;
|
||||
_MinorVersion = MinorVersion;
|
||||
_BuildNumber = BuildNumber;
|
||||
}
|
||||
else
|
||||
throw new ArgumentException("MajorVersion,MinorVersion, or BuildNumber is invalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize Versioning with a single MajorVersion,MinorVersion,BuildNumber and RevisionNumber.
|
||||
/// </summary>
|
||||
/// <param name="MajorVersion">Major Version</param>
|
||||
/// <param name="MinorVersion">Minor Version</param>
|
||||
/// <param name="BuildNumber">Build Number</param>
|
||||
/// <param name="RevisionNumber">Revision Number</param>
|
||||
/// <exception cref="ArgumentException">if Major,Minor,Build, or Revision < -1</exception>
|
||||
public Versioning(int MajorVersion, int MinorVersion, int BuildNumber, int RevisionNumber)
|
||||
{
|
||||
if (MajorVersion >= STAR_ALL && MinorVersion >= STAR_ALL && _BuildNumber >= STAR_ALL && RevisionNumber >= STAR_ALL)
|
||||
{
|
||||
_MajorVersion = MajorVersion;
|
||||
_MinorVersion = MinorVersion;
|
||||
_BuildNumber = BuildNumber;
|
||||
_RevisionNumber = RevisionNumber;
|
||||
}
|
||||
else
|
||||
throw new ArgumentException("MajorVersion,MinorVersion, BuildNumber, or RevisionNumber is invalid");
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize Versioning with a .Net Version Object
|
||||
/// </summary>
|
||||
/// <param name="version">a .Net Version Object</param>
|
||||
public Versioning(Version version)
|
||||
{
|
||||
_MajorVersion = version.Major;
|
||||
_MinorVersion = version.Minor;
|
||||
_BuildNumber = version.Build;
|
||||
_RevisionNumber = version.Revision;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Versioning Getter/Setter
|
||||
|
||||
/// <summary>
|
||||
/// Set/Retrieve Version
|
||||
/// </summary>
|
||||
public String Version
|
||||
{
|
||||
get
|
||||
{
|
||||
return VersionToVersionString(_MajorVersion, _MinorVersion, _BuildNumber, _RevisionNumber);
|
||||
}
|
||||
set
|
||||
{
|
||||
if (IsValidVersionStr(value) && !value.Contains(";"))
|
||||
ParseVersion(value, out this._MajorVersion, out this._MinorVersion, out this._BuildNumber, out this._RevisionNumber);
|
||||
else
|
||||
throw new ArgumentException("Invalid Version String");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Static Helpers
|
||||
|
||||
/// <summary>
|
||||
/// Gets a Versioning object for the Version Information of a File
|
||||
/// </summary>
|
||||
/// <param name="FileNameNPath">Full File Name and Path</param>
|
||||
/// <returns>returns a new Versioning Object for a File, or null if error occured</returns>
|
||||
public static Versioning GetFileVersioning(string FileNameNPath)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(FileNameNPath) && System.IO.File.Exists(FileNameNPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
FileVersionInfo info = FileVersionInfo.GetVersionInfo(FileNameNPath);
|
||||
return new Versioning(info.FileMajorPart, info.FileMinorPart, info.FileBuildPart, info.FilePrivatePart);
|
||||
}
|
||||
catch (Exception) { /* ignore */ }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses out a single Version from a string
|
||||
/// </summary>
|
||||
/// <param name="strVersion">pass in a Version format [Major].[Minor].[Build], like 5.3.3 or 5.4.*</param>
|
||||
/// <param name="MajorVersion">returns an int or STAR_ALL</param>
|
||||
/// <param name="MinorVersion">returns an int or STAR_ALL</param>
|
||||
/// <param name="BuildNumber">returns an int or STAR_ALL</param>
|
||||
/// <param name="RevisionNumber">returns an int or STAR_ALL</param>
|
||||
public static void ParseVersion(string strVersion, out int MajorVersion, out int MinorVersion, out int BuildNumber, out int RevisionNumber)
|
||||
{
|
||||
if (!IsValidVersionStr(strVersion) || strVersion.Contains(";"))
|
||||
throw new ArgumentException("Invalid Version String");
|
||||
|
||||
MajorVersion = STAR_ALL;
|
||||
MinorVersion = STAR_ALL;
|
||||
BuildNumber = STAR_ALL;
|
||||
RevisionNumber = STAR_ALL;
|
||||
string[] MajorMinorPossBuildVersion = strVersion.Split('.');
|
||||
try
|
||||
{
|
||||
for (int i = 0; i < MajorMinorPossBuildVersion.Length; ++i)
|
||||
{
|
||||
if (i == 0)
|
||||
{
|
||||
if (MajorMinorPossBuildVersion[0] != "*")
|
||||
MajorVersion = int.Parse(MajorMinorPossBuildVersion[0]);
|
||||
}
|
||||
else if (i == 1)
|
||||
{
|
||||
if (MajorMinorPossBuildVersion[1] != "*")
|
||||
MinorVersion = int.Parse(MajorMinorPossBuildVersion[1]);
|
||||
}
|
||||
else if (i == 2)
|
||||
{
|
||||
if (MajorMinorPossBuildVersion[2] != "*")
|
||||
BuildNumber = int.Parse(MajorMinorPossBuildVersion[2]);
|
||||
}
|
||||
else if (i == 3)
|
||||
{
|
||||
if (MajorMinorPossBuildVersion[2] != "*")
|
||||
RevisionNumber = int.Parse(MajorMinorPossBuildVersion[3]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
catch (Exception) { /* Ignore */ }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Turns Version Numbers into a Version String
|
||||
/// </summary>
|
||||
/// <param name="MajorVersion">Major Version</param>
|
||||
/// <param name="MinorVersion">Minor Version, can be *</param>
|
||||
/// <param name="BuildNumber">Build Number, can be * or UNINITIALIZED</param>
|
||||
/// <returns>the Version String</returns>
|
||||
public static string VersionToVersionString(int MajorVersion, int MinorVersion = STAR_ALL, int BuildNumber = STAR_ALL, int RevisionNumber = STAR_ALL)
|
||||
{
|
||||
string strRetVal = String.Empty;
|
||||
if (MajorVersion >= STAR_ALL)
|
||||
{
|
||||
// Major Version
|
||||
if (MajorVersion == STAR_ALL)
|
||||
strRetVal += "*";
|
||||
else
|
||||
strRetVal += MajorVersion.ToString();
|
||||
|
||||
// Minor Version
|
||||
if (MinorVersion >= STAR_ALL)
|
||||
{
|
||||
strRetVal += ".";
|
||||
if (MinorVersion == STAR_ALL)
|
||||
strRetVal += "*";
|
||||
else
|
||||
strRetVal += MinorVersion.ToString();
|
||||
}
|
||||
|
||||
// Build Number
|
||||
if (BuildNumber >= STAR_ALL)
|
||||
{
|
||||
strRetVal += ".";
|
||||
if (BuildNumber == STAR_ALL)
|
||||
strRetVal += "*";
|
||||
else
|
||||
strRetVal += BuildNumber.ToString();
|
||||
}
|
||||
|
||||
// Revision Number
|
||||
if (RevisionNumber >= STAR_ALL)
|
||||
{
|
||||
strRetVal += ".";
|
||||
if (RevisionNumber == STAR_ALL)
|
||||
strRetVal += "*";
|
||||
else
|
||||
strRetVal += RevisionNumber.ToString();
|
||||
}
|
||||
}
|
||||
return strRetVal;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Stats - Validation
|
||||
|
||||
private const string CharSet_AllowedNumeric = "0123456789";
|
||||
private const string CharSet_AllowedVersionChars = CharSet_AllowedNumeric + "*;.";
|
||||
|
||||
/// <summary>
|
||||
/// Generic Function to use with Allowed Character Sets above
|
||||
/// </summary>
|
||||
/// <param name="TextToEvaluate">string to evaluate</param>
|
||||
/// <param name="TextToEvaluateWith">Pass in one of the legal character consts declared above</param>
|
||||
/// <returns>true if valid, false otherwise</returns>
|
||||
private static bool ContainsOnlyLegalChars(string TextToEvaluate, string TextToEvaluateWith)
|
||||
{
|
||||
foreach (char c in TextToEvaluate.ToCharArray())
|
||||
{
|
||||
bool bFound = (TextToEvaluateWith.IndexOf(c) >= 0);
|
||||
if (!bFound)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Used to Validate a Version string of format 12.1.12;12.2.*;12.2.1
|
||||
/// </summary>
|
||||
/// <param name="VersionStr">a Version String</param>
|
||||
/// <returns>true if valid, false otherwise</returns>
|
||||
public static bool IsValidVersionStr(string VersionStr)
|
||||
{
|
||||
if (String.IsNullOrEmpty(VersionStr))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else if (VersionStr.Length < 1 && VersionStr.Length > 14) // restrict Version String Length
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else if (!ContainsOnlyLegalChars(VersionStr, CharSet_AllowedVersionChars))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ICloneable Members
|
||||
|
||||
/// <summary>
|
||||
/// Clone the Object
|
||||
/// </summary>
|
||||
/// <returns>a copy of this Versioning Object</returns>
|
||||
public object Clone()
|
||||
{
|
||||
Versioning versioning = new Versioning(this._MajorVersion, this._MinorVersion, this._BuildNumber, this._RevisionNumber);
|
||||
return versioning;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IComparable Members
|
||||
|
||||
/// <summary>
|
||||
/// Compare two Versioning Objects
|
||||
/// </summary>
|
||||
/// <param name="obj">a Versioning Object</param>
|
||||
/// <returns>-1, 0, +1</returns>
|
||||
public int CompareTo(object obj)
|
||||
{
|
||||
if (obj is Versioning)
|
||||
{
|
||||
Versioning v = (Versioning)obj;
|
||||
//*.*.*
|
||||
//*.2.*
|
||||
//1.*.*
|
||||
//1.1.*
|
||||
//1.1.1
|
||||
//2.2.2
|
||||
//2.2.*
|
||||
int nCompare = 0;
|
||||
nCompare = this._MajorVersion.CompareTo(v._MajorVersion);
|
||||
if(nCompare == 0)
|
||||
nCompare = this._MinorVersion.CompareTo(v._MinorVersion);
|
||||
if(nCompare == 0)
|
||||
nCompare = this._BuildNumber.CompareTo(v._BuildNumber);
|
||||
if (nCompare == 0)
|
||||
nCompare = this._RevisionNumber.CompareTo(v._BuildNumber);
|
||||
return nCompare;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException("object is not a Versioning");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IVersionSupported Members
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the Version String passed in is supported/matches Versioning for this object
|
||||
/// </summary>
|
||||
/// <param name="Version">a Versioning string to validate against</param>
|
||||
/// <returns>true if supported, false otherwise</returns>
|
||||
public bool IsSupported(string Version)
|
||||
{
|
||||
Versioning version = new Versioning(Version);
|
||||
return IsSupported(version);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the Version passed in is supported/matches Versioning for this object
|
||||
/// </summary>
|
||||
/// <param name="Version">a Versioning Object to validate against</param>
|
||||
/// <returns>true if supported, false otherwise</returns>
|
||||
public bool IsSupported(Versioning Version)
|
||||
{
|
||||
if (Version != null)
|
||||
{
|
||||
int nCompare = this.CompareTo(Version);
|
||||
if (nCompare == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else if (nCompare == 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else if (nCompare == -1)
|
||||
{
|
||||
if (((this._MajorVersion == STAR_ALL) || (this._MajorVersion == Version._MajorVersion)) &&
|
||||
((this._MinorVersion == STAR_ALL) || (this._MinorVersion == Version._MinorVersion)) &&
|
||||
((this._BuildNumber == STAR_ALL) || (this._BuildNumber == Version._BuildNumber)) &&
|
||||
((this._RevisionNumber == STAR_ALL) || (this._RevisionNumber == Version._RevisionNumber))
|
||||
)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the Version passed in is supported/matches Versioning for this object
|
||||
/// </summary>
|
||||
/// <param name="Version">a Version Object to Validate against</param>
|
||||
/// <returns>true if supported, false otherwise</returns>
|
||||
public bool IsSupported(Version Version)
|
||||
{
|
||||
Versioning version = new Versioning(Version.Major, Version.Minor, Version.Build, Version.Revision);
|
||||
return true;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// Allows us to easily parse/sort/search multiple versioning classes
|
||||
/// </remarks>
|
||||
public static class Versionings
|
||||
{
|
||||
/// <summary>
|
||||
/// Used to parse multiple ";" seperated versions from a string
|
||||
/// </summary>
|
||||
/// <param name="strVersions">single/multiple version strings, seperated by ";", in the format [Major].[Minor].[Build].[Revision], like 5.3.3.1 or 5.4.*.*</param>
|
||||
/// <returns>a sorted array of versionings or null if error occured</returns>
|
||||
public static Versioning[] ParseVersions(string strVersions)
|
||||
{
|
||||
if (!Versioning.IsValidVersionStr(strVersions))
|
||||
return null;
|
||||
|
||||
List<Versioning> RetValueVersions = new List<Versioning>();
|
||||
string[] Versions = strVersions.Split(';');
|
||||
foreach (string Version in Versions)
|
||||
RetValueVersions.Add(new Versioning(Version));
|
||||
|
||||
RetValueVersions.Sort();
|
||||
return RetValueVersions.ToArray();
|
||||
}
|
||||
|
||||
#region IsSupportedFile
|
||||
|
||||
/// <summary>
|
||||
/// Use this to find out if a File Version is supported by the passed in Versions string
|
||||
/// </summary>
|
||||
/// <param name="strVersions">single/multiple version strings, seperated by ";", in the format [Major].[Minor].[Build], like 5.3.3 or 5.4.*</param>
|
||||
/// <param name="FileNameNPath">Full File Name and Path</param>
|
||||
/// <returns>true if the File Version is supported by the Versions string</returns>
|
||||
public static bool IsSupportedFile(string strVersions, string FileNameNPath)
|
||||
{
|
||||
return IsSupported(ParseVersions(strVersions), Versioning.GetFileVersioning(FileNameNPath));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use this to find out if a File Version is supported by the passed in Versions []
|
||||
/// </summary>
|
||||
/// <param name="Versions">single/multiple versioning objects</param>
|
||||
/// <param name="FileNameNPath">Full File Name and Path</param>
|
||||
/// <returns>true if the File Version is supported by the Versions string</returns>
|
||||
public static bool IsSupportedFile(Versioning[] Versions, string FileNameNPath)
|
||||
{
|
||||
return IsSupported(Versions, Versioning.GetFileVersioning(FileNameNPath));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IsSupported
|
||||
|
||||
/// <summary>
|
||||
/// Pass in a Versions string, and a Version to check against. Returns true, if the Version is IVersionSupported by
|
||||
/// the passed in Versions string.
|
||||
/// </summary>
|
||||
/// <param name="strVersions">single/multiple version strings, seperated by ";", in the format [Major].[Minor].[Build].[Revision], like 5.3.3 or 5.4.*</param>
|
||||
/// <param name="strVersion">any version string in the format [Major].[Minor].[Build], like 5.3.3 or 5.4.*</param>
|
||||
/// <returns>true, if a Versioning Object in the Versions returns true for IVersionSupported, false otherwise</returns>
|
||||
public static bool IsSupported(string strVersions, string strVersion)
|
||||
{
|
||||
return IsSupported(ParseVersions(strVersions), new Versioning(strVersion));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pass in a single/multipe Versions object, and a Version object to check against. Returns true, if the Version is IVersionSupported by
|
||||
/// the passed in Versions Objects.
|
||||
/// </summary>
|
||||
/// <param name="Versions">single/multiple versioning objects</param>
|
||||
/// <param name="Version">single versioning object</param>
|
||||
/// <returns>true, if a Versioning Object in the Versions returns true for IVersionSupported, false otherwise</returns>
|
||||
public static bool IsSupported(Versioning[] Versions, Versioning Version)
|
||||
{
|
||||
// Let IVersionSupported do all the work
|
||||
foreach (Versioning _version in Versions)
|
||||
{
|
||||
if (_version.IsSupported(Version))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pass in a single/multipe Versions object, and a Version object to check against. Returns true, if the Version is IVersionSupported by
|
||||
/// the passed in Versions Objects.
|
||||
/// </summary>
|
||||
/// <param name="Versions">single/multiple versioning objects</param>
|
||||
/// <param name="Version">single version object</param>
|
||||
/// <returns>true, if a Versioning Object in the Versions returns true for IVersionSupported, false otherwise</returns>
|
||||
public static bool IsSupported(Versioning[] Versions, Version Version)
|
||||
{
|
||||
// Let IVersionSupported do all the work
|
||||
foreach (Versioning _version in Versions)
|
||||
{
|
||||
if (_version.IsSupported(Version))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user