/// ======================================================================================================= public static Return BUILD_CODE(string path_to_code) { string code = File.ReadAllText(DISK.AutoAddBaseDirectory(path_to_code)); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters(); foreach (string ass in DefaultAssemblies) { parameters.ReferencedAssemblies.Add(ass); } parameters.GenerateExecutable = true; parameters.OutputAssembly = DISK.ConvertExtension(path_to_code, ".exe"); CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, code); List <CATMessage> msgs = new List <CATMessage>(); msgs.Add(new CATMessage(code, Status.INFO)); Status status = Status.PASS; foreach (CompilerError CompErr in results.Errors) { status = Status.FAIL; msgs.Add(new CATMessage("Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine, Status.FAIL)); } msgs.Add(new CATMessage(parameters.OutputAssembly, status)); return(new Return(msgs)); }
/// ======================================================================================================= public static void EDIT_RENAME_ALL_FILES_INDEXED(string folder, string new_name_prefix) { folder = DISK.AutoAddBaseDirectory(folder); if (Directory.Exists(folder)) { foreach (string file in Directory.GetFiles(folder)) { string extension = new FileInfo(file).Extension; string newfilename = folder + "\\" + new_name_prefix + extension; File.Move(file, DISK.AutoIncrementFilename(newfilename)); } } }
/// ======================================================================================================= public static Return AbuFolder(string from, string to, string timestamp_on) { from = DISK.AutoAddBaseDirectory(from); to = DISK.AutoAddBaseDirectory(to); DISK.CreateFolder(to); if (Directory.Exists(from)) { string newto = to + "\\" + DISK.GetDirName(from) + (Convert.ToBoolean(timestamp_on) ? Timer.TimeStamp() : ""); CopyFolderContents(from, newto); return(new Return(from + " copied to " + newto)); } return(new Return(from + " does not exist")); }
/// ======================================================================================================= private static void RunAuto(AutoReport auto_report, string auto_alias, string binary_name, out List <Control> interactive_controls) { List <Control> interactivecontrols = new List <Control>(); DataGridView autodata = Data.BlankDgv((int)CAT.AutoFields.NumberOfColumns); DataGridView batchdata = Data.BlankDgv((int)CAT.BatchFields.NumberOfColumns); string binary_path = DISK.AutoAddBaseDirectory(auto_alias + @"\" + binary_name); Data.LoadDataGrid(binary_path, ref autodata); FormAccess(FormDelegates.LoadAutoData, null, auto_alias); FormAccess(FormDelegates.ClearAutoStatuses, new object[] { }, auto_alias); foreach (DataGridViewRow autorow in autodata.Rows) { if (autorow.Index < autodata.RowCount - 1) { if (!AbortAll) { Data.LoadDataGrid(new FileInfo(binary_path).Directory.FullName + @"\batch" + autorow.Index + ".bin", ref batchdata); Action runbatch = new Action(() => { List <Control> ctrls; RunBatch(auto_report, auto_alias, autorow.Index, autodata, batchdata, out ctrls); if (ctrls != null) { foreach (Control ctrl in ctrls) { interactivecontrols.Add(ctrl); } } }); if (Regex.IsMatch(Data.GetCell(autodata, (int)CAT.AutoFields.Mode, autorow.Index), "-t")) { Task t = new Task(() => { runbatch(); }); AutoTasks.Add(t); t.Start(); } else { runbatch(); } } else { FormAccess(FormDelegates.SetBatchStatus, new object[] { Status.ABORT, autorow.Index }, auto_alias); } } } CAT.FormAccess(CAT.FormDelegates.SaveAuto, new object[] { }, auto_alias); interactive_controls = interactivecontrols; }
/// ======================================================================================================= public static Return AbuFile(string from, string to, string timestamp_on) { from = DISK.AutoAddBaseDirectory(from); to = DISK.AutoAddBaseDirectory(to); if (File.Exists(from)) { DISK.CreateFolder(to); string path = Path.GetFileNameWithoutExtension(from); path += (Convert.ToBoolean(timestamp_on) ? Timer.TimeStamp() : ""); path += Path.GetExtension(from); path = to + path; File.Copy(from, path, true); return(new Return(from + " copied to " + path)); } return(new Return(from + " does not exist")); }
// Only document uppercase static functions and uppercase constants /// ======================================================================================================= public static string Features(string path) { string alltext = ""; path = DISK.AutoAddBaseDirectory(DISK.AutoAddExt(path, "dll")); Assembly assembly = Assembly.LoadFile(path); Type[] ts = assembly.GetTypes(); foreach (Type t in ts) { if (!Regex.IsMatch(t.Name, "<>") && t.Name != "RunType" && t.Name.ToUpper() == t.Name) { var inst = Activator.CreateInstance(t); alltext += t.Namespace + "." + t.Name; try { alltext += ": " + t.GetField("Description").GetValue(inst); } catch { } alltext += "\r\n"; foreach (FieldInfo f in t.GetFields()) { if (f.IsLiteral && f.Name.ToUpper() == f.Name) { alltext += "const " + f.Name + ": " + f.GetValue(f); alltext += "\r\n"; } } foreach (MethodInfo m in t.GetMethods()) { if (m.IsStatic && m.Name.ToUpper() == m.Name) { alltext += "* " + m.Name + "("; foreach (ParameterInfo pi in m.GetParameters()) { alltext += pi.Name + ","; } alltext = alltext.Substring(alltext.Length - 1) == "," ? alltext.Remove(alltext.Length - 1, 1) : alltext; alltext += ")"; alltext += "\r\n"; } } } } return(alltext); }
/// ======================================================================================================= public void AutoComplete() { EndTime = DateTime.Now; if (BatchReports.Count > 0) { string reportfolder = DISK.AutoAddBaseDirectory(Alias) + @"\Reports\"; DISK.CreateFolder(reportfolder); string reportpath = reportfolder + "AutoReport.bin"; string timestampedreportpath = reportfolder + "AutoReport" + Timer.TimeStamp() + ".bin"; Save(reportpath); Save(timestampedreportpath); CAT.FormAccess(CAT.FormDelegates.UpdateNamedOverlay, new object[] { Alias, Alias + " complete (" + AutoDuration() + ")", CalculatedAutoResult() }, Alias); } else { CAT.FormAccess(CAT.FormDelegates.UpdateNamedOverlay, new object[] { Alias, "No report for" + Alias, CAT.Status.ABORT }, Alias); Enabled = false; } }
/// ======================================================================================================= public static bool Run(string auto_alias, string binary_name, string number = null, bool new_form = false) { int commandnumber = Convert.ToInt32(number); int batchnumber = 0; // Default AutoReport autoreport = new AutoReport(auto_alias); // Always something to report autoreport.Enabled = (bool)FormAccess(FormDelegates.ReportEnabled, null, auto_alias); List <Control> interactivecontrols = new List <Control>(); if (!Running) // Not allowed to run while running { string autovars = (string)FormAccess(FormDelegates.GetAutoVars, null, auto_alias); if (!autovars.Contains(COMMAND_MODE_DIRTY_RUN)) { CleanRun(auto_alias); } AutoTasks = new List <Task>(); BatchTasks = new List <Task>(); CommandTasks = new List <Task>(); Running = true; RunMode = RunType.Command; string binary_path = DISK.AutoAddBaseDirectory(auto_alias + @"\" + binary_name); DataGridView batchdata = Data.BlankDgv((int)CAT.BatchFields.NumberOfColumns); DataGridView autodata = Data.BlankDgv((int)CAT.AutoFields.NumberOfColumns); if (File.Exists(binary_path)) { if (Regex.IsMatch(binary_path, "auto.bin")) { Data.LoadDataGrid(binary_path, ref autodata); RunMode = number == null ? RunType.Auto : RunType.Batch; if (RunMode == RunType.Batch) { Data.LoadDataGrid(new FileInfo(binary_path).Directory.FullName + @"\batch" + number + ".bin", ref batchdata); } } else if (Regex.IsMatch(binary_path, @"batch\d*.bin")) { Data.LoadDataGrid(new FileInfo(binary_path).Directory.FullName + @"\auto.bin", ref autodata); RunMode = number == null ? RunType.Batch : RunType.Command; Data.LoadDataGrid(binary_path, ref batchdata); string subvalue = Regex.Match(binary_path, @"batch\d*.bin").Value; string newvalue = Regex.Match(subvalue, @"[0-9]+").Value; batchnumber = Convert.ToInt32(newvalue); } else { Running = false; throw new Exception("Binary " + binary_path + " is invalid - thus did not start automation"); } } else { Running = false; throw new Exception("Binary " + binary_path + " does not exist - thus did not start automation"); } switch (RunMode) { case RunType.Command: if (Regex.IsMatch(Data.GetCell(batchdata, (int)CAT.BatchFields.Mode, commandnumber), "-nr")) { autoreport.Enabled = false; } autoreport.AddBatch(new BatchReport(batchnumber, Data.GetCell(autodata, (int)CAT.AutoFields.Name, batchnumber))); RunCommand(autoreport, new Map(auto_alias, batchnumber, commandnumber), batchdata, out interactivecontrols, GetAutoVars(autodata, batchnumber, auto_alias)); autoreport.WaitForBatch(batchnumber); Running = false; break; case RunType.Batch: if (Regex.IsMatch(Data.GetCell(autodata, (int)CAT.AutoFields.Mode, batchnumber), "-nr")) { autoreport.Enabled = false; } RunBatch(autoreport, auto_alias, batchnumber, autodata, batchdata, out interactivecontrols); Running = false; break; case RunType.Auto: RunAuto(autoreport, auto_alias, binary_name, out interactivecontrols); Running = false; break; } autoreport.WaitForAuto(); if (autoreport.Enabled) { ShowReport(autoreport); } if (interactivecontrols != null && interactivecontrols.Count > 0) { InteractiveShowControls(interactivecontrols); } return(true); } else { autoreport.AddOverlay("Busy running automation - thus did not start new automation - please wait (or click abort then retry run)...", Status.BUSY); return(false); } }
/// ======================================================================================================= // String based command line executer. Return all the standard output text. Ignore error text, as this isn't considered important (this is not a debug application). public static Status RunCmd(AutoReport auto_report, Map map, string fileName = "cmd.exe", string path = @"C:\", string command = "", int timeout = 120, string commandPrefix = "/C", bool use_shell = false, bool redirect_std_out = true, bool redirect_std_in = false, bool redirect_std_err = false, bool nowindow = true) { DateTime starttime = DateTime.Now; if (!CAT.AbortAll) { try { if (string.IsNullOrWhiteSpace(path) && Directory.Exists(command)) { command = @"%SystemRoot%\explorer.exe " + command; auto_report.AddOverlayedMessage(map, "Applied assumption: " + command, Status.WARN); } } catch { } path = DISK.AutoAddBaseDirectory(path); if (!Directory.Exists(path)) { if (auto_report != null) { auto_report.AddOverlayedMessage(map, "Path '" + path + "' is invalid", Status.FAIL); } } Process process = new Process(); try { ProcessStartInfo processinfo = new ProcessStartInfo() { CreateNoWindow = nowindow, UseShellExecute = use_shell, RedirectStandardOutput = redirect_std_out, RedirectStandardError = redirect_std_err, RedirectStandardInput = redirect_std_in, WorkingDirectory = path, WindowStyle = ProcessWindowStyle.Normal, FileName = fileName, Arguments = commandPrefix + command }; string alias = path + ">" + command; process.StartInfo = processinfo; process.Start(); string standardoutputtext = ""; string overlayname = "standardOutput" + map.A + map.B + map.C; if (auto_report != null) { auto_report.AddOverlay(overlayname, "", Status.INFO); } while (!process.StandardOutput.EndOfStream) { string line = process.StandardOutput.ReadLine(); standardoutputtext += line + "\r\n"; if (auto_report != null) { auto_report.UpdateOverlay(overlayname, standardoutputtext, Status.INFO); auto_report.UpdateCommandProgress(map); } if (CAT.AbortAll || CAT.AbortCurrent) { CAT.AbortCurrent = false; process.Close(); if (auto_report != null) { auto_report.AddOverlayedMessage(map, "User aborted after " + (DateTime.Now - starttime).TotalSeconds + "s", Status.ABORT); } return(Status.ABORT); } Thread.Sleep(10); if ((DateTime.Now - starttime).TotalMilliseconds > (timeout * 1000)) { process.Close(); if (auto_report != null) { auto_report.AddOverlayedMessage(map, "Timeout occured (timeout = " + timeout + "s)", Status.TIMEOUT); } return(Status.TIMEOUT); } } if (auto_report != null) { auto_report.AddMessage(map, standardoutputtext, Status.INFO); } process.Close(); return(Status.PASS); } catch (Exception e) { try { process.Close(); } catch { } if (auto_report != null) { auto_report.AddOverlayedMessage(map, ErrorMsg(e), Status.FAIL); } } } else { return(Status.ABORT); } return(Status.PASS); }
// String based DLL function executer. Path-format:"name.dll" Command-format:"namespace.class functionname(parameter1,parameter2,parameter3,parameteretc)" Do not deviate from the format! Do not use special characters! /// ======================================================================================================= public static Status RunDll(Map map, string path, string command, int timeout, out List <Control> interactive_controls, AutoReport auto_report = null) { string c = command; interactive_controls = new List <Control>(); Status status = Status.PASS; foreach (string namespace_class_function in c.Split(';')) { // Get cheker Checker checker = null; try { checker = GetChecker(auto_report, map, command); } catch (Exception e) { auto_report.AddOverlayedMessage(map, e.Message, Status.ABORT); } // Check for abort if (CAT.AbortAll) { return(Status.ABORT); } // Command started auto_report.OverlayCommandStarted(map); // Check for valid function and class string functionwithparameters = namespace_class_function.Substring(Regex.Match(namespace_class_function, @"\s").Index + 1, namespace_class_function.Length - Regex.Match(namespace_class_function, @"\s").Index - 1); string namespaceclass = namespace_class_function.Substring(0, Regex.Match(namespace_class_function, @"\s").Index); if (string.IsNullOrWhiteSpace(namespaceclass)) { functionwithparameters = namespace_class_function; } // Check function if (!Regex.IsMatch(functionwithparameters, FUNC_FORMAT + PARAM_FORMAT)) { functionwithparameters += "()"; } // Auto add brackets (no parameters) // Retry function check if (!Regex.IsMatch(functionwithparameters, FUNC_FORMAT + PARAM_FORMAT)) { auto_report.AddOverlayedMessage(map, "Function '" + functionwithparameters + "' is invalid", Status.FAIL); return(Status.FAIL); } // Function Name and Parameters string functionname = ExtractFunctionName(functionwithparameters); List <string> parameterList = ExtractParameters(functionwithparameters); // Default DLL if (string.IsNullOrWhiteSpace(namespaceclass)) { Type[] types = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type t in types) { if (t.GetMethod(functionname) != null) { namespaceclass = "API." + t.Name; auto_report.AddOverlayedMessage(map, "Applied assumption (Namespace.Class): " + namespaceclass, Status.WARN); } } if (string.IsNullOrWhiteSpace(namespaceclass)) { namespaceclass = DISK.RemoveExtension(path) + "." + DISK.RemoveExtension(path); auto_report.AddOverlayedMessage(map, "Applied assumption (Namespace.Class): " + namespaceclass, Status.WARN); } } // Class if (string.IsNullOrWhiteSpace(namespaceclass)) { auto_report.AddOverlayedMessage(map, "Class '" + namespaceclass + "' is invalid", Status.FAIL); return(Status.FAIL); } // DLL Thread object returnvalue = null; path = DISK.AutoAddBaseDirectory(DISK.AutoAddExt(path, "dll")); DateTime starttime = DateTime.Now; Assembly assembly = null; try { assembly = Assembly.LoadFile(path); if (assembly == null) { throw new Exception("Assembly still null"); } } catch (Exception e) { auto_report.AddOverlayedMessage(map, "Error loading assembly " + path + ":\r\n" + ErrorMsg(e), Status.FAIL); return(Status.FAIL); } Type type = null; try { type = assembly.GetType(namespaceclass); if (type == null) { throw new Exception("Type still null"); } } catch (Exception e) { auto_report.AddOverlayedMessage(map, "Error loading type " + namespaceclass + ":\r\n" + ErrorMsg(e), Status.FAIL); return(Status.FAIL); } object instance = null; try { instance = Activator.CreateInstance(type); if (instance == null) { throw new Exception("Instance still null"); } } catch (Exception e) { auto_report.AddOverlayedMessage(map, "Error loading instance for " + type + ":\r\n" + ErrorMsg(e), Status.FAIL); return(Status.FAIL); } MethodInfo newmethod = null; try { newmethod = type.GetMethod(functionname); if (newmethod == null) { throw new Exception("Method still null"); } } catch (Exception e) { auto_report.AddOverlayedMessage(map, "Error loading method " + functionname + " for " + type + ":\r\n" + ErrorMsg(e), Status.FAIL); return(Status.FAIL); } string name = newmethod.Name; var ts = new CancellationTokenSource(); CancellationToken ct = ts.Token; bool iscomplete = false; bool exception = false; Task.Factory.StartNew(() => { try { if (newmethod.ReturnType == typeof(void)) { newmethod.Invoke(instance, parameterList.Cast <object>().ToArray()); } else { if (parameterList != null) { returnvalue = newmethod.Invoke(null, parameterList.Cast <object>().ToArray()); } else { returnvalue = newmethod.Invoke(null, null); } } } catch (Exception e) { auto_report.AddOverlayedMessage(map, ErrorMsg(e), Status.FAIL); exception = true; } iscomplete = true; }, ct); while (!iscomplete) { // Timeout if ((DateTime.Now - starttime).TotalSeconds > timeout) { ts.Cancel(); auto_report.AddOverlayedMessage(map, "Timeout occured (timeout = " + timeout + "s)", Status.TIMEOUT); return(Status.TIMEOUT); } // Abort if (CAT.AbortAll || CAT.AbortCurrent) { ts.Cancel(); CAT.AbortCurrent = false; // Reset to jump to next command Thread.Sleep(500); // Allow threads to cleanup using abort flags auto_report.AddOverlayedMessage(map, "User aborted after " + (int)((DateTime.Now - starttime).TotalMilliseconds) + "ms", Status.ABORT); return(Status.ABORT); } // CPU handling Thread.Sleep(10); // Progress Feedback auto_report.UpdateCommandProgress(map); } // RETURN VALUE if (exception) { status = Status.FAIL; } else if (returnvalue == null) { } else if (returnvalue is Control) { interactive_controls.Add(returnvalue as Control); } else if (returnvalue is List <Control> ) { foreach (Control ctrl in (returnvalue as List <Control>)) { interactive_controls.Add(ctrl); } ; } else if (!(returnvalue is Return)) { auto_report.AddOverlayedMessage(map, "This framework only supports 'Return' return type (or void)!\r\n" + returnvalue.GetType() + " is invalid", Status.FAIL); status = Status.FAIL; } else { if (((Return)returnvalue).Messages != null) { foreach (CATMessage message in ((Return)returnvalue).Messages) { auto_report.AddOverlayedMessage(map, message.Text, message.Status); if (message.Status == Status.FAIL) { status = Status.FAIL; } } // Add extra message checker messages if (checker != null && checker.CheckType == "Messages") { List <Result> messageresults = Results.Check(((Return)returnvalue).Messages, checker.CheckFunction, checker.CheckParameters); foreach (Result message in messageresults) { auto_report.AddOverlayedMessage(map, message.Message, message.Passed ? Status.PASS : Status.FAIL); } } } // Charts if (((Return)returnvalue).Charts != null) { List <ChartData> newdata = new List <ChartData>(); foreach (ChartData chart in ((Return)returnvalue).Charts) { newdata.Add(chart); } auto_report.AddChartList(map, newdata); // Add extra chart checker messages if (checker != null && checker.CheckType == "Charts") { List <Result> chartresults = Results.Check(((Return)returnvalue).Charts, checker.CheckFunction, checker.CheckParameters); foreach (Result chartmessage in chartresults) { auto_report.AddMessage(map, chartmessage.Message, chartmessage.Passed ? Status.PASS : Status.FAIL); } } } // Charts List if (((Return)returnvalue).ChartsList != null) { foreach (List <ChartData> chartlist in ((Return)returnvalue).ChartsList) { auto_report.AddChartList(map, chartlist); } } } } return(status); }