T IQueryExecutor.ExecuteScalar <T>(QueryModel queryModel) { var mapping = _schema.MappingFor(queryModel.SelectClause.Selector.Type); var documentQuery = new DocumentQuery(mapping, queryModel); _schema.EnsureStorageExists(mapping.DocumentType); if (queryModel.ResultOperators.OfType <AnyResultOperator>().Any()) { var anyCommand = documentQuery.ToAnyCommand(); return(_runner.Execute(conn => { anyCommand.Connection = conn; return (T)anyCommand.ExecuteScalar(); })); } if (queryModel.ResultOperators.OfType <CountResultOperator>().Any()) { var countCommand = documentQuery.ToCountCommand(); return(_runner.Execute(conn => { countCommand.Connection = conn; var returnValue = countCommand.ExecuteScalar(); return Convert.ToInt32(returnValue).As <T>(); })); } throw new NotSupportedException(); }
T IQueryExecutor.ExecuteScalar <T>(QueryModel queryModel) { if (queryModel.ResultOperators.OfType <AnyResultOperator>().Any()) { var storage = _schema.StorageFor(queryModel.SelectClause.Selector.Type); var anyCommand = storage.AnyCommand(queryModel); return(_runner.Execute(conn => { anyCommand.Connection = conn; return (T)anyCommand.ExecuteScalar(); })); } if (queryModel.ResultOperators.OfType <CountResultOperator>().Any()) { var storage = _schema.StorageFor(queryModel.SelectClause.Selector.Type); var countCommand = storage.CountCommand(queryModel); return(_runner.Execute(conn => { countCommand.Connection = conn; var returnValue = countCommand.ExecuteScalar(); return Convert.ToInt32(returnValue).As <T>(); })); } throw new NotSupportedException(); }
public void Restore(string pathToProjectFile, string[] packageSources) { ExtractNugetExecutable(); var packageSourcesArgument = CreatePackageSourcesArguments(); int exitcode = 0; if (_scriptEnvironment.IsWindows) { exitcode = _commandRunner.Execute(PathToNuget, $"restore {pathToProjectFile} {packageSourcesArgument}"); } else { exitcode = _commandRunner.Execute("mono", $"{PathToNuget} restore \"{pathToProjectFile}\" {packageSourcesArgument}"); } if (exitcode != 0) { // We must throw here, otherwise we may incorrectly run with the old 'project.assets.json' throw new Exception($"Unable to restore packages from '{pathToProjectFile}'. Make sure that all script files contains valid NuGet references"); } string CreatePackageSourcesArguments() { return(packageSources.Length == 0 ? string.Empty : packageSources.Select(s => $"-Source {s}") .Aggregate((current, next) => $"{current} {next}")); } }
public void SetPosition(int position) { _runner.Execute(new KnobPositionSetCommand() { Position = position }); }
public void RegisterFileHandler() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // register dotnet-script as the tool to process .csx files _commandRunner.Execute("reg", @"add HKCU\Software\classes\.csx /f /ve /t REG_SZ /d metatool"); _commandRunner.Execute("reg", $@"add HKCU\Software\Classes\metatool\Shell\Open\Command /f /ve /t REG_EXPAND_SZ /d ""\""%MetatoolDir%\Metatool.exe\"" \""%1\"" -- %*"""); } }
public void Restore(string pathToProjectFile) { ExtractNugetExecutable(); if (RuntimeHelper.IsWindows()) { _commandRunner.Execute(PathToNuget, $"restore {pathToProjectFile}"); } else { _commandRunner.Execute("mono", $"{PathToNuget} restore \"{pathToProjectFile}\""); } }
public void Restore(string pathToProjectFile) { ExtractNugetExecutable(); if (_scriptEnvironment.IsWindows) { _commandRunner.Execute(PathToNuget, $"restore {pathToProjectFile}"); } else { _commandRunner.Execute("mono", $"{PathToNuget} restore \"{pathToProjectFile}\""); } }
/// <summary> /// turn the servo on /// </summary> public void On() { _runner.Execute(new ServoOnCommand() { ServoID = _servoID }); }
public IEnumerable <string> SchemaTableNames() { return(_runner.Execute(conn => { var table = conn.GetSchema("Tables"); var tables = new List <string>(); foreach (DataRow row in table.Rows) { tables.Add(row[2].ToString()); } return tables.Where(name => name.StartsWith("mt_")).ToArray(); })); }
public void CreateExecutable <TReturn, THost>(ScriptContext context, LogFactory logFactory, string runtimeIdentifier, string executableFileName = null) { if (runtimeIdentifier == null) { throw new ArgumentNullException(nameof(runtimeIdentifier)); } executableFileName = executableFileName ?? Path.GetFileNameWithoutExtension(context.FilePath); const string AssemblyName = "scriptAssembly"; var tempProjectPath = ScriptProjectProvider.GetPathToProjectFile(Path.GetDirectoryName(context.FilePath), ScriptEnvironment.Default.TargetFramework); var renamedProjectPath = ScriptProjectProvider.GetPathToProjectFile(Path.GetDirectoryName(context.FilePath), ScriptEnvironment.Default.TargetFramework, executableFileName); var tempProjectDirectory = Path.GetDirectoryName(tempProjectPath); var scriptAssemblyPath = CreateScriptAssembly <TReturn, THost>(context, tempProjectDirectory, AssemblyName); var projectFile = new ProjectFile(File.ReadAllText(tempProjectPath)); projectFile.PackageReferences.Add(new PackageReference("Microsoft.CodeAnalysis.Scripting", ScriptingVersion)); projectFile.AssemblyReferences.Add(new AssemblyReference(scriptAssemblyPath)); projectFile.Save(renamedProjectPath); CopyProgramTemplate(tempProjectDirectory); var commandRunner = new CommandRunner(logFactory); // todo: may want to add ability to return dotnet.exe errors var exitcode = commandRunner.Execute("dotnet", $"publish \"{renamedProjectPath}\" -c Release -r {runtimeIdentifier} -o \"{context.WorkingDirectory}\" {(ScriptEnvironment.Default.TargetFramework == "netcoreapp3.0" ? "/p:PublishSingleFile=true" : "")} /p:DebugType=Embedded"); if (exitcode != 0) { throw new Exception($"dotnet publish failed with result '{exitcode}'"); } _scriptConsole.WriteSuccess($"Published {context.FilePath} (executable) to {context.WorkingDirectory}"); }
public void Execute_should_throw_error_if_command_is_not_found() { var sut = new CommandRunner(new ITcxEditorCommand[] { new CommandA() }); Assert.Throws <CommandNotFoundException>( () => sut.Execute(new InputB())); }
public IEnumerable <CompilationReference> Read(ProjectFileInfo projectFile) { const string outputDirectory = "compilation"; var workingDirectory = Path.GetDirectoryName(projectFile.Path); if (!Directory.Exists(Path.Combine(workingDirectory, outputDirectory))) { Directory.CreateDirectory(Path.Combine(workingDirectory, outputDirectory)); } // Copy the csproj file so that we don't interfere with the project.assets.json file // used for execution. string pathToCompilationProjectFile = Path.Combine(workingDirectory, outputDirectory, Path.GetFileName(projectFile.Path)); File.Copy(projectFile.Path, pathToCompilationProjectFile, true); // We remove any third party package references since we are only after the framework assemblies here. RemovePackageReferences(pathToCompilationProjectFile); var referencePathsFile = Path.Combine(workingDirectory, outputDirectory, "ReferencePaths.txt"); if (File.Exists(referencePathsFile)) { File.Delete(referencePathsFile); } var exitCode = _commandRunner.Execute("dotnet", $"build \"{pathToCompilationProjectFile}\" /p:OutputType=Library -o {outputDirectory}", workingDirectory); if (exitCode != 0) { throw new Exception($"Unable to read compilation dependencies for '{projectFile.Path}'. Make sure that all script files contains valid NuGet references"); } var referenceAssemblies = File.ReadAllLines(referencePathsFile); var compilationReferences = referenceAssemblies.Select(ra => new CompilationReference(ra)).ToArray(); return(compilationReferences); }
public void CreateExecutable <TReturn, THost>(ScriptContext context, LogFactory logFactory, string runtimeIdentifier) { if (runtimeIdentifier == null) { throw new ArgumentNullException(nameof(runtimeIdentifier)); } const string AssemblyName = "scriptAssembly"; var tempProjectPath = ScriptProjectProvider.GetPathToProjectFile(Path.GetDirectoryName(context.FilePath)); var tempProjectDirectory = Path.GetDirectoryName(tempProjectPath); var scriptAssemblyPath = CreateScriptAssembly <TReturn, THost>(context, tempProjectDirectory, AssemblyName); var projectFile = new ProjectFile(File.ReadAllText(tempProjectPath)); projectFile.PackageReferences.Add(new PackageReference("Microsoft.CodeAnalysis.Scripting", ScriptingVersion)); projectFile.AssemblyReferences.Add(new AssemblyReference(scriptAssemblyPath)); projectFile.Save(tempProjectPath); CopyProgramTemplate(tempProjectDirectory); var commandRunner = new CommandRunner(logFactory); // todo: may want to add ability to return dotnet.exe errors var exitcode = commandRunner.Execute("dotnet", $"publish \"{tempProjectPath}\" -c Release -r {runtimeIdentifier} -o {context.WorkingDirectory}"); if (exitcode != 0) { throw new Exception($"dotnet publish failed with result '{exitcode}'"); } _scriptConsole.WriteSuccess($"Published {context.FilePath} (executable) to {context.WorkingDirectory}"); }
public void try_command_runner() { var builder = new SchemaBuilder(); builder.CreateTable(typeof(SchemaBuilderTests.MySpecialDocument), typeof(Guid)); builder.DefineUpsert(typeof (SchemaBuilderTests.MySpecialDocument), typeof(Guid)); var id = Guid.NewGuid(); using (var runner = new CommandRunner(ConnectionSource.ConnectionString)) { runner.Execute(builder.ToSql()); /* runner.Execute("mt_upsert_myspecialdocument", command => { command.Parameters.Add("docId", NpgsqlDbType.Uuid).Value = id; command.Parameters.Add("doc", NpgsqlDbType.Json).Value = "{\"id\":\"1\"}"; }); runner.Execute("mt_upsert_myspecialdocument", command => { command.Parameters.Add("docId", NpgsqlDbType.Uuid).Value = id; command.Parameters.Add("doc", NpgsqlDbType.Json).Value = "{\"id\":\"2\"}"; }); * */ //runner.DescribeSchema(); runner.SchemaFunctionNames().Each(x => Debug.WriteLine(x)); } }
public void CreateExecutable(ScriptContext context, LogFactory logFactory) { var tempProjectPath = _scriptProjectProvider.CreateProjectForScriptFile(context.FilePath); var tempProjectDirecory = Path.GetDirectoryName(tempProjectPath); var scriptAssemblyPath = CreateScriptAssembly(context, tempProjectDirecory); var projectFile = new ProjectFile(File.ReadAllText(tempProjectPath)); projectFile.AddPackageReference(new PackageReference("Microsoft.CodeAnalysis.Scripting", ScriptingVersion, PackageOrigin.ReferenceDirective)); projectFile.AddAssemblyReference(scriptAssemblyPath); projectFile.Save(tempProjectPath); CopyProgramTemplate(tempProjectDirecory); var runtimeIdentifier = _scriptEnvironment.RuntimeIdentifier; var commandRunner = new CommandRunner(logFactory); // todo: may want to add ability to return dotnet.exe errors var exitcode = commandRunner.Execute("dotnet", $"publish \"{tempProjectPath}\" -c Release -r {runtimeIdentifier} -o {context.WorkingDirectory}"); if (exitcode != 0) { throw new Exception($"dotnet publish failed with result '{exitcode}'"); } }
public void Restore(ProjectFileInfo projectFileInfo, string[] packageSources) { var packageSourcesArgument = CreatePackageSourcesArguments(); var configFileArgument = CreateConfigFileArgument(); var runtimeIdentifier = _scriptEnvironment.RuntimeIdentifier; var workingDirectory = Path.GetFullPath(Path.GetDirectoryName(projectFileInfo.Path)); _logger.Debug($"Restoring {projectFileInfo.Path} using the dotnet cli. RuntimeIdentifier : {runtimeIdentifier} NugetConfigFile: {projectFileInfo.NuGetConfigFile}"); var exitcode = _commandRunner.Execute("dotnet", $"restore \"{projectFileInfo.Path}\" -r {runtimeIdentifier} {packageSourcesArgument} {configFileArgument}", workingDirectory); if (exitcode != 0) { // We must throw here, otherwise we may incorrectly run with the old 'project.assets.json' throw new Exception($"Unable to restore packages from '{projectFileInfo.Path}'. Make sure that all script files contains valid NuGet references"); } string CreatePackageSourcesArguments() { return(packageSources.Length == 0 ? string.Empty : packageSources.Select(s => $"-s {s}") .Aggregate((current, next) => $"{current} {next}")); } string CreateConfigFileArgument() { return(string.IsNullOrWhiteSpace(projectFileInfo.NuGetConfigFile) ? string.Empty : $"--configfile \"{projectFileInfo.NuGetConfigFile}\""); } }
public void SimplePublishTest() { using (var workspaceFolder = new DisposableFolder()) { var code = @"WriteLine(""hello world"");"; var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); File.WriteAllText(mainPath, code); var publishResult = ScriptTestRunner.Default.Execute($"publish {mainPath}", workspaceFolder.Path); Assert.Equal(0, publishResult.exitCode); var exePath = Path.Combine(workspaceFolder.Path, "publish", _scriptEnvironment.RuntimeIdentifier, "script"); var executableRunResult = _commandRunner.Execute(exePath); Assert.Equal(0, executableRunResult); } }
public void SimplePublishTest() { using (var scriptFolder = new DisposableFolder()) { var code = @"WriteLine(""hello world"");"; var mainPath = Path.Combine(scriptFolder.Path, "main.csx"); File.WriteAllText(mainPath, code); var args = new string[] { "publish", mainPath }; var publishResult = Execute(string.Join(" ", args), scriptFolder.Path); Assert.Equal(0, publishResult.exitCode); var exePath = Path.Combine(scriptFolder.Path, "publish", "script"); var executableRunResult = _commandRunner.Execute(exePath); Assert.Equal(0, executableRunResult); } }
public void Execute_should_work_multiple_times_with_multiple_commands() { var sut = new CommandRunner( new ITcxEditorCommand[] { new CommandA(), new CommandB() }); var result1 = sut.Execute(new InputB()) as OutputB; var result2 = sut.Execute(new InputA()) as OutputA; var result3 = sut.Execute(new InputA()) as OutputA; var result4 = sut.Execute(new InputB()) as OutputB; var result5 = sut.Execute(new InputB()) as OutputB; result1.Val.ShouldBe("B1"); result2.Val.ShouldBe("A1"); result3.Val.ShouldBe("A2"); result4.Val.ShouldBe("B2"); result5.Val.ShouldBe("B3"); }
public void CreateSchema(IDocumentSchema schema, DocumentMapping mapping) { var writer = new StringWriter(); mapping.WriteSchemaObjects(schema, writer); _runner.Execute(writer.ToString()); }
/// <summary> /// play a series of notes /// </summary> /// <param name="notes">format [note:A-F][#][octave:1-7][duration:1-128] ex. D#5-8,C,A-4,R</param> public void PlayNotes(string notes = null) { _runner.Execute(new SoundPlayNotesCommand() { Notes = notes }); }
/// <summary> /// turn the Led on /// <param name="color">the color to display</param> /// </summary> public void On(LedColor?color = null) { _runner.Execute(new LedOnCommand() { Color = color }); }
public void Execute_should_return_response_of_command() { var sut = new CommandRunner( new ITcxEditorCommand[] { new CommandA() }); var result = sut.Execute(new InputA()) as OutputA; result.Val.ShouldBe("A1"); }
private void RunCommand(CommandRunner commandRunner, string msBuildCommand) { var arguments = BuildArguments(); commandRunner.Execute(msBuildCommand, arguments); ShowOutput(commandRunner.StandardOutput, " "); ShowOutput(commandRunner.StandardError, "(EE)"); }
static void Main(string[] args) { var commandParser = new CommandParser(); var command = commandParser.Parse(); var moduleRunner = new ModuleRunner(); moduleRunner.Execute(command); var commandRunner = new CommandRunner(); commandRunner.Execute(command); }
public HiLoSequenceTests() { _container.GetInstance<DocumentCleaner>().CompletelyRemoveAll(); var sql = SchemaBuilder.GetText("mt_hilo"); _runner = _container.GetInstance<CommandRunner>(); _runner.Execute(sql); theSequence = new HiLoSequence(_runner, "foo", new HiloDef()); }
public static void CleanBasicDocuments() { var runner = new CommandRunner(new ConnectionSource()); runner.Execute("DROP TABLE IF EXISTS {0} CASCADE;".ToFormat(SchemaBuilder.TableNameFor(typeof (User)))); runner.Execute("DROP TABLE IF EXISTS {0} CASCADE;".ToFormat(SchemaBuilder.TableNameFor(typeof (Issue)))); runner.Execute("DROP TABLE IF EXISTS {0} CASCADE;".ToFormat(SchemaBuilder.TableNameFor(typeof (Company)))); runner.Execute("DROP TABLE IF EXISTS {0} CASCADE;".ToFormat(SchemaBuilder.TableNameFor(typeof (Target)))); runner.Execute("DROP FUNCTION if exists {0}(docId UUID, doc JSON)".ToFormat(SchemaBuilder.UpsertNameFor(typeof(User)))); runner.Execute("DROP FUNCTION if exists {0}(docId UUID, doc JSON)".ToFormat(SchemaBuilder.UpsertNameFor(typeof(Issue)))); runner.Execute("DROP FUNCTION if exists {0}(docId UUID, doc JSON)".ToFormat(SchemaBuilder.UpsertNameFor(typeof(Company)))); runner.Execute("DROP FUNCTION if exists {0}(docId UUID, doc JSON)".ToFormat(SchemaBuilder.UpsertNameFor(typeof(Target)))); }
public void Restore(string pathToProjectFile) { _logger.Debug($"Restoring {pathToProjectFile} using the dotnet cli."); var exitcode = _commandRunner.Execute("dotnet", $"restore \"{pathToProjectFile}\""); if (exitcode != 0) { // We must throw here, otherwise we may incorrectly run with the old 'project.assets.json' throw new Exception($"Unable to restore packages from '{pathToProjectFile}'. Make sure that all script files contains valid NuGet references"); } }
public void Execute_should_pass_input_to_command() { CommandA commandASpy = new CommandA(); var sut = new CommandRunner( new ITcxEditorCommand[] { commandASpy }); InputA input = new InputA(); sut.Execute(input); commandASpy.LastInput.ShouldBeSameAs(input); }
public void SimplePublishTest() { using (var workspaceFolder = new DisposableFolder()) { var code = @"WriteLine(""hello world"");"; var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); File.WriteAllText(mainPath, code); var publishResult = ScriptTestRunner.Default.Execute($"publish {mainPath}", workspaceFolder.Path); Assert.Equal(0, publishResult.exitCode); var exePath = Path.Combine(workspaceFolder.Path, "publish", _scriptEnvironment.RuntimeIdentifier, "main"); var executableRunResult = _commandRunner.Execute(exePath); Assert.Equal(0, executableRunResult); var publishedFiles = Directory.EnumerateFiles(Path.Combine(workspaceFolder.Path, "publish", _scriptEnvironment.RuntimeIdentifier)); if (_scriptEnvironment.NetCoreVersion.Major >= 3) { Assert.True(publishedFiles.Count() == 1, "There should be only a single published file"); } else { Assert.True(publishedFiles.Count() > 1, "There should be multiple published files"); } } }
public void SimplePublishTest() { using (var workspaceFolder = new DisposableFolder()) { var code = @"WriteLine(""hello world"");"; var mainPath = Path.Combine(workspaceFolder.Path, "main.csx"); File.WriteAllText(mainPath, code); var publishResult = ScriptTestRunner.Default.Execute($"publish {mainPath}", workspaceFolder.Path); Assert.Equal(0, publishResult.exitCode); var exePath = Path.Combine(workspaceFolder.Path, "publish", _scriptEnvironment.RuntimeIdentifier, "script"); var executableRunResult = _commandRunner.Execute(exePath); Assert.Equal(0, executableRunResult); #if NETCOREAPP3_0 var publishedFiles = Directory.EnumerateFiles(Path.Combine(workspaceFolder.Path, "publish", _scriptEnvironment.RuntimeIdentifier)); Assert.True(1 == publishedFiles.Count(), "There should be only a single published file on .NET Core 3.0"); #endif } }
public void try_it_out() { var runner = new CommandRunner(new ConnectionSource()); runner.Execute(conn => { var table = conn.GetSchema("Tables"); foreach (DataRow row in table.Rows) { Debug.WriteLine("{0} / {1} / {2}", row[0], row[1], row[2]); } }); }
public NUnit.Framework.Api.ITestResult Run(ITestListener listener, ITestFilter filter) { if (settings.Contains("WorkDirectory")) { TestExecutionContext.CurrentContext.WorkDirectory = (string)settings["WorkDirectory"]; } else { TestExecutionContext.CurrentContext.WorkDirectory = Environment.CurrentDirectory; } TestCommand testCommand = loadedTest.GetTestCommand(filter); return(CommandRunner.Execute(testCommand)); }
public void CreateNewScriptFile(string fileName, string currentDirectory) { _scriptConsole.WriteNormal($"Creating '{fileName}'"); if (!Path.HasExtension(fileName)) { fileName = Path.ChangeExtension(fileName, ".csx"); } var pathToScriptFile = Path.Combine(currentDirectory, fileName); if (!File.Exists(pathToScriptFile)) { var scriptFileTemplate = TemplateLoader.ReadTemplate("helloworld.csx.template"); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { // add a shebang to set dotnet-script as the interpreter for .csx files // and make sure we are using environment newlines, because shebang won't work with windows cr\lf scriptFileTemplate = $"#!/usr/bin/env dotnet-script" + Environment.NewLine + scriptFileTemplate.Replace("\r\n", Environment.NewLine); } File.WriteAllText(pathToScriptFile, scriptFileTemplate, new UTF8Encoding(false /* Linux shebang can't handle BOM */)); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { // mark .csx file as executable, this activates the shebang to run dotnet-script as interpreter _commandRunner.Execute($"/bin/chmod", $"+x {pathToScriptFile}"); } _scriptConsole.WriteSuccess($"...'{pathToScriptFile}' [Created]"); } else { _scriptConsole.WriteHighlighted($"...'{pathToScriptFile}' already exists [Skipping]"); } }