/// <summary> /// start excel (interop mode) to execute a bunch of calc /// - the excel need to be enabled to load macro ( eg. Developer tab / Macro Security / Trust access to VBA project object model ) /// - module_name is the name where it place the macros /// - input_csv_pathfilename is the pathfilename of the csv to load data from /// - output_csv_pathfilename is the pathfilename where output results are places /// /// example input_csv /// cells_to_write,INPUT,H8,I8,J8 /// cells_to_read,OUTPUT,D109,D110 /// input_data_set_follow /// 1;2;3 /// 4;5;6 /// 7;8;9 /// 1;2;3 /// /// this will compute 4 times the worksheet by setting values in INPUT sheet cells "H8,I8,J8" /// and reading back results from the OUTPUT sheet cells "D109,D110" that will be written in the `output_csv_pathfilename` /// </summary> public static void AutomaticCalc(this Application app, Workbook wb, string module_name, string input_csv_pathfilename, string output_csv_pathfilename) { Microsoft.Vbe.Interop.VBComponent module = null; // check if module already exists var module_cnt = wb.VBProject.VBComponents.Count; for (int i = 1; i <= module_cnt; ++i) { var _module = wb.VBProject.VBComponents.Item(i); if (_module.Name == module_name) { module = _module; break; } } // if not exists, create with AutomaticCalc code if (module == null) { module = wb.VBProject.VBComponents.Add(Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule); module.Name = module_name; var ass = Assembly.GetExecutingAssembly(); var vba_code = ass.GetResourceTextFile("SearchAThing.Sci.Excel.excel_interop_automatic_calc.vba"); module.CodeModule.AddFromString(vba_code); } app.Run($"{module_name}.AutomaticCalc", input_csv_pathfilename, output_csv_pathfilename); }
public static void RemoveAllModules() { Microsoft.Vbe.Interop.VBProject project = default(Microsoft.Vbe.Interop.VBProject); //UPGRADE_WARNING: Couldn't resolve default property of object Application.VBE.ActiveVBProject. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' project = AutoCADAcadApplication_definst.Application.VBE.ActiveVBProject; Interaction.MsgBox("Removing Modules"); Microsoft.Vbe.Interop.VBComponent comp = default(Microsoft.Vbe.Interop.VBComponent); foreach (comp in project.VBComponents) { //And (comp.Type = vbext_ct_ClassModule Or comp.Type = vbext_ct_StdModule) Then if (!(comp.Name == "DevTools") & Strings.Left(comp.Name, 5) != "Sheet" & comp.Name != "ThisWorkbook") { project.VBComponents.Remove(comp); } } }
private void button23_Click(object sender, EventArgs e) { return; InstanceExcel(); Microsoft.Vbe.Interop.VBE vbe; try { vbe = (Microsoft.Vbe.Interop.VBE)ExcelApp.VBE; } catch (SystemException ex) { ShowBox(ex.Message); return; } Microsoft.Vbe.Interop.VBComponent vbc = vbe.ActiveVBProject.VBComponents.Add (Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule); vbc.Name = "newModule"; vbc.CodeModule.InsertLines(1, "Sub Text()\n\t MsgBox 123\nEnd Sub"); }
public static void InsertMacroInExcel(Microsoft.Office.Interop.Excel.Application app, Microsoft.Vbe.Interop.VBComponent xlMod, Microsoft.Vbe.Interop.VBComponent xlModule) { //initialize the Excel application and make it invisible to the user. //app = new Excel.Application(); //This is a must for lengthy spreadsheets - the Excel COM library does not like it if a user clicks around in the spreadsheet while it is being created. app.UserControl = false; app.Visible = false; //Create the Excel workbook and worksheet - and give the worksheet a name. /*place the VB macro code within a string first. * Make sure that you maintain spacing levels for code that goes inside Subs. * End each line with \r\n to tell VBA to start a new line. */ string macroCode = "Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)\r\n" + "If Target.Column = 2 Then\r\n" + "fname = ThisWorkbook.Path & Application.PathSeparator\r\n" + "Link = fname & ActiveCell & \".png\" \r\n" + "On Error GoTo NoCanDo\r\n" + "ActiveWorkbook.FollowHyperlink Address:= Link, NewWindow:= True\r\n" + "Running = False\r\n" + "End If\r\n" + "Exit Sub\r\n" + "NoCanDo: MsgBox \"Cannot find or open \" & Link\r\n" + "Running = False\r\n" + "End Sub\r\n" + "Private Sub Worksheet_Change(ByVal Target As Range)\r\n" + "LastRow = Range(\"A\" & Rows.Count).End(xlUp).Row\r\n" + "lr = Sheets(\"worksheet_table\").Cells(Rows.Count, 1).End(xlUp).Row\r\n" + "If Intersect(Target, Range(\"D2:D\" & LastRow)) Is Nothing Or Target.Cells.Count > 1 Then\r\n" + "Exit Sub\r\n" + "Else\r\n" + "If Target.Offset(0, -1) = 0 And Target = 0 Then\r\n" + "Target.Offset(0, 2) = 4\r\n" + "Target.Offset(0, 1) = \"Missed threat\"\r\n" + "Columns(5).AutoFit\r\n" + "ElseIf Target.Offset(0, -1) = 0 And Target = 1 Then\r\n" + "Target.Offset(0, 2) = 2\r\n" + "Target.Offset(0, 1) = \"Ok clean\"\r\n" + "ElseIf Target.Offset(0, -1) = 1 And Target = 1 Then\r\n" + "Target.Offset(0, 2) = 1\r\n" + "Target.Offset(0, 1) = \"Ok threat\"\r\n" + "ElseIf Target.Offset(0, -1) = 1 And Target = 0 Then\r\n" + "Target.Offset(0, 2) = 3\r\n" + "Target.Offset(0, 1) = \"False alarm\"\r\n" + "End If\r\n" + "End If\r\n" + "End Sub\r\n" + "Sub Elemenr()\r\n" + " Dim DirArray As Variant\r\n" + " DirArray = Range(\"G1:G20\").Value\r\n" + " Dim arr As New Collection, a\r\n" + " Dim aFirstArray() As Variant\r\n" + " Dim i As Long\r\n" + " On Error Resume Next\r\n" + " For Each a In DirArray\r\n" + " arr.Add a, a\r\n" + " Next\r\n" + " For i = 2 To arr.Count\r\n" + " Cells(i, 11) = arr(i)\r\n" + " Next\r\n" + "End Sub\r\n"; xlMod.CodeModule.AddFromString(macroCode); }
public static void SaveNewExcelFile(Excel.Application app, Excel.Workbook workbook, Excel.Worksheet worksheet, Microsoft.Vbe.Interop.VBComponent xlMod, Microsoft.Vbe.Interop.VBComponent xlModule) { string pathToJson = @"D:\Images\"; string result = "aiReport_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsm"; FileInfo fullPath = new FileInfo(pathToJson + result); try { //save the workbook. workbook.SaveAs(fullPath, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, false, false, null, null, null); } catch (Exception) { //release all memory - stop EXCEL.exe from hanging around. if (xlMod != null) { Marshal.ReleaseComObject(xlMod); } if (xlModule != null) { Marshal.ReleaseComObject(xlModule); } if (workbook != null) { Marshal.ReleaseComObject(workbook); } if (worksheet != null) { Marshal.ReleaseComObject(worksheet); } if (app != null) { Marshal.ReleaseComObject(app); } xlMod = null; xlModule = null; workbook = null; worksheet = null; app = null; GC.Collect(); Environment.Exit(0); } workbook.Close(); app.Quit(); //release all memory - stop EXCEL.exe from hanging around. if (xlModule != null) { Marshal.ReleaseComObject(xlMod); } if (xlMod != null) { Marshal.ReleaseComObject(xlMod); } if (workbook != null) { Marshal.ReleaseComObject(workbook); } if (worksheet != null) { Marshal.ReleaseComObject(worksheet); } if (app != null) { Marshal.ReleaseComObject(app); } xlMod = null; xlModule = null; workbook = null; worksheet = null; app = null; GC.Collect(); }
public static void ExportSourceFiles(ref string destPath) { clsCRC32 CRC32 = new clsCRC32(); Microsoft.Vbe.Interop.VBComponent comp = default(Microsoft.Vbe.Interop.VBComponent); string ignoreFilePath = null; string cleanFilePath = null; string ignorePath = null; Scripting.FileSystemObject fileSystemHandler = new Scripting.FileSystemObject(); Scripting.File ignoreFile = null; Scripting.File rootFile = null; string frxName = null; string frmName = null; bool copyFRX = false; //UPGRADE_WARNING: Couldn't resolve default property of object Application.VBE.ActiveVBProject. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' project = AutoCADAcadApplication_definst.Application.VBE.ActiveVBProject; ignorePath = destPath + "ignore\\"; //Clean out the ignore folder //fileSystemHandler.DeleteFile (ignorePath & "*") //No longer needed since modVfcMain is handling this... //Loop through all of the components and export to the ignore folder // For Each comp In project.VBComponents // If Left(comp.Name, 5) <> "Sheet" And comp.Name <> "ThisWorkbook" And comp.Name <> "DevTools" And comp.Name <> "ThisDrawing" Then // 'cleanFilePath = destPath & comp.Name & ToFileExtension(comp.Type) // ignoreFilePath = ignorePath & comp.Name & ToFileExtension(comp.Type) // comp.Export ignoreFilePath // End If // Next //Loop through root directory and find files with no match in ignore folder foreach (Scripting.File rootFile_loopVariable in fileSystemHandler.GetFolder(destPath).Files) { rootFile = rootFile_loopVariable; //Check that this file is a type handled by VBA if (Strings.InStr(VBAFileTypes, GetFileExtension(ref rootFile.Name, ref true) + ",") > 0) { ignoreFilePath = ignorePath + rootFile.Name; //If file doesn't exist in the ignore folder, then go ahead and delete it... most likely removed from VBProject if (!fileSystemHandler.FileExists(ignoreFilePath)) { rootFile.Delete(); } } } //Loop through all of the files in the ignore directory and perform a CRC compare. Copy to root if CRC doesn't match //Make sure to ignore .FRX foreach (Scripting.File ignoreFile_loopVariable in fileSystemHandler.GetFolder(ignorePath).Files) { ignoreFile = ignoreFile_loopVariable; copyFRX = false; if (Strings.InStr(VBAMoveTypes, GetFileExtension(ref ignoreFile.Name, ref true) + ",") > 0) { //Check that file exists in root, otherwise it should be copied by default //UPGRADE_WARNING: Dir has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"' if (!string.IsNullOrEmpty(FileSystem.Dir(destPath + ignoreFile.Name))) { //Move the file if the CRC32 doesn't match.. otherwise delete it if (Conversion.Hex(CRC32.CalcCRC32(ref ignorePath + ignoreFile.Name)) != Conversion.Hex(CRC32.CalcCRC32(ref destPath + ignoreFile.Name))) { ignoreFile.Copy(destPath + ignoreFile.Name, true); //Also copy the matching FRM and FRX files if a form comparison file is found with a non-matching CRC32 if (GetFileExtension(ref ignoreFile.Name, ref true) == "FRMCMP") { copyFRX = true; } } } else { //Copy from ignore to root since file doesn't exist ignoreFile.Copy(destPath, true); //Also copy the match FRX file if copying a form if (GetFileExtension(ref ignoreFile.Name, ref true) == "FRMCMP") { copyFRX = true; } } //ignoreFile.Delete } if (copyFRX & GetFileExtension(ref ignoreFile.Name, ref true) == "FRMCMP") { frxName = Strings.Left(ignoreFile.Name, Strings.Len(ignoreFile.Name) - 6) + "frx"; frmName = Strings.Left(ignoreFile.Name, Strings.Len(ignoreFile.Name) - 6) + "frm"; fileSystemHandler.CopyFile(ignorePath + frxName, destPath + frxName, true); fileSystemHandler.CopyFile(ignorePath + frmName, destPath + frmName, true); //fileSystemHandler.DeleteFile (ignorePath & frxName) //fileSystemHandler.DeleteFile (ignorePath & frmName) } } if (My.MyProject.Forms.frmVfcMain.cbDeleteIgnoreFiles.CheckState) { fileSystemHandler.DeleteFile(destPath + "ignore\\*"); } }
static void Main() { bool exit = false; while (exit == false) { Console.Clear(); Console.WriteLine("\n===== y emu hard? =====\n"); Console.Write("\t[1] cmd.exe /c (T1059.003)\n\t[2] powershell - c (T1059.001)\n\t[3] Unmanaged PowerShell aka PS w/o PowerShell.exe (T1059.001)\n\t[4] CreateProcess() API (T1106)\n\t[5] WinExec() API (T1106)\n\t[6] ShellExecute (T1106)\n\t[7] Windows Management Instrumentation (T1047)\n\t[8] VBScript (T1059.005)\n\t[9] Windows Fiber (research-based)\n\t[10] WMIC XSL Script/Squiblytwo (T1220)\n\t[11] Microsoft Word VBA Macro (T1059.005)\n\t[12] Python (T1059.006)\n\nSelect an execution procedure (or exit): "); string exec = Console.ReadLine().ToLower(); switch (exec) { case "1": bool cmd = true; while (cmd) { Console.Clear(); Console.WriteLine("\n===== cmd.exe /c execution =====\n"); Console.Write("cmd.exe /c [magic]? <<< please provide magic (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"So the pie isn't perfect? Cut it into wedges. Stay in control, and never panic.\" --Martha Stewart ====="); Thread.Sleep(3000); cmd = false; }//end if else { Console.Write("\nAre you sure you want to execute:\n\tcmd.exe /c " + command + "\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing cmd.exe /c " + command + "\n"); cliExec("cmd", command); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== No one likes a quiter... ====="); Thread.Sleep(3000); cmd = false; break; default: Console.WriteLine("\nMight want to rethink that last one..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "2": bool ps = true; while (ps) { Console.Clear(); Console.WriteLine("\n===== powershell.exe -c execution =====\n"); Console.Write("powershell.exe -c [sauce]? <<< please provide sauce (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"People say nothing is impossible, but I do nothing every day.\" --Winnie the Pooh ====="); Thread.Sleep(3000); ps = false; }//end if else { Console.Write("\nAre you sure you want to execute:\n\tpowershell.exe -c " + command + "\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing powershell.exe -c " + command + "\n"); cliExec("powershell", command); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== There is no try, only quit... ====="); Thread.Sleep(3000); ps = false; break; default: Console.WriteLine("\nDon't be weird..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "3": bool noPs = true; while (noPs) { Console.Clear(); Console.WriteLine("\n===== Unmanaged PowerShell execution =====\n"); Console.Write("\"powershell.exe -c\" [oomph]? <<< but not really,\n\twarning: commands that include CLIs with no args such as just \"cmd\" or \"powershell\" may hang\n\tplease provice oomph (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"They say stay in the lines, but there's always something better on the other side.\" --John Mayer ====="); Thread.Sleep(3000); noPs = false; }//end if else { Console.Write("\nAre you sure you want to execute \"" + command + "\" using Unmanaged PowerShell\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Process currentProcess = Process.GetCurrentProcess(); Console.WriteLine("Executing \"" + command + "\" using Unmanaged PowerShell\n"); //thank you https://github.com/Ben0xA/AwesomerShell Runspace rs = RunspaceFactory.CreateRunspace(); rs.Open(); PowerShell power = PowerShell.Create(); power.Runspace = rs; power.AddScript(command); Collection<PSObject> output = power.Invoke(); Console.WriteLine("PS \"" + command + "\"" + " executed within " + currentProcess.Id + " at " + DateTime.Now.ToString("HH:mm:ss tt") + "\n"); Console.WriteLine("\n==== Output/Error(s) =====\n"); if (output != null) { foreach (PSObject rtnItem in output) { Console.WriteLine(rtnItem.ToString()); }//end foreach }//end if trackANDkill((int) currentProcess.Id); rs.Close(); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== Quiting is not giving up... ====="); Thread.Sleep(3000); noPs = false; break; default: Console.WriteLine("\nThat's a paddlin..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "4": bool cp = true; while (cp) { Console.Clear(); Console.WriteLine("\n===== CreateProcess() API execution =====\n"); Console.Write("API needs an application with full path and args (ex: C:\\Windows\\System32\\cmd.exe /c calc)\n\tplease oblige (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"There's no such thing as perfect...Even with your imperfections, you can do anything.\" --Bathtub Barracuda ====="); Thread.Sleep(3000); cp = false; }//end if else { string[] full = command.Split(' '); string app = ""; string param = ""; int count = 0; foreach (string i in full) { if (count == 0) app = i; else if (count == 1) param = i; else param += " " + i; count++; }//end foreach Console.Write("\nAre you sure you want to execute:\n\t" + app + " with parameters \"" + param + "\" using CreateProcess()\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); STARTUPINFO si = new STARTUPINFO(); PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); Console.WriteLine("Executing " + app + " with params \"" + param + "\" using CreateProcess()\n"); CreateProcess(app, param, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref si, out pi); Console.WriteLine(app + " started as PID " + pi.dwProcessId + " at " + DateTime.Now.ToString("HH:mm:ss tt") + "\n"); Console.WriteLine("\n==== Output/Error(s) =====\n"); try { trackANDkill((int) pi.dwProcessId); }//end try catch { Console.WriteLine("\t Process died too fast to fully index"); }//end catch Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== Jimmy Buffett would be so disappointed... ====="); Thread.Sleep(3000); cp = false; break; default: Console.WriteLine("\nY tho..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "5": bool winexec = true; while (winexec) { Console.Clear(); Console.WriteLine("\n===== WinExec() API execution =====\n"); Console.Write("API takes ANY command (exe + parameters), please give us direction/meaning/purpose (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"He who has a why to live can bear almost any how.\" --Friedrich Nietzsche ====="); Thread.Sleep(3000); winexec = false; }//end if else { Console.Write("\nAre you sure you want to execute " + command + " using WinExec()\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Process currentProcess = Process.GetCurrentProcess(); Console.WriteLine("Executing " + command + " using WinExec() at " + DateTime.Now.ToString("HH:mm:ss tt") + "\n"); Console.WriteLine("\n==== Output/Error(s) =====\n"); WinExec(command, 1); Thread.Sleep(2000); Console.WriteLine(); trackANDkill((int) currentProcess.Id); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== At least you're not too legit... ====="); Thread.Sleep(3000); winexec = false; break; default: Console.WriteLine("\nNow that's just rude..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "6": bool se = true; while (se) { Console.Clear(); Console.WriteLine("\n===== ShellExecute execution =====\n"); Console.Write("ShellExecute needs an application (an exe somewhere) and args\n\tplease oblige (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"They misunderestimated me.\" --George W. Bush ====="); Thread.Sleep(3000); se = false; }//end if else { string[] full = command.Split(' '); string app = ""; string param = ""; int count = 0; foreach (string i in full) { if (count == 0) app = i; else if (count == 1) param = i; else param += " " + i; count++; }//end foreach Console.Write("\nAre you sure you want to execute " + app + " with params \"" + param + "\" using ShellExecute\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Process process = new Process(); Console.WriteLine("Executing " + app + " with params \"" + param + "\" using ShellExecute\n"); process.StartInfo.FileName = app; process.StartInfo.Arguments = param; process.StartInfo.RedirectStandardOutput = false; process.StartInfo.RedirectStandardError = false; process.StartInfo.UseShellExecute = true; process.Start(); Console.WriteLine(process.ProcessName + " started at " + process.StartTime + " as PID " + process.Id); trackANDkill((int) process.Id); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== Boo... ====="); Thread.Sleep(3000); se = false; break; default: Console.WriteLine("\nI thought we were friends..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "7": bool wmi = true; while (wmi) { Console.Clear(); Console.WriteLine("\n===== WMI execution =====\n"); Console.Write("WMI needs an application (an exe somewhere) and args\n\tplease oblige (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"I'm not Mother Teresa, but I'm not Charles Manson, either.\" --Iron Mike Tyson ====="); Thread.Sleep(3000); wmi = false; }//end if else { Console.Write("\nAre you sure you want to execute " + command + " using WMI\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing " + command + " using WMI\n"); //thank you https://github.com/GhostPack/SharpWMI ManagementScope scope = new ManagementScope("root\\cimv2"); var wmiProcess = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); ManagementBaseObject inParams = wmiProcess.GetMethodParameters("Create"); System.Management.PropertyDataCollection properties = inParams.Properties; inParams["CommandLine"] = command; ManagementBaseObject outParams = wmiProcess.InvokeMethod("Create", inParams, null); Console.WriteLine(command + " executed at " + DateTime.Now.ToString("HH:mm:ss tt") + " as PID " + outParams["processId"]); Console.WriteLine("\n==== Output/Error(s) =====\n"); Console.WriteLine(outParams["returnValue"]); UInt32 pid = (UInt32) outParams["processId"]; trackANDkill((int) pid); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== Acronymns right... ====="); Thread.Sleep(3000); ps = false; break; default: Console.WriteLine("\nMaybe try that again, but better..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "8": bool wscript = true; while (wscript) { Console.Clear(); Console.WriteLine("\n===== VBScript execution =====\n"); Console.Write("I'll build a vbs file for you (you're welcome),\n\tbut I WILL NOT sanitize input (so play nice unless you know what you're doing)\n\tI need a full command and args (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"Automation may be a good thing, but don’t forget that it began with Frankenstein.\" --Anonymous ====="); Thread.Sleep(3000); wscript = false; }//end if else { Console.Write("\nAre you sure you want to execute:\n\t" + command + " with the wscript shell\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing " + command + " using the wscript shell\n"); cliExec("wscript", command); Console.Write("\nPress enter to continue "); Console.ReadLine(); File.Delete(Directory.GetCurrentDirectory() + "\\parent.vbs"); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== Like a bad habit... ====="); Thread.Sleep(3000); wscript = false; break; default: Console.WriteLine("\nEveryone likes a mystery..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "9": bool fiber = true; while (fiber) { Console.Clear(); Console.WriteLine("\n===== Windows Fiber execution =====\n"); Console.Write("Fibers are like threads but \"invisible\" in terms of scheduling to the kernel\n\tscheduling is implemented in userland, you're welcome\n\tI need a full command and args (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"Men don't pay attention to small things.\" --Katherine Johnson ====="); Thread.Sleep(3000); fiber = false; }//end if else { Console.Write("\nAre you sure you want to execute:\n\t" + command + " from a Windows fiber\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing " + command + " from a Windows fiber\n"); Thread t = new Thread(ThreadProc); t.Start(command); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== Threads are easier anyways... ====="); Thread.Sleep(3000); fiber = false; break; default: Console.WriteLine("\nThis is already complex enough..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "10": bool wxsl = true; while (wxsl) { Console.Clear(); Console.WriteLine("\n===== WMIC XSL Script Processing (Squiblytwo) =====\n"); Console.Write("I'll build a xsl file for you (you're welcome),\n\tbut I WILL NOT sanitize input (so play nice unless you know what you're doing)\n\tI need a full command and args (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"...If it weren't for those meddling kids.\" --Too Many Scooby-Doo Villains ====="); Thread.Sleep(3000); wxsl = false; }//end if else { Console.Write("\nAre you sure you want to execute:\n\t" + command + " through a wmic xsl script\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing " + command + " through a wmic xsl script\n"); cliExec("wxsl", command); Console.Write("\nPress enter to continue "); Console.ReadLine(); File.Delete(Directory.GetCurrentDirectory() + "\\parent.xsl"); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== WMIC is weird... ====="); Thread.Sleep(3000); wxsl = false; break; default: Console.WriteLine("\nDon't try to wiggle out of this one..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "11": bool wordz = true; while (wordz) { Console.Clear(); Console.WriteLine("\n===== Microsoft Word VBA Macro =====\n"); Console.Write("I'll build a doc file for you (you're welcome),\n\tbut I WILL NOT sanitize input (so play nice unless you know what you're doing)\n\tI need a full command and args (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"Words are but pictures of our thoughts.\" --John Dryden ====="); Thread.Sleep(3000); wordz = false; }//end if else { Console.Write("\nAre you sure you want to execute:\n\t" + command + " inside a Word macro\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing " + command + " inside a Word macro at " + DateTime.Now.ToString("HH:mm:ss tt") + "\n"); Console.WriteLine(); //thank you https://github.com/enigma0x3/Generate-Macro Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application(); object missing = System.Reflection.Missing.Value; string VBCode = "Sub AutoOpen()\nEZ\nEnd Sub\nPublic Function EZ() As Variant\nPID = Shell(\"" + command + "\",4)\nEnd Function"; try { Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing); string path = Directory.GetCurrentDirectory() + "\\parent.docm"; document.SaveAs2(path); Microsoft.Vbe.Interop.VBProject Project = document.VBProject; Microsoft.Vbe.Interop.VBComponent Module = Project.VBComponents.Add(Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule); Microsoft.Vbe.Interop.CodeModule Code = Module.CodeModule; Code.AddFromString(VBCode); Process currentProcess = Process.GetCurrentProcess(); Process process = new Process(); process.StartInfo.FileName = "winword.exe"; process.StartInfo.Arguments = path; process.StartInfo.RedirectStandardOutput = false; process.StartInfo.RedirectStandardError = false; process.StartInfo.UseShellExecute = false; process.Start(); Console.WriteLine(process.ProcessName + " started at " + process.StartTime + " as PID " + process.Id); //find real winword.exe Thread.Sleep(1000); Process[] winWordTwo = Process.GetProcessesByName("winword"); foreach (Process winPid in winWordTwo) { trackANDkill((int) winPid.Id); }//end foreach Console.Write("\nPress enter to continue "); Console.ReadLine(); File.Delete(path); }//end try catch (Exception ex) { Console.Write(ex + "\n\nAlso double check that you have enabled macros and automagic code access (aka trust access to the VBA project object model) for this jazz to work\n\nPeep https://support.office.com/en-us/article/enable-or-disable-macros-in-office-files-12b036fd-d140-4e74-b45e-16fed1a7e5c6 for the good word\n"); }//end catch break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== This was harder to do than it seems... ====="); Thread.Sleep(3000); wordz = false; break; default: Console.WriteLine("\nThere's a time to be different, but not now..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "exit": Console.Clear(); Console.WriteLine("\n===== stay classy =====\n"); Thread.Sleep(3000); System.Environment.Exit(1); break; default: Console.Clear(); Console.WriteLine("\n===== try to play nice... =====\n"); break; case "12": bool python = true; while (python) { Console.Clear(); Console.WriteLine("\n===== python.exe execution =====\n"); Console.Write("please provide the cmd.exe command you want to execute via python.exe (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"Snakes are only cool if they are eating their own tail.\" --Yours Truly ====="); Thread.Sleep(3000); python = false; }//end if else { Console.Write("\nAre you sure you want to execute:\n\t " + command + " via python.exe\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing " + command + " via python.exe\n"); command = "\"import os;os.system(\'" + command + "\')\""; Console.Write(command); cliExec("python", command); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== I'm not a big fan of python either... ====="); Thread.Sleep(3000); python = false; break; default: Console.WriteLine("\nNot everyone can color inside the lines..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; }//end switch }//end while }//end Main
private void Work_Macro_Click(object sender, EventArgs e) { //Проверяем существование базы данных в текущем каталоге String db_filename = Directory.GetCurrentDirectory() + @"\db.accdb"; if (File.Exists(Directory.GetCurrentDirectory() + @"\db.accdb") == false) { //Создание каталога ADOX ADOX.Catalog adoxCat = new ADOX.Catalog(); //Создание базы данных adoxCat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Directory.GetCurrentDirectory() + @"\db.accdb" + ";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Password="******"\db.accdb", false); //Создаем ссылку класса VBProject на текущий объект БД Microsoft.Vbe.Interop.VBProject project = oAccess.VBE.VBProjects.Item(1); //Создаем ссылку класса VBComponent на созданный модуль БД Microsoft.Vbe.Interop.VBComponent module = project.VBComponents.Add(Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule); //Вставляем текст в модуль module.CodeModule.AddFromString(Properties.Resources.Macro); //Сохранение макроса oAccess.DoCmd.Save(Microsoft.Office.Interop.Access.AcObjectType.acModule, module.Name.ToString()); //Присваеваем список схем и выбранных таблиц string[] Schemas = new string[ListBox_Schemes.Items.Count]; string[] Tables = new string[CheckedListBox_Tables.CheckedItems.Count]; //Цикл по схемам int i = 0; foreach (Object Схема in ListBox_Schemes.Items) { Schemas[i] = (string)Схема; i++; } i = 0; //Цикл по таблицам foreach (Object Таблица in CheckedListBox_Tables.CheckedItems) { Tables[i] = (string)Таблица; i++; } //Запуск функции "export" в созданном модуле VBA oAccess.Run("export", Schemas, Tables, Server.Text, Port.Text, Uid.Text, Pwd.Text); //Закрытие модуля VBA oAccess.DoCmd.Close(Microsoft.Office.Interop.Access.AcObjectType.acModule, module.Name.ToString(), Microsoft.Office.Interop.Access.AcCloseSave.acSaveYes); //Удаление модуля VBA oAccess.DoCmd.DeleteObject(Microsoft.Office.Interop.Access.AcObjectType.acModule, module.Name.ToString()); //Выход из приложения ACCESS без сохранения изменений oAccess.DoCmd.Quit(Microsoft.Office.Interop.Access.AcQuitOption.acQuitSaveNone); //Освободить объект oAccess System.Runtime.InteropServices.Marshal.ReleaseComObject(oAccess); oAccess = null; }