/// <summary> /// Installs the windows service. It uses InstallUtil.exe to complete the actual installation/uninstallation. /// During the run for the InstallUtil.exe console window is hidden. /// If any error occurred the console output is captured and embedded into the raised Exception object. /// </summary> /// <param name="serviceFile">The service file.</param> /// <param name="isInstalling">if set to <c>true</c> [is installing].</param> /// <param name="args">The additional InstallUtil.exe arguments.</param> /// <exception cref="T:System.Exception"></exception> /// <returns></returns> static public string InstallService(string serviceFile, bool isInstalling, string args = null) { var util = new ExternalTool { ExePath = IO.Path.Combine(CurrentFrameworkDirectory, "InstallUtil.exe"), Arguments = string.Format("{1} \"{0}\" ", serviceFile, isInstalling ? "" : "/u") + args ?? "" }; var buf = new StringBuilder(); int retval = util.ConsoleRun(line => buf.AppendLine(line)); string output = buf.ToString(); string logoLastLine = "Microsoft Corporation. All rights reserved."; int pos = output.IndexOf(logoLastLine); if (pos != -1) { output = output.Substring(pos + logoLastLine.Length).Trim(); } if (retval != 0) { throw new Exception(output); } return(output); }
void setToolValues(object sender, EventArgs e) { ExternalTool selectedItem = ((ListBox)ControlDictionary["toolListBox"]).SelectedItem as ExternalTool; selectedItem.MenuCommand = ControlDictionary["titleTextBox"].Text; selectedItem.Command = ControlDictionary["commandTextBox"].Text; }
public static void Prot_Event_Closed(object sender) { try { ProtocolBase Prot = (ProtocolBase)sender; MessageCollector.AddMessage(MessageClass.InformationMsg, Language.strConnenctionCloseEvent, true); MessageCollector.AddMessage(MessageClass.ReportMsg, string.Format(Language.strConnenctionClosedByUser, Prot.InterfaceControl.Info.Hostname, Prot.InterfaceControl.Info.Protocol.ToString(), Environment.UserName)); Prot.InterfaceControl.Info.OpenConnections.Remove(Prot); if (Prot.InterfaceControl.Info.OpenConnections.Count < 1 && Prot.InterfaceControl.Info.IsQuickConnect == false) { ConnectionTreeNode.SetNodeImage(Prot.InterfaceControl.Info.TreeNode, TreeImageType.ConnectionClosed); } if (Prot.InterfaceControl.Info.PostExtApp != "") { ExternalTool extA = GetExtAppByName(Prot.InterfaceControl.Info.PostExtApp); if (extA != null) { extA.Start(Prot.InterfaceControl.Info); } } } catch (Exception ex) { MessageCollector.AddMessage(MessageClass.ErrorMsg, Language.strConnenctionCloseEventFailed + Environment.NewLine + ex.Message, true); } }
string FindFontFileFromFontName(string fontname, string style) { string s, e; ExternalTool.Run("/bin/bash", string.Format("-c \"fc-match -f '%{{file}}:%{{family}}\\n' '{0}:style={1}'\"", fontname, style), out s, out e); s = s.Trim(); var split = s.Split(':'); //check font family, fontconfig might return a fallback if (split [1].Contains(",")) //this file defines multiple family names { var families = split [1].Split(','); foreach (var f in families) { if (f.ToLowerInvariant() == fontname.ToLowerInvariant()) { return(split [0]); } } //didn't find it return(String.Empty); } else { if (split [1].ToLowerInvariant() != fontname.ToLowerInvariant()) { return(String.Empty); } } return(split [0]); }
public void ExternalTool_ConsumingResultWithStandardErrorOutput_ThrowsException() { const string canary = "6h4sb6455t"; // Just echo something to stderr. Assert.ThrowsException <EnvironmentException>(() => ExternalTool.Execute(TestData.CommandHandler, TestData.MakeCommandString(string.Format("echo {0} 1>&2", canary)), ExecuteTimeout)); }
public void ExternalTool_WithStandardOutputAndStandardErrorContents_BothOutputStreamsAreWrittenToFile() { const string canary1 = "se5sm85"; const string canary2 = "ze5vb75"; var outputFile = Path.GetTempFileName(); // Need to do this the long way around to avoid consuming the result. var result = new ExternalTool { ExecutablePath = TestData.CommandHandler, Arguments = TestData.MakeCommandString(string.Format("echo {0} & {1}", canary1, canary2)), OutputFilePath = outputFile }.Start().GetResult(ExecuteTimeout); // Just for debug info. result.ForwardOutputs(); try { Assert.AreNotEqual(0, result.ExitCode); Assert.IsTrue(result.StandardOutput.Contains(canary1)); Assert.IsTrue(result.StandardError.Contains(canary2)); var outputFileContents = File.ReadAllText(outputFile); Assert.IsTrue(outputFileContents.Contains(canary1)); Assert.IsTrue(outputFileContents.Contains(canary2)); } finally { File.Delete(outputFile); } }
void ToolEvt(object sender, EventArgs e) { SdMenuCommand item = (SdMenuCommand)sender; StringParserService stringParserService = (StringParserService)ServiceManager.Services.GetService(typeof(StringParserService)); for (int i = 0; i < ToolLoader.Tool.Count; ++i) { if (item.Text == ToolLoader.Tool[i].ToString()) { ExternalTool tool = (ExternalTool)ToolLoader.Tool[i]; stringParserService.Properties["StartupPath"] = Application.StartupPath; string command = stringParserService.Parse(tool.Command); try { ProcessStartInfo startinfo = new ProcessStartInfo(command, ""); startinfo.WorkingDirectory = ""; Process.Start(startinfo); } catch (Exception ex) { MessageBox.Show(command + "\n" + ex.ToString(), "启动程序时出错:", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; } } }
public void ExternalTool_ConsumingResultWithNonSuccessfulExitCode_ThrowsException() { const string canary = "fgujw456hnt"; // Nonsense command, should result in error. Assert.ThrowsException <EnvironmentException>(() => ExternalTool.Execute(TestData.CommandHandler, TestData.MakeCommandString(canary), ExecuteTimeout)); }
public static ActionResult UninstallService(Session session) { return(session.HandleErrors( () => { // Debugger.Launch(); var installDir = session.Property("INSTALLDIR"); var filePath = session.Property(InstallBuilder.CustomParam); if (string.IsNullOrEmpty(filePath)) { throw new InvalidOperationException("FilePath is empty"); } if (!File.Exists(filePath)) { throw new InvalidOperationException(filePath + " does not exist"); } var externalTool = new ExternalTool { ExePath = filePath, Arguments = "uninstall" }; session.Log($"Executing '{filePath}' uninstall..."); externalTool.WinRun(); session.Log($"Deleting '{installDir}'..."); Directory.Delete(installDir, true); })); }
public static ActionResult InstallService(Session session) { return(session.HandleErrors( () => { // Debugger.Launch(); var filePath = session.Property(InstallBuilder.CustomParam); if (string.IsNullOrEmpty(filePath)) { throw new InvalidOperationException("FilePath is empty"); } if (!File.Exists(filePath)) { throw new InvalidOperationException(filePath + " does not exist"); } var externalTool = new ExternalTool { ExePath = filePath, Arguments = "install" }; session.Log($"Executing '{filePath} install'..."); externalTool.WinRun(); externalTool.Arguments = "start"; session.Log($"Executing '{filePath} start'..."); externalTool.WinRun(); })); }
/// <summary> /// Applies digital signature to a file (e.g. msi, exe, dll) with MS <c>SignTool.exe</c> utility. /// </summary> /// <param name="fileToSign">The file to sign.</param> /// <param name="pfxFile">Specify the signing certificate in a file. If this file is a PFX with a password, the password may be supplied /// with the <c>password</c> parameter.</param> /// <param name="timeURL">The timestamp server's URL. If this option is not present (pass to null), the signed file will not be timestamped. /// A warning is generated if timestamping fails.</param> /// <param name="password">The password to use when opening the PFX file. Should be <c>null</c> if no password required.</param> /// <param name="optionalArguments">Extra arguments to pass to the <c>SignTool.exe</c> utility.</param> /// <param name="wellKnownLocations">The optional ';' separated list of directories where SignTool.exe can be located. /// If this parameter is not specified WixSharp will try to locate the SignTool in the built-in well-known locations (system PATH)</param> /// <returns>Exit code of the <c>SignTool.exe</c> process.</returns> /// /// <example>The following is an example of signing <c>Setup.msi</c> file. /// <code> /// WixSharp.CommonTasks.Tasks.DigitalySign( /// "Setup.msi", /// "MyCert.pfx", /// "http://timestamp.verisign.com/scripts/timstamp.dll", /// "MyPassword", /// null); /// </code> /// </example> static public int DigitalySign(string fileToSign, string pfxFile, string timeURL, string password, string optionalArguments = null, string wellKnownLocations = null) { //"C:\Program Files\\Microsoft SDKs\Windows\v6.0A\bin\signtool.exe" sign /f "pfxFile" /p password /v "fileToSign" /t timeURL //string args = "sign /v /f \"" + pfxFile + "\" \"" + fileToSign + "\""; string args = "sign /v /f \"" + pfxFile + "\""; if (timeURL != null) { args += " /t \"" + timeURL + "\""; } if (password != null) { args += " /p \"" + password + "\""; } if (!optionalArguments.IsEmpty()) { args += " " + optionalArguments; } args += " \"" + fileToSign + "\""; var tool = new ExternalTool { WellKnownLocations = wellKnownLocations ?? @"C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin;C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin", ExePath = "signtool.exe", Arguments = args }; return(tool.ConsoleRun()); }
/// <summary> /// Processes the string representation of the specified effect into /// a platform-specific binary format using the specified context. /// </summary> /// <param name="input">The effect string to be processed.</param> /// <param name="context">Context for the specified processor.</param> /// <returns>A platform-specific compiled binary effect.</returns> /// <remarks> /// If you get an error during processing, compilation stops immediately. /// The effect processor displays an error message. /// Once you fix the current error, it is possible you may get more errors on subsequent compilation attempts. /// </remarks> public override CompiledEffectContent Process(EffectContent input, ContentProcessorContext context) { var mgfxc = Path.Combine(Path.GetDirectoryName(typeof(EffectProcessor).Assembly.Location), "mgfxc.dll"); var sourceFile = input.Identity.SourceFilename; var destFile = Path.GetTempFileName(); var arguments = "\"" + mgfxc + "\" \"" + sourceFile + "\" \"" + destFile + "\" /Profile:" + GetProfileForPlatform(context.TargetPlatform); if (DebugMode == EffectProcessorDebugMode.Debug) { arguments += " /Debug"; } if (!string.IsNullOrWhiteSpace(Defines)) { arguments += " \"/Defines:" + Defines + "\""; } var success = ExternalTool.Run("dotnet", arguments, out var stdout, out var stderr) == 0; var ret = success ? new CompiledEffectContent(File.ReadAllBytes(destFile)) : null; File.Delete(destFile); var stdOutLines = stdout.ToString().Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); foreach (var line in stdOutLines) { if (line.StartsWith("Dependency:") && line.Length > 12) { context.AddDependency(line[12..]);
/// <summary> /// Adds the reference to the Visual Studio project. /// </summary> /// <param name="project">The project.</param> /// <returns></returns> /// <exception cref="Exception"> /// Project '{project.ProjectPath}' not found. /// or /// 'Heat' failure... /// </exception> public Harvester AddProject(VsProject project) { if (!System.IO.File.Exists(project.ProjectPath)) { throw new Exception($"Project '{project.ProjectPath}' not found."); } var sourceDir = project.BuildPath; var projectDir = project.ProjectPath.PathGetDirName(); var targetDir = project.TargetDir ?? this.targetDir; var output = this.project.OutDir.PathJoin($"{project.Name}.wxs"); var tool = new ExternalTool { ExePath = heat, Arguments = new[] { $"project \"{project.ProjectPath}\"", project.Binaries ? "-pog Binaries" : "", project.Symbols ? "-pog Symbols" : "", project.Documents ? "-pog Documents" : "", project.Satellites ? "-pog Satellites" : "", project.Content ? "-pog Content" : "", "-ag", "-sfrag", $"-directoryid \"{targetDir}\"", "-template fragment", $"-platform AnyCPU", $"-projectname \"{project.Name}\"", $"-out \"{output}\"" }.Join(" ") }; // Note, all StdOut and StdErr will be printed by the `tool` anyway if (tool.ConsoleRun() != 0) { throw new Exception("'Heat' failure..."); } var xml = XDocument.Load(output); foreach (var fragment in xml.Root.Elements()) { this.project.AddXml("Wix", fragment.ToString()); } // As intended the TargetDir for candle is the sourceDir this.project.CandleOptions += $" -d\"{project.Name}.TargetDir\"=\"{sourceDir}\" " + $" -d\"{project.Name}.ProjectDir\"=\"{projectDir}\" "; components.Add(project); if (!Compiler.PreserveTempFiles) { System.IO.File.Delete(output); } return(this); }
public void ExternalTool_StandardOutputIsCaptured() { const string canary = "146adgha4"; var result = ExternalTool.Execute(TestData.CommandHandler, TestData.MakeCommandString(string.Format("echo {0}", canary)), ExecuteTimeout); Assert.AreEqual(0, result.ExitCode); Assert.IsTrue(result.StandardOutput.Contains(canary)); }
private static void StartPreConnectionExternalApp(ConnectionInfo ConnectionInfo) { if (ConnectionInfo.PreExtApp != "") { ExternalTool extA = GetExtAppByName(ConnectionInfo.PreExtApp); extA?.Start(ConnectionInfo); } }
public MainWindow() { InitializeComponent(); ExternalTool.Initialise("BalanceSpecsGUI.Resources.DefaultTools.json"); NewButton_Click(null, null); }
private void Button_Click(object sender, RoutedEventArgs e) { ExternalTool.Initialise("BalanceSpecsGUI.Resources.DefaultTools.json"); ExternalTool.AddToolToSettings(PathToExecutable.Text, Name.Text); this.Close(); }
public void LoadExternalAppsFromXML() { #if !PORTABLE var oldPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), GeneralAppInfo.ProductName, SettingsFileInfo.ExtAppsFilesName); #endif var newPath = Path.Combine(SettingsFileInfo.SettingsPath, SettingsFileInfo.ExtAppsFilesName); var xDom = new XmlDocument(); if (File.Exists(newPath)) { Logger.Instance.Info($"Loading External Apps from: {newPath}"); xDom.Load(newPath); } #if !PORTABLE else if (File.Exists(oldPath)) { Logger.Instance.Info($"Loading External Apps from: {oldPath}"); xDom.Load(oldPath); } #endif else { Logger.Instance.Warn("Loading External Apps failed: Could not FIND file!"); return; } if (xDom.DocumentElement == null) { Logger.Instance.Warn("Loading External Apps failed: Could not LOAD file!"); return; } foreach (XmlElement xEl in xDom.DocumentElement.ChildNodes) { var extA = new ExternalTool { DisplayName = xEl.Attributes["DisplayName"].Value, FileName = xEl.Attributes["FileName"].Value, Arguments = xEl.Attributes["Arguments"].Value }; if (xEl.HasAttribute("WaitForExit")) { extA.WaitForExit = bool.Parse(xEl.Attributes["WaitForExit"].Value); } if (xEl.HasAttribute("TryToIntegrate")) { extA.TryIntegrate = bool.Parse(xEl.Attributes["TryToIntegrate"].Value); } Logger.Instance.Info($"Adding External App: {extA.DisplayName} {extA.FileName} {extA.Arguments}"); Runtime.ExternalTools.Add(extA); } _MainForm.SwitchToolBarText(Convert.ToBoolean(mRemoteNG.Settings.Default.ExtAppsTBShowText)); frmMain.Default.AddExternalToolsToToolBar(); }
public void ExternalTool_StandardErrorIsInExceptionMessage() { const string canary = "jtd78d56rereee"; // Nonsense command, should result in error. var ex = Assert.ThrowsException <EnvironmentException>(() => ExternalTool.Execute(TestData.CommandHandler, TestData.MakeCommandString(canary), ExecuteTimeout)); Assert.IsTrue(ex.Message.Contains(canary)); }
/// <summary> /// Выполнить внешнее ПО /// </summary> /// <param name="Program"></param> /// <param name="ProgArgs"></param> /// <param name="Args"></param> /// <param name="Rewrite"></param> /// <returns></returns> public static ExternalToolResult Exec(string Program, string ProgArgs, ArgumentList Args, OptRewrite[] Rewrite) { var CmdPath = ProcessCommand(Program, Args, Rewrite); var CmdArgs = ProcessCommand(ProgArgs, Args, Rewrite); string Dir = Args.Get("$dir"); return(ExternalTool.Run(CmdPath, CmdArgs, Dir)); }
private string FindFont(string name, string style) { if (CurrentPlatform.OS == OS.Windows) { var fontDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts"); var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts", false); foreach (var font in key.GetValueNames().OrderBy(x => x)) { if (font.StartsWith(name, StringComparison.OrdinalIgnoreCase)) { var fontPath = key.GetValue(font).ToString(); return(Path.IsPathRooted(fontPath) ? fontPath : Path.Combine(fontDirectory, fontPath)); } } } else if (CurrentPlatform.OS == OS.Linux) { string s, e; ExternalTool.Run("/bin/bash", string.Format("-c \"fc-match -f '%{{file}}:%{{family}}\\n' '{0}:style={1}'\"", name, style), out s, out e); s = s.Trim(); var split = s.Split(':'); if (split.Length < 2) { return(string.Empty); } // check font family, fontconfig might return a fallback if (split[1].Contains(",")) { // this file defines multiple family names var families = split[1].Split(','); foreach (var f in families) { if (f.ToLowerInvariant() == name.ToLowerInvariant()) { return(split[0]); } } // didn't find it return(string.Empty); } else { if (split[1].ToLowerInvariant() != name.ToLowerInvariant()) { return(string.Empty); } } return(split[0]); } return(String.Empty); }
public override bool Initialize() { if (InterfaceControl.Info != null) { _externalTool = Runtime.GetExtAppByName(Convert.ToString(InterfaceControl.Info.ExtApp)); _externalTool.ConnectionInfo = InterfaceControl.Info; } return(base.Initialize()); }
void setToolValues(object sender, EventArgs e) { ExternalTool selectedItem = ((ListBox)ControlDictionary["toolListBox"]).SelectedItem as ExternalTool; selectedItem.MenuCommand = ControlDictionary["titleTextBox"].Text; selectedItem.Command = ControlDictionary["commandTextBox"].Text; selectedItem.Arguments = ControlDictionary["argumentTextBox"].Text; selectedItem.InitialDirectory = ControlDictionary["workingDirTextBox"].Text; selectedItem.PromptForArguments = ((CheckBox)ControlDictionary["promptArgsCheckBox"]).Checked; selectedItem.UseOutputPad = ((CheckBox)ControlDictionary["useOutputPadCheckBox"]).Checked; }
private void NewExternalWidget() { var newTool = ExternalTool.PickTool(); if (newTool == null) { return; } AddToolWidget(newTool); }
void AddButton_Click(object sender, RoutedEventArgs e) { EditEnable = true; ButtonsEnable = true; var newTool = new ExternalTool(); listBox.Items.Add(newTool); SelectedTool = newTool; int i = listBox.SelectedIndex; listBox.SelectedIndex = listBox.Items.Count - 1; }
private void StartExternalApp(ExternalTool externalTool) { try { var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; externalTool.Start(interfaceControl?.Info); } catch (Exception ex) { Runtime.MessageCollector.AddExceptionMessage("cmenTabExternalAppsEntry_Click failed (UI.Window.ConnectionWindow)", ex); } }
public override bool Initialize() { if (InterfaceControl.Info == null) { return(base.Initialize()); } _externalTool = Runtime.GetExtAppByName(InterfaceControl.Info.ExtApp); _externalTool.ConnectionInfo = InterfaceControl.Info; return(base.Initialize()); }
private void StartExternalApp(ExternalTool externalTool) { try { var interfaceControl = TabController.SelectedTab?.Tag as InterfaceControl; externalTool.Start(interfaceControl?.Info); } catch (Exception ex) { Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg, "cmenTabExternalAppsEntry_Click failed (UI.Window.ConnectionWindow)" + Environment.NewLine + ex.Message, true); } }
public async Task ExternalTool_WhenAsync_StandardOutputIsCaptured() { const string canary = "146adgha4"; using (var cancel = new CancellationTokenSource(ExecuteTimeout)) { var result = await ExternalTool.ExecuteAsync(TestData.CommandHandler, TestData.MakeCommandString(string.Format("echo {0}", canary)), cancel.Token); Assert.AreEqual(0, result.ExitCode); Assert.IsTrue(result.StandardOutput.Contains(canary)); } }
static void TemplateMethodPattern() { Console.WriteLine("\n\nTemplate Method Pattern"); var tool = new ExternalTool(); var concreteA = new ConcreteTemplateA(tool); concreteA.Method(); var concreteB = new ConcreteTemplateB(tool); concreteB.Method(); }