public IEnumerable<Result> Run(Context context, ISpecificationRunListener listener, RunOptions options) { IEnumerable<Result> results; listener.OnContextStart(context.GetInfo()); Result result = Result.Pass(); if (context.HasExecutableSpecifications) { result = context.EstablishContext(); } if (result.Passed) { results = RunSpecifications(context, listener, options); } else { results = FailSpecifications(context, listener, options, result); } if (context.HasExecutableSpecifications) { result = context.Cleanup(); } listener.OnContextEnd(context.GetInfo()); return results; }
public IEnumerable<Result> Run(Context context, ISpecificationRunListener listener, RunOptions options, IEnumerable<ICleanupAfterEveryContextInAssembly> globalCleanups, IEnumerable<ISupplementSpecificationResults> resultSupplementers) { IEnumerable<Result> results; listener.OnContextStart(context.GetInfo()); Result result = Result.Pass(); if (context.HasExecutableSpecifications) { result = context.EstablishContext(); } if (result.Passed) { results = RunSpecifications(context, listener, options, resultSupplementers); } else { results = FailSpecifications(context, listener, result, resultSupplementers); } if (context.HasExecutableSpecifications) { result = context.Cleanup(); foreach (var cleanup in globalCleanups) { cleanup.AfterContextCleanup(); } } listener.OnContextEnd(context.GetInfo()); return results; }
public RunNode Run(string fileName, string arguments, RunOptions options) { var node = new ExternalNode(fileName, arguments, options) { OutputNode = this }; InputNode = node; return node; }
public AppDomainRunner(ISpecificationRunListener listener, RunOptions options) { _listener = new RemoteRunListener(listener); _options = options; _signalRunStart = new InvokeOnce(listener.OnRunStart); _signalRunEnd = new InvokeOnce(listener.OnRunEnd); }
public DefaultRunner(ISpecificationRunListener listener, RunOptions options) { _listener = listener; _options = options; _assemblyRunner = new AssemblyRunner(_listener, _options); _explorer = new AssemblyExplorer(); _runStart = () => _listener.OnRunStart(); _runEnd = () => _listener.OnRunEnd(); }
private static RunOptions GetOptions(string args) { var runOptions = new RunOptions(); try { Parser.Default.ParseArguments(args.Split(new[] {' '}, 3), runOptions); } catch { } return runOptions; }
private IEnumerable<Result> FailSpecifications(Context context, ISpecificationRunListener listener, RunOptions options, Result result) { var results = new List<Result>(); foreach (var specification in context.Specifications) { listener.OnSpecificationStart(specification.GetInfo()); listener.OnSpecificationEnd(specification.GetInfo(), result); results.Add(result); } return results; }
private static IEnumerable<Result> RunSpecifications(Context context, ISpecificationRunListener listener, RunOptions options, IEnumerable<ISupplementSpecificationResults> resultSupplementers) { var results = new List<Result>(); foreach (var specification in context.Specifications) { var runner = new SpecificationRunner(listener, options, resultSupplementers); var result = runner.Run(specification); results.Add(result); } return results; }
public AssemblyRunner(ISpecificationRunListener listener, RunOptions options) { _listener = new AggregateRunListener(new[] { new AssemblyLocationAwareListener(), new AssemblyContextRunListener(), listener }); _options = options; _assemblyStart = OnAssemblyStart; _assemblyEnd = OnAssemblyEnd; }
public DefaultRunner(ISpecificationRunListener listener, RunOptions options, bool signalRunStartAndEnd) { _listener = listener; _options = options; _assemblyRunner = new AssemblyRunner(_listener, _options); _explorer = new AssemblyExplorer(); if (signalRunStartAndEnd) { _runStart = new InvokeOnce(() => _listener.OnRunStart()); _runEnd = new InvokeOnce(() => _listener.OnRunEnd()); } }
public static RunResult Run(RunOptions options) { RunResult result = new RunResult(); using (Process p = Detach(options)) { Thread.Sleep(2000); p.WaitForInputIdle(); result.WindowTitle = p.MainWindowTitle; p.CloseMainWindow(); p.WaitForExit(); result.ExitCode = p.ExitCode; } return result; }
private static IEnumerable<Result> FailSpecifications(Context context, ISpecificationRunListener listener, RunOptions options, Result result, IEnumerable<ISupplementSpecificationResults> resultSupplementers) { result = resultSupplementers.Aggregate(result, (r, supplement) => supplement.SupplementResult(r)); var results = new List<Result>(); foreach (var specification in context.Specifications) { listener.OnSpecificationStart(specification.GetInfo()); listener.OnSpecificationEnd(specification.GetInfo(), result); results.Add(result); } return results; }
public AssemblyRunner(ISpecificationRunListener listener, RunOptions options) { var state = new RedirectOutputState(); _listener = new AggregateRunListener(new[] { new AssemblyLocationAwareListener(), new SetUpRedirectOutputRunListener(state), listener, new TearDownRedirectOutputRunListener(state), new AssemblyContextRunListener() }); _options = options; _assemblyStart = OnAssemblyStart; _assemblyEnd = OnAssemblyEnd; }
public IEnumerable<Result> Run(Context context, ISpecificationRunListener listener, RunOptions options, IEnumerable<ICleanupAfterEveryContextInAssembly> globalCleanups, IEnumerable<ISupplementSpecificationResults> resultSupplementers) { var results = new List<Result>(); listener.OnContextStart(context.GetInfo()); foreach (var specification in context.Specifications) { Result result = Result.Pass(); if (specification.IsExecutable) { result = context.EstablishContext(); } if (result.Passed) { var runner = new SpecificationRunner(listener, options, resultSupplementers); result = runner.Run(specification); } else { results = FailSpecification(listener, specification, result); } if (specification.IsExecutable) { var cleanupResult = context.Cleanup(); if (result.Passed && !cleanupResult.Passed) { result = cleanupResult; } foreach (var cleanup in globalCleanups) { cleanup.AfterContextCleanup(); } } results.Add(result); } listener.OnContextEnd(context.GetInfo()); return results; }
/// <summary> /// Runs the installer and waits till its exit for a specified timeout. /// </summary> /// <param name="options">Run options.</param> /// <param name="timeout">Timeout. Negative values mean "no timeout".</param> /// <returns>Exit code of the installer process.</returns> /// <exception cref="TimeoutException"> /// Timeout exceeded while waiting for the installer process to exit. /// </exception> public static int Run(RunOptions options, TimeSpan timeout) { Process p = Detach(options); if (timeout < TimeSpan.Zero) { p.WaitForExit(); } else { if (!p.WaitForExit((int)timeout.TotalMilliseconds)) { p.Kill(); p.WaitForExit(); throw new TimeoutException(); } } return p.ExitCode; }
public void WhenRunningWith_OneProject_OneJob_And_CopyTask__ShouldCopyFileToTarget() { RunOptions options = new RunOptions { BackendXml = true, ConfigPath = "eaw-ci.xml", ProjectName = "pid0", JobName = "My-Job" }; CreateXmlConfigWithTask(CopyTask); EawXBuildApplication sut = new EawXBuildApplication(_services.BuildServiceProvider(), options); sut.Run(); bool actual = _fileSystem.File.Exists("newfile.xml"); Assert.IsTrue(actual); }
public int StartPaused(RunOptions options, TestRunner runner) { var currentPath = Environment.CurrentDirectory; try { Environment.CurrentDirectory = Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath); using (var assembly = Reflect.On(options.TestRuns.ElementAt(0).Assemblies.ElementAt(0).Assembly)) { _version = assembly.GetTargetFramework(); } //var wrapper = getWrapper(options, runner); var inputFile = Path.GetTempFileName(); var outputFile = Path.GetTempFileName(); var writer = new OptionsXmlWriter(new Plugin[] {}, options); writer.Write(inputFile); AutoTest.Core.DebugLog.Debug.WriteDebug("About to debug:"); AutoTest.Core.DebugLog.Debug.WriteDebug(File.ReadAllText(inputFile)); var arguments = string.Format("--input=\"{0}\" --output=\"{1}\" --startsuspended --silent", inputFile, outputFile); var exe = new TestProcessSelector().Get(options.TestRuns.ElementAt(0).Assemblies.ElementAt(0).Assembly); AutoTest.Core.DebugLog.Debug.WriteDebug("Running: " + exe + " " + arguments); _process = new Process(); _process.StartInfo = new ProcessStartInfo(exe, arguments); _process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; _process.StartInfo.RedirectStandardInput = true; _process.StartInfo.UseShellExecute = false; _process.StartInfo.CreateNoWindow = true; _process.StartInfo.WorkingDirectory = Environment.CurrentDirectory; _process.Start(); return(_process.Id); } catch (Exception ex) { AutoTest.Core.DebugLog.Debug.WriteException(ex); } finally { Environment.CurrentDirectory = currentPath; } return(0); }
public async Task <int> Execute(RunOptions options) { WelcomeHelper.PrintWelcomeMessage(); if (!File.Exists("endpoints.json")) { Console.WriteLine("Could not find endpoints.json. Please run 'erg discover <url>' first to find our runnable endpoints"); } var endpoints = ConfigReader.GetEndpoints(); var endpoint = endpoints.FirstOrDefault(e => e.Alias == options.CommandAlias); if (endpoint is null) { Console.WriteLine($"Could not find endpoint {options.CommandAlias}. Please run 'erg discover <url> first to find out runnable endpoints'"); return(1); } return(await RunEndpoint(endpoint)); }
public async Task <PopulationRunResults> RunAsync(PopulationSimulation populationSimulation, SimulationRunOptions simulationRunOptions) { _progressUpdater = _progressManager.Create(); _progressUpdater.Initialize(populationSimulation.NumberOfItems, PKSimConstants.UI.Calculating); var begin = SystemTime.UtcNow(); try { var populationData = _populationExporter.CreatePopulationDataFor(populationSimulation); var modelCoreSimulation = _modelCoreSimulationMapper.MapFrom(populationSimulation, shouldCloneModel: false); var runOptions = new RunOptions { NumberOfCoresToUse = _userSettings.MaximumNumberOfCoresToUse }; _eventPublisher.PublishEvent(new SimulationRunStartedEvent()); var populationRunResults = await _populationRunner.RunPopulationAsync(modelCoreSimulation, runOptions, populationData, populationSimulation.AgingData.ToDataTable()); _simulationResultsSynchronizer.Synchronize(populationSimulation, populationRunResults.Results); _populationSimulationAnalysisSynchronizer.UpdateAnalysesDefinedIn(populationSimulation); _eventPublisher.PublishEvent(new SimulationResultsUpdatedEvent(populationSimulation)); return(populationRunResults); } catch (OperationCanceledException) { simulationTerminated(); return(null); } catch (Exception) { simulationTerminated(); throw; } finally { var end = SystemTime.UtcNow(); var timeSpent = end - begin; _eventPublisher.PublishEvent(new SimulationRunFinishedEvent(populationSimulation, timeSpent)); } }
/// <summary> /// Runs a method in the compiled code based on the given options. If the code does not compile, /// it throws an exception. If the method cannot be run or is not found, it throws an exception. /// </summary> /// <param name="opts">The configuration based on which the method is run.</param> /// <returns>The result of invoking the method. If the method is void, the result is set to null.</returns> public object Run(RunOptions opts) { ValidateRunOptions(opts); using (var compileStream = new MemoryStream()) { EmitResult result = cSharpCompilation.Emit(compileStream); if (!result.Success) { throw CompilationError.Build(GetErrors()); } compileStream.Seek(0, SeekOrigin.Begin); Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(compileStream); string namespaceAndClass = $"{opts.GetNamespace()}.{opts.GetClass()}"; var type = assembly.GetType(namespaceAndClass); if (type == null) { throw new RunError( $"Could not find class '{opts.GetClass()}' in namespace '{opts.GetNamespace()}'"); } var members = type.GetMember(opts.GetMethod()); if (members == null || members.Count() == 0) { throw new RunError( $"Could not find method '{opts.GetMethod()}' in class '{opts.GetClass()}' and namespace '{opts.GetNamespace()}'"); } var member = members.First() as MethodInfo; if (member == null) { throw new RunError( $"Could not find method '{opts.GetMethod()}' in class '{opts.GetClass()}' and namespace '{opts.GetNamespace()}'"); } var instance = assembly.CreateInstance(namespaceAndClass); return(member.Invoke(instance, opts.GetArgs())); } }
public static IEnumerable <Type> FilterBy(this IEnumerable <Type> types, RunOptions options) { if (options == null) { return(types); } var filteredTypes = types; var restrictToTypes = new HashSet <string>(options.Filters, StringComparer.OrdinalIgnoreCase); if (restrictToTypes.Any()) { filteredTypes = filteredTypes.Where(x => restrictToTypes.Contains(x.FullName)); } var includeTags = new HashSet <Tag>(options.IncludeTags.Select(tag => new Tag(tag))); var excludeTags = new HashSet <Tag>(options.ExcludeTags.Select(tag => new Tag(tag))); if (includeTags.Any() || excludeTags.Any()) { var extractor = new AttributeTagExtractor(); var filteredTypesWithTags = filteredTypes.Select(type => (Type: type, Tags: extractor.ExtractTags(type))); if (includeTags.Any()) { filteredTypesWithTags = filteredTypesWithTags.Where(x => x.Tags.Intersect(includeTags).Any()); } if (excludeTags.Any()) { filteredTypesWithTags = filteredTypesWithTags.Where(x => !x.Tags.Intersect(excludeTags).Any()); } filteredTypes = filteredTypesWithTags.Select(x => x.Type); } return(filteredTypes); }
public void TestRunOptions() { using (var opt = new RunOptions()) { Assert.NotNull(opt); //verify default options Assert.False(opt.Terminate); Assert.Equal(LogLevel.Verbose, opt.LogVerbosityLevel); Assert.Equal("", opt.LogTag); // try setting options opt.Terminate = true; Assert.True(opt.Terminate); opt.LogVerbosityLevel = LogLevel.Error; Assert.Equal(LogLevel.Error, opt.LogVerbosityLevel); opt.LogTag = "MyLogTag"; Assert.Equal("MyLogTag", opt.LogTag); } }
/// <summary> /// Constructs a cluster proxy from a cluster definition. /// </summary> /// <param name="clusterDefinition">The cluster definition.</param> /// <param name="nodeProxyCreator"> /// The application supplied function that creates a management proxy /// given the node name, public address or FQDN, private address, and /// the node definition. /// </param> /// <param name="appendToLog">Optionally have logs appended to an existing log file rather than creating a new one.</param> /// <param name="defaultRunOptions"> /// Optionally specifies the <see cref="RunOptions"/> to be assigned to the /// <see cref="SshProxy{TMetadata}.DefaultRunOptions"/> property for the /// nodes managed by the cluster proxy. This defaults to <see cref="RunOptions.None"/>. /// </param> /// <remarks> /// The <paramref name="nodeProxyCreator"/> function will be called for each node in /// the cluster definition giving the application the chance to create the node /// proxy using the node's SSH credentials and also to specify logging. A default /// creator that doesn't initialize SSH credentials and logging is used if <c>null</c> /// is passed. /// </remarks> public ClusterProxy( ClusterDefinition clusterDefinition, NodeProxyCreator nodeProxyCreator = null, bool appendToLog = false, RunOptions defaultRunOptions = RunOptions.None) { Covenant.Requires <ArgumentNullException>(clusterDefinition != null); if (nodeProxyCreator == null) { nodeProxyCreator = (name, publicAddress, privateAddress, append) => { var context = KubeHelper.CurrentContext; if (context != null && context.Extension != null) { return(new SshProxy <NodeDefinition>(name, publicAddress, privateAddress, context.Extension.SshCredentials)); } else { // Note that the proxy returned won't actually work because we're not // passing valid SSH credentials. This is useful for situations where // we need a cluster proxy for global things (like managing a hosting // environment) where we won't need access to specific cluster nodes. return(new SshProxy <NodeDefinition>(name, publicAddress, privateAddress, SshCredentials.None)); } }; } this.Definition = clusterDefinition; this.KubeContext = KubeHelper.CurrentContext; this.defaultRunOptions = defaultRunOptions; this.nodeProxyCreator = nodeProxyCreator; this.appendLog = appendToLog; CreateNodes(); }
public IEnumerable <Result> Run( Context context, ISpecificationRunListener listener, RunOptions options, IEnumerable <ICleanupAfterEveryContextInAssembly> globalCleanups, IEnumerable <ISupplementSpecificationResults> resultSupplementers) { listener.OnContextStart(context.GetInfo()); var result = Result.Pass(); if (context.HasExecutableSpecifications) { result = context.EstablishContext(); } var results = result.Passed ? RunSpecifications(context, listener, options, resultSupplementers) : FailSpecifications(context, listener, result, resultSupplementers); if (context.HasExecutableSpecifications) { var cleanupResult = context.Cleanup(); if (!cleanupResult.Passed) { listener.OnFatalError(cleanupResult.Exception); } foreach (var cleanup in globalCleanups) { cleanup.AfterContextCleanup(); } } listener.OnContextEnd(context.GetInfo()); return(results); }
/// <summary> /// Run on 'run' verb, e.g. App.Console.exe run /// </summary> /// <param name="options"></param> /// <returns></returns> private static async Task Run(RunOptions options) { var processSvc = ServiceProvider.GetService <IProcessService>(); switch (options.Action) { case RunAction.AnAction: try { await processSvc.Process(); } catch (Exception e) { _logger?.LogError(e, "Failed to run process"); throw; } break; default: throw new ArgumentOutOfRangeException(); } }
public SPMeta2ProvisionRegresionTestBase() { ModelServiceBase.OnResolveNullModelHandler = (node => new EmptyModelhandler()); RegressionService.EnableDefinitionProvision = true; RegressionService.ProvisionGenerationCount = 2; RegressionService.EnableDefinitionValidation = true; RegressionService.ShowOnlyFalseResults = true; EnablePropertyUpdateValidation = false; PropertyUpdateGenerationCount = 2; TestOptions = new RunOptions(); TestOptions.EnableWebApplicationDefinitionTest = false; TestOptions.EnableSerializeDeserializeAndStillDeployTests = false; TestOptions.EnableContentTypeHubTests = true; TestOptions.EnablWebConfigModificationTest = false; }
public void GivenUnixLikeSystem__WhenRunningWith_OneProject_OneJob_And_RunProgramTask__ShouldRunProgram() { RunOptions options = new RunOptions { BackendXml = true, ConfigPath = "eaw-ci.xml", ProjectName = "pid0", JobName = "My-Job" }; CreateXmlConfigWithTask(EchoTask); StringBuilder stringBuilder = new StringBuilder(); Console.SetOut(new StringWriter(stringBuilder)); EawXBuildApplication sut = new EawXBuildApplication(_services.BuildServiceProvider(), options); sut.Run(); string actual = stringBuilder.ToString().Trim(); Assert.AreEqual("Hello World", actual); }
/// <summary> /// Constructor. Note that you should dispose the instance when you're finished with it. /// </summary> /// <param name="addressOrFQDN">The target XenServer IP address or FQDN.</param> /// <param name="username">The user name.</param> /// <param name="password">The password.</param> /// <param name="name">Optionally specifies the XenServer name.</param> /// <param name="logFolder"> /// The folder where log files are to be written, otherwise or <c>null</c> or /// empty if logging is disabled. /// </param> public XenClient(string addressOrFQDN, string username, string password, string name = null, string logFolder = null) { Covenant.Requires <ArgumentNullException>(!string.IsNullOrEmpty(username)); if (!IPAddress.TryParse(addressOrFQDN, out var address)) { var hostEntry = Dns.GetHostEntry(addressOrFQDN); if (hostEntry.AddressList.Length == 0) { throw new XenException($"[{addressOrFQDN}] is not a valid IP address or fully qualified domain name of a XenServer host."); } address = hostEntry.AddressList.First(); } var logWriter = (TextWriter)null; if (!string.IsNullOrEmpty(logFolder)) { Directory.CreateDirectory(logFolder); logWriter = new StreamWriter(Path.Combine(logFolder, $"XENSERVER-{addressOrFQDN}.log")); } Address = addressOrFQDN; Name = name; SshProxy = new SshProxy <XenClient>(addressOrFQDN, null, address, SshCredentials.FromUserPassword(username, password), logWriter); SshProxy.Metadata = this; runOptions = RunOptions.IgnoreRemotePath; // Initialize the operation classes. Repository = new RepositoryOperations(this); Template = new TemplateOperations(this); Machine = new MachineOperations(this); }
public IEnumerable<Result> Run(Context context, ISpecificationRunListener listener, RunOptions options) { var results = new List<Result>(); listener.OnContextStart(context.GetInfo()); foreach (var specification in context.Specifications) { Result result = Result.Pass(); if (specification.IsExecutable) { result = context.EstablishContext(); } if (result.Passed) { var runner = new SpecificationRunner(listener, options); result = runner.Run(specification); } if (specification.IsExecutable) { var cleanupResult = context.Cleanup(); if (result.Passed && !cleanupResult.Passed) { result = cleanupResult; } } results.Add(result); } listener.OnContextEnd(context.GetInfo()); return results; }
public void Extract_The_Text_From_A_Button() { // arrange var program = new Program(); var dumpFile = Scenario.WinForms.GetDumpFile(); var options = new RunOptions() { DumpLocation = dumpFile.FullName, AdditionalTypes = new[] { typeof(ButtonExtractor), typeof(TestAnalyzer) }, SettingsFile = "Settings/Mortician_Should.json", }; // act CompositionContainer cc = null; var result = program.DefaultExecution(options, container => cc = container); var analyzer = cc.GetExportedValue <TestAnalyzer>(); // assert result.Should().Be(0); analyzer.ButtonText.Should().Be("Hello World"); }
private static int programRun(RunOptions opts) { var inputStream = File.OpenRead(opts.inputFiles.Skip(1).First()); var chip = new FcVirtualChip(); if (opts.memorySize > 0) { chip.memorySize = (uint)opts.memorySize; } chip.initialize(); chip.loadProgram(inputStream); while (chip.state != FcVirtualChip.State.Stopped) { chip.tick(); } if (opts.dump) { Console.WriteLine("== MEMORY DUMP =="); for (var i = 0; i < chip.memory.Length; i++) { Console.Write($"{chip.memory[i]:x2} "); } Console.WriteLine(); Console.WriteLine("== REGISTER DUMP =="); var registerIds = (FcRegister[])Enum.GetValues(typeof(FcRegister)); foreach (var registerId in registerIds) { Console.WriteLine($"{registerId} {chip.registers.Get(registerId):x4}"); } } return(0); }
public void Should_produce_xml() { var plugins = new List <Plugin>(); var options = new RunOptions(); plugins.Add(new Plugin(@"C:\Some\Path\Assembly.dll", "This.Is.Full.Type.Name.For.Class.Implementing.IAutoTestNetTestRunner")); plugins.Add(new Plugin(@"C:\Some\Path\Assembly.dll", "Some.Class.Name")); var runner1 = new RunnerOptions("nunit"); runner1.AddCategories(new string[] { "SomeTestCategory", "SomeOtherTestCategory" }); var assembly1 = new AssemblyOptions(@"C:\my\testassembly.dll"); assembly1.HasBeenVerified(true); assembly1.AddTests(new string[] { "testassembly.class.test1", "testassembly.class.test2" }); assembly1.AddMembers(new string[] { "testassembly.class2", "testassembly.class3" }); assembly1.AddNamespaces(new string[] { "testassembly.somenamespace1", "testassembly.somenamespace2" }); runner1.AddAssemblies(new AssemblyOptions[] { assembly1, new AssemblyOptions(@"C:\my\anothernunitassembly.dll") }); options.AddTestRun(runner1); var runner2 = new RunnerOptions("another"); runner2.AddAssembly(new AssemblyOptions(@"C:\my\other\testassembly.dll")); options.AddTestRun(runner2); var writer = new OptionsXmlWriter(plugins, options); var file = Path.GetTempFileName(); writer.Write(file); var path = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath); var original = File.ReadAllText(file).Replace("\r\n", "\n"); var generated = File.ReadAllText(Path.Combine(path, "TestOptionsCorrected.xml")).Replace("\r\n", "\n"); Assert.That(original, Is.EqualTo(generated)); }
/// <summary> /// Deletes a hive Docker config. /// </summary> /// <param name="configName">The config name.</param> /// <param name="options">Optional command run options.</param> /// <exception cref="HiveException">Thrown if the operation failed.</exception> public void Remove(string configName, RunOptions options = RunOptions.None) { Covenant.Requires <ArgumentException>(HiveDefinition.IsValidName(configName)); var bundle = new CommandBundle("./delete-config.sh"); bundle.AddFile("delete-config.sh", $@"#!/bin/bash docker config inspect {configName} if [ ""$?"" != ""0"" ] ; then echo ""Config doesn't exist."" else docker config rm {configName} fi ", isExecutable: true); var response = hive.GetReachableManager().SudoCommand(bundle, RunOptions.None); if (response.ExitCode != 0) { throw new HiveException(response.ErrorSummary); } }
private static void RunBackup(RunOptions opts) { try { var bcore = LoadCore(); string bsname = GetBackupSetName(opts.BSName, bcore.SrcDependencies); List <(int, string)>?trackclasses; try { trackclasses = Core.ReadTrackClassFile(Path.Combine(GetBUSourceDir(), TrackClassFile)); } catch { trackclasses = null; } bcore.RunBackup(bsname, opts.Message, true, !opts.Scan, trackclasses, new List <string?> { opts.BackupHash }); } catch (Exception e) { Console.WriteLine(e.Message); } }
private static void Run(RunOptions options) { var client = new Client(options.Url, new HttpClient()); while (true) { Console.WriteLine(); Console.Write("> "); var command = Console.ReadLine(); if (command == "EXIT") { break; } Parser.Default .ParseArguments <GetOrdersOptions, NewOrderOptions, AmendOrderOptions, CancelOrderOptions, GetTransactionsOptions>(command.Split(' ')) .WithParsed <GetOrdersOptions>(o => Execute(o, client).Wait()) .WithParsed <NewOrderOptions>(o => Execute(o, client).Wait()) .WithParsed <AmendOrderOptions>(o => Execute(o, client).Wait()) .WithParsed <CancelOrderOptions>(o => Execute(o, client).Wait()) .WithParsed <GetTransactionsOptions>(o => Execute(o, client).Wait()); } }
private static IEnumerable <Result> FailSpecifications(Context context, ISpecificationRunListener listener, RunOptions options, Result result, IEnumerable <ISupplementSpecificationResults> resultSupplementers) { result = resultSupplementers.Aggregate(result, (r, supplement) => supplement.SupplementResult(r)); var results = new List <Result>(); foreach (var specification in context.Specifications) { listener.OnSpecificationStart(specification.GetInfo()); listener.OnSpecificationEnd(specification.GetInfo(), result); results.Add(result); } return(results); }
private static IEnumerable <Result> RunSpecifications(Context context, ISpecificationRunListener listener, RunOptions options, IEnumerable <ISupplementSpecificationResults> resultSupplementers) { var results = new List <Result>(); foreach (var specification in context.Specifications) { var runner = new SpecificationRunner(listener, options, resultSupplementers); var result = runner.Run(specification); results.Add(result); } return(results); }
public IEnumerable <Result> Run(Context context, ISpecificationRunListener listener, RunOptions options, IEnumerable <ICleanupAfterEveryContextInAssembly> globalCleanups, IEnumerable <ISupplementSpecificationResults> resultSupplementers) { IEnumerable <Result> results; listener.OnContextStart(context.GetInfo()); Result result = Result.Pass(); if (context.HasExecutableSpecifications) { result = context.EstablishContext(); } if (result.Passed) { results = RunSpecifications(context, listener, options, resultSupplementers); } else { results = FailSpecifications(context, listener, options, result, resultSupplementers); } if (context.HasExecutableSpecifications) { result = context.Cleanup(); foreach (var cleanup in globalCleanups) { cleanup.AfterContextCleanup(); } } listener.OnContextEnd(context.GetInfo()); return(results); }
public static int Run(RunOptions options) { Process p = Detach(options); p.WaitForExit(); return p.ExitCode; }
private Controller(Action <string> listenCallback, RunOptions runOptions) { listener = new ControllerRunListener(listenCallback); explorer = new AssemblyExplorer(); runner = new DefaultRunner(listener, runOptions, false); }
private void DrawJsonResults(Dictionary <DnsServer, List <DnsResponse> > results, RunOptions options) { var headers = options.Template.ToLowerInvariant().Split(',', StringSplitOptions.RemoveEmptyEntries); var dynamicResults = new List <dynamic>(); foreach (var pair in results) { var server = pair.Key; var responses = pair.Value; foreach (var response in responses) { dynamic expando = new System.Dynamic.ExpandoObject(); foreach (string header in headers) { if (!TemplateHelper.ResponseGetterMap.ContainsKey(header)) { throw new Exception(string.Format(i18n.dug.ER_Unable_Resolve_Header, header)); } try{ object data = TemplateHelper.ResponseGetterMap[header](KeyValuePair.Create(server, response)); ((IDictionary <String, Object>)expando).Add(header, data); } catch { // Most of the time this means the data isnt present (like if they want errorcode but there was no error) } } dynamicResults.Add(expando); } } var jsonResult = JsonSerializer.Serialize(dynamicResults, new JsonSerializerOptions { WriteIndented = true }); Console.WriteLine(jsonResult); }
public MemberRunner(ISpecificationRunListener listener, Assembly assembly, RunOptions options, MemberInfo memberInfo) { try { var runner = new DefaultRunner(listener, options); runner.RunMember(assembly, memberInfo); } catch (Exception err) { listener.OnFatalError(new ExceptionResult(err)); } }
public IEnumerable <Result> Run(Context context, ISpecificationRunListener listener, RunOptions options, IEnumerable <ICleanupAfterEveryContextInAssembly> globalCleanups, IEnumerable <ISupplementSpecificationResults> resultSupplementers) { var results = new List <Result>(); listener.OnContextStart(context.GetInfo()); foreach (var specification in context.Specifications) { Result result = Result.Pass(); if (specification.IsExecutable) { result = context.EstablishContext(); } if (result.Passed) { var runner = new SpecificationRunner(listener, options, resultSupplementers); result = runner.Run(specification); } else { results = FailSpecification(listener, specification, result); } if (specification.IsExecutable) { var cleanupResult = context.Cleanup(); if (result.Passed && !cleanupResult.Passed) { result = cleanupResult; } foreach (var cleanup in globalCleanups) { cleanup.AfterContextCleanup(); } } results.Add(result); } listener.OnContextEnd(context.GetInfo()); return(results); }
public NamespaceRunner(ISpecificationRunListener listener, Assembly assembly, RunOptions options, string targetNamespace) { try { var runner = new DefaultRunner(listener, options); runner.RunNamespace(assembly, targetNamespace); } catch (Exception err) { listener.OnFatalError(new ExceptionResult(err)); } }
public AppDomainRunner(ISpecificationRunListener listener, RunOptions options) { _internalListener = listener; _listener = new RemoteRunListener(listener); _options = options; }
public AssemblyRunner(ISpecificationRunListener listener, Assembly assembly, RunOptions options) { try { var runner = new DefaultRunner(listener, options); runner.RunAssembly(assembly); } catch (Exception err) { listener.OnFatalError(new ExceptionResult(err)); } }
public SpecificationRunner(ISpecificationRunListener listener, RunOptions options) { _listener = listener; _options = options; }
public static void RunCmd(string arguments) { ArrayList bpLocations = null; if (arguments.Length == 0 && g_lastSavedRunCommand != null) { // we have requested to restart the process. // We should kill the existing one. if (Debugger.Processes.HaveActive) { // save locations of current breakpoints foreach (MDbgBreakpoint b in Debugger.Processes.Active.Breakpoints) { if (bpLocations == null) { bpLocations = new ArrayList(); } bpLocations.Add(b.Location); } ExecuteCommand("kill"); } arguments = g_lastSavedRunCommand; } // Parse the arguments. RunOptions options = new RunOptions(arguments); if (options.Application == null) { throw new MDbgShellException("Must specify a program to run"); } else if (!File.Exists(options.Application)) { throw new MDbgShellException("The specified executable \'" + options.Application + "\' could not be found."); } String version = options.Version; // Only happens if no -ver was specified from commandline. if (version == null) { version = MdbgVersionPolicy.GetDefaultLaunchVersion(options.Application); if ((version != null) && (options.Verbosity >= RunVerbosity.High)) { CommandBase.WriteOutput("No version specified with run, defaulting to " + version); } } if ((version != null) && (options.Verbosity >= RunVerbosity.High)) { WriteOutput("Debuggee runtime version will be: " + version); } // get MdbgProcess for that version MDbgProcess p = Debugger.Processes.CreateLocalProcess(new CorDebugger(version)); if (p == null) { throw new MDbgShellException("Could not create debugging interface for runtime version " + version); } p.DebugMode = options.DebugMode; p.CreateProcess(options.Application, options.Arguments); // recreate debugger breakpoints if (bpLocations != null) { foreach (object location in bpLocations) { p.Breakpoints.CreateBreakpoint(location); } } p.Go().WaitOne(); g_lastSavedRunCommand = arguments; Shell.DisplayCurrentLocation(); }
public Controller(Action <string> listenCallback, string runOptions) : this(listenCallback, RunOptions.Parse(runOptions)) { }
public NamespaceRunner(ISpecificationRunListener listener, Assembly assembly, RunOptions options, string targetNamespace) { var runner = new DefaultRunner(listener, options); runner.RunNamespace(assembly, targetNamespace); }
public static Process Detach(RunOptions options) { Console.WriteLine("InstallerEditor: {0}", Executable); return(Detach(Executable, options.CommandLineArgs)); }
public SpecificationRunner(ISpecificationRunListener listener, RunOptions options, IEnumerable<ISupplementSpecificationResults> resultSupplementers) { _listener = listener; _options = options; _resultSupplementers = resultSupplementers; }
private void DrawCsvResults(Dictionary <DnsServer, List <DnsResponse> > results, RunOptions options) { var headers = options.Template.ToLowerInvariant().Split(',', StringSplitOptions.RemoveEmptyEntries); var csvResults = new List <string>(); foreach (var pair in results) { var server = pair.Key; var responses = pair.Value; foreach (var response in responses) { List <string> responseResults = new List <string>(); foreach (string header in headers) { if (!TemplateHelper.ResponseGetterMap.ContainsKey(header)) { throw new Exception(string.Format(i18n.dug.ER_Unable_Resolve_Header, header)); } try{ string dataString = TemplateHelper.ResponseGetterMap[header](KeyValuePair.Create(server, response)).ToString(); dataString = dataString.Replace(Environment.NewLine, "\\n").Replace(",", string.Empty); //Cant have real newlines or rogue commas in the csv output... responseResults.Add(dataString); } catch { responseResults.Add(string.Empty); // Most of the time this means the data isnt present (like if they want errorcode but there was no error) } } csvResults.Add(string.Join(',', responseResults)); } } foreach (var result in csvResults) { Console.WriteLine(result); } }
public static IEnumerable<Context> FilteredBy(this IEnumerable<Context> contexts, RunOptions options) { var results = contexts; if (options.Filters.Any()) { var includeFilters = options.Filters; results = results.Where(x => includeFilters.Any(filter => StringComparer.OrdinalIgnoreCase.Equals(filter, x.Type.FullName))); } if (options.IncludeTags.Any()) { var tags = options.IncludeTags.Select(tag => new Tag(tag)); results = results.Where(x => x.Tags.Intersect(tags).Any()); } if (options.ExcludeTags.Any()) { var tags = options.ExcludeTags.Select(tag => new Tag(tag)); results = results.Where(x => !x.Tags.Intersect(tags).Any()); } return results; }
private static void RunNode(RunOptions options) { using var app = new Application(options.ConfigPath, options); app.Start(options); }
public static int Run(RunOptions options) { return Run(options, new TimeSpan(-1)); }
/// <summary> /// Runs the external program. /// </summary> /// <param name="app">Program filename.</param> /// <param name="commandLine">Commandline</param> /// <param name="input">Optional Input for the program (will be provided as stdin)</param> /// <param name="workspace">Optional custom workspace directory. Use null to keep the same directory.</param> /// <param name="options">Defines the options how to run. See RunOptions.</param> /// <param name="envVars">Custom environment variables to pass to the child process.</param> /// <returns>The exit code of the program.</returns> public static int Run(string app, string commandLine = null, string input = null, string workspace = null, RunOptions options = RunOptions.Default, Dictionary <string, string> envVars = null) { // Check if the application exists, including the PATH directories. if (options.HasFlag(RunOptions.AppMustExist) && !File.Exists(app)) { bool existsInPath = false; if (!app.Contains(Path.DirectorySeparatorChar) && !app.Contains(Path.AltDirectorySeparatorChar)) { string[] pathDirectories = Environment.GetEnvironmentVariable("PATH").Split(Path.PathSeparator); foreach (string pathDirectory in pathDirectories) { string tryApp = Path.Combine(pathDirectory, app); if (File.Exists(tryApp)) { app = tryApp; existsInPath = true; break; } } } if (!existsInPath) { throw new Exception(string.Format("Couldn't find the executable to run: {0}", app)); } } Stopwatch stopwatch = Stopwatch.StartNew(); if (!options.HasFlag(RunOptions.NoLoggingOfRunCommand)) { Log.Verbose("Running: " + app + " " + (string.IsNullOrEmpty(commandLine) ? "" : commandLine)); } bool redirectStdOut = (options & RunOptions.NoStdOutRedirect) != RunOptions.NoStdOutRedirect; Process proc = new Process(); proc.StartInfo.FileName = app; proc.StartInfo.Arguments = string.IsNullOrEmpty(commandLine) ? "" : commandLine; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = input != null; proc.StartInfo.CreateNoWindow = true; if (workspace != null) { proc.StartInfo.WorkingDirectory = workspace; } if (redirectStdOut) { proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.OutputDataReceived += StdOut; proc.ErrorDataReceived += StdErr; } if (envVars != null) { foreach (var env in envVars) { if (env.Key == "PATH") { proc.StartInfo.EnvironmentVariables[env.Key] = proc.StartInfo.EnvironmentVariables[env.Key] + ';' + env.Value; } else { proc.StartInfo.EnvironmentVariables[env.Key] = env.Value; } } } if ((options & RunOptions.UTF8Output) == RunOptions.UTF8Output) { proc.StartInfo.StandardOutputEncoding = new UTF8Encoding(false, false); } proc.Start(); if (redirectStdOut) { proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); } if (string.IsNullOrEmpty(input) == false) { proc.StandardInput.WriteLine(input); proc.StandardInput.Close(); } if (!options.HasFlag(RunOptions.NoWaitForExit)) { proc.WaitForExit(); } int result = -1; if (!options.HasFlag(RunOptions.NoWaitForExit)) { stopwatch.Stop(); result = proc.ExitCode; if (!options.HasFlag(RunOptions.NoLoggingOfRunCommand) || options.HasFlag(RunOptions.NoLoggingOfRunDuration)) { Log.Info(string.Format("Took {0}s to run {1}, ExitCode={2}", stopwatch.Elapsed.TotalSeconds, Path.GetFileName(app), result)); } } return(result); }
public static Process Detach(RunOptions options) { Console.WriteLine("dotNetInstaller: {0}", Executable); return Detach(Executable, options.CommandLineArgs); }
public static int Run(string configFile) { RunOptions options = new RunOptions(configFile); return Run(options); }
public DefaultRunner(ISpecificationRunListener listener, RunOptions options) : this(listener, options, true) { }