Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Build automation system for .NET

License

NotificationsYou must be signed in to change notification settings

DevTeam/csharp-interactive

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NuGet csiGitHubGitHub Build

C# interactive build automation system makes it easy to build .NET projects. It can be part of your solution as a regular .NET console project or run C# scripts without compiling them, or even run in REPL mode - allowing you to run C# interactively.

Key Features

✔️ Three IntegratedExecution Modes

Flexible interoperability between modes for diverse workflow requirements.

✔️ Native Cross-Platform Support

Seamless operation across Windows, Linux, and macOS environments.

✔️ Debugging Support

Ability to debug in “.NET build project” mode, allowing developers to efficiently identify and fix problems during the compilation and build process.

✔️ Zero Abstraction Constraints

No restrictive abstractions (e.g., Tasks, Targets, DependsOn) to limit script design:

  • Pure .NET codebase – no proprietary syntax or hidden layers
  • Adheres to industry-standard coding practices for maintainability

✔️ Powerful API for building .NET projects

Granular control over builds, tests, and deployments with streamlined project configuration.

✔️ Summarised statistics

Consolidated build statistics.

Operating modes

Interactive

REPL (Read-Eval-Print-Loop) interface for interactive code evaluation. Please seethis page for installation details.

Launch the tool in the interactive mode:

dotnet csi

Simply enter C# commands sequentially one line after another and get the result in console output.

Running C# script

Direct execution of C# scripts without prior compilation:

  • Zero-Compilation Workflow - execute .csx files directly using Roslyn scripting engines, bypassing traditional dotnet build steps for rapid iteration.
  • Cross-Platform Scripting
    • Windows - integrate with PowerShell/PowerShell Core automation pipelines
    • Linux/macOS - combine with bash/zsh scripts via shebang directives (#!/usr/bin/env dotnet-script)
    • Dependency Management - resolve NuGet packages in scripts via #r "nuget: PackageName/Version" syntax, with local cache optimization.

Run a specified script with a given argument:

dotnet csi ./MyDirectory/hello.csx World

Run a single script located in theMyDirectory directory:

dotnet csi ./MyDirectory World
Usage details
dotnet csi [options] [--] [script] [script arguments]

Executes a script if specified, otherwise launches an interactive REPL (Read Eval Print Loop).

-- - Indicates that the remaining arguments should not be treated as options.

script - The path to the script file to run. If no such file is found, the command will treat it as a directory and look for a single script file inside that directory.

script arguments - Script arguments are accessible in a script via the global listArgs[index] by an argument index.

@file - Read the response file for more options.

Supported options:

OptionDescriptionAlternative form
--helpShow how to use the command./?,-h,/h,/help
--versionDisplay the tool version./version
--sourceSpecify the NuGet package source to use. Supported formats: URL, or a UNC directory path.-s,/s,/source
--property <key=value>Define a key-value pair(s) for the script properties calledProps, which is accessible in scripts.-p,/property,/p
--property:<key=value>Define a key-value pair(s) in MSBuild style for the script properties calledProps, which is accessible in scripts.-p:<key=value>,/property:<key=value>,/p:<key=value>,--property:key1=val1;key2=val2
.NET build project

Seamless integration into existing solutions as a standard .NET console project. Please seethis page for details on how to install theproject template.

Create a console projectBuild containing a script from the templatebuild

dotnet new build -o ./Build

The created project contains 2 entry points:

  • Program.csx to run as a script
    dotnet csi ./Build
  • Program.cs to run as .NET application
    dotnet run --project ./Build

NuGet packages

Package nameLinkDescriptionInstallation
dotnet-csiNuGetInteractive .NET tool for REPL and running scriptsdotnet tool install --global dotnet-csi
CSharpInteractive.TemplatesNuGet.NET build project templatedotnet new install CSharpInteractive.Templates
CSharpInteractiveNuGetA library for use in .NET build projectsdotnet add package CSharpInteractive

Usage examples

API

Output, logging and tracing

Writing a line to a build log

WriteLine("Hello");

Writing a line highlighted with "Header" color to a build log

WriteLine("Hello",Header);WriteLine("Hello ".WithColor(Header),"world!");

Writing an empty line to a build log

WriteLine();

Registering errors in the build log

Error("Error info");Error("Error info","Error identifier");Error("Error: ".WithColor(),"datails".WithColor(Color.Details));

Registering warnings in the build log

Warning("Warning info");Warning("Warning ","info".WithColor(Color.Details));

Registering a summary in the build log

Summary("Summary message");Summary("Summary ","message".WithColor(Color.Details));

Registering information in the build log

Info("Some info");Info("Some ","info".WithColor(Color.Details));

Registering trace information in the build log

Trace("Some trace info");Trace("Some trace ","info".WithColor(Color.Details));

Arguments and parameters

Command line arguments

Args have got from the script arguments.

if(Args.Count>0){WriteLine(Args[0]);}if(Args.Count>1){WriteLine(Args[1]);}

Using properties

WriteLine(Props["version"]);WriteLine(Props.Get("configuration","Release"));// Some CI/CDs have integration of these properties.// For example in TeamCity this property with all changes will be available in the next TeamCity steps.Props["version"]="1.1.6";

Microsoft DI

Using the Host property

Host is actually the provider of all global properties and methods.

varpackages=Host.GetService<INuGet>();Host.WriteLine("Hello");

Getting services

This method might be used to get access to different APIs likeINuGet orICommandLine.

GetService<INuGet>();varserviceProvider=GetService<IServiceProvider>();serviceProvider.GetService(typeof(INuGet));

Besides that, it is possible to get an instance ofSystem.IServiceProvider to access APIs.

Using service collections

publicvoidRun(){varserviceProvider=GetService<IServiceCollection>().AddTransient<MyTask>().BuildServiceProvider();varmyTask=serviceProvider.GetRequiredService<MyTask>();varexitCode=myTask.Run();exitCode.ShouldBe(0);}privateclassMyTask(ICommandLineRunnerrunner){publicint?Run()=>runner.Run(newCommandLine("whoami")).EnsureSuccess().ExitCode;}

NuGet

Restoring a NuGet package of newest version

usingHostApi;IEnumerable<NuGetPackage>packages=GetService<INuGet>().Restore(newNuGetRestoreSettings("IoC.Container").WithVersionRange(VersionRange.All));

Restoring a NuGet package by a version range for the specified .NET and path

usingHostApi;varpackagesPath=Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString()[..4]);varsettings=newNuGetRestoreSettings("IoC.Container").WithVersionRange(VersionRange.Parse("[1.3, 1.3.8)")).WithTargetFrameworkMoniker("net5.0").WithPackagesPath(packagesPath);IEnumerable<NuGetPackage>packages=GetService<INuGet>().Restore(settings);

Command Line

Building custom command lines

usingHostApi;// Creates and run a simple command line"whoami".AsCommandLine().Run().EnsureSuccess();// Creates and run a simple command linenewCommandLine("whoami").Run().EnsureSuccess();// Creates and run a command line with argumentsnewCommandLine("cmd","/c","echo","Hello").Run();// Same as previous statementnewCommandLine("cmd","/c").AddArgs("echo","Hello").Run().EnsureSuccess();(newCommandLine("cmd")+"/c"+"echo"+"Hello").Run().EnsureSuccess();"cmd".AsCommandLine("/c","echo","Hello").Run().EnsureSuccess();("cmd".AsCommandLine()+"/c"+"echo"+"Hello").Run().EnsureSuccess();// Just builds a command line with multiple environment variablesvarcmd=newCommandLine("cmd","/c","echo","Hello").AddVars(("Var1","val1"),("var2","Val2"));// Same as previous statementcmd=newCommandLine("cmd")+"/c"+"echo"+"Hello"+("Var1","val1")+("var2","Val2");// Builds a command line to run from a specific working directorycmd=newCommandLine("cmd","/c","echo","Hello").WithWorkingDirectory("MyDyrectory");// Builds a command line and replaces all command line argumentscmd=newCommandLine("cmd","/c","echo","Hello").WithArgs("/c","echo","Hello !!!");

Running a command line

usingHostApi;GetService<ICommandLineRunner>().Run(newCommandLine("cmd","/c","DIR")).EnsureSuccess();// or the same thing using the extension methodnewCommandLine("cmd","/c","DIR").Run().EnsureSuccess();// using operator '+'varcmd=newCommandLine("cmd")+"/c"+"DIR";cmd.Run().EnsureSuccess();// with environment variablescmd=newCommandLine("cmd")+"/c"+"DIR"+("MyEnvVar","Some Value");cmd.Run().EnsureSuccess();

Running a command line asynchronously

usingHostApi;awaitGetService<ICommandLineRunner>().RunAsync(newCommandLine("cmd","/C","DIR")).EnsureSuccess();// or the same thing using the extension methodvarresult=awaitnewCommandLine("cmd","/c","DIR").RunAsync().EnsureSuccess();

Running and analyzing an output

usingHostApi;varlines=newList<string>();varresult=newCommandLine("cmd","/c","SET").AddVars(("MyEnv","MyVal")).Run(output=>lines.Add(output.Line)).EnsureSuccess();lines.ShouldContain("MyEnv=MyVal");

Running asynchronously in parallel

usingHostApi;vartask=newCommandLine("cmd","/c","DIR").RunAsync().EnsureSuccess();varresult=newCommandLine("cmd","/c","SET").Run().EnsureSuccess();awaittask;

Cancellation of asynchronous run

Cancellation will destroy the process and its child processes.

usingHostApi;varcancellationTokenSource=newCancellationTokenSource();vartask=newCommandLine("cmd","/c","TIMEOUT","/T","120").RunAsync(null,cancellationTokenSource.Token);cancellationTokenSource.CancelAfter(TimeSpan.FromMilliseconds(100));task.IsCompleted.ShouldBeFalse();

Running with timeout

If timeout expired a process will be killed.

usingHostApi;varexitCode=newCommandLine("cmd","/c","TIMEOUT","/T","120").Run(null,TimeSpan.FromMilliseconds(1)).ExitCode;

Docker CLI

Building a project in a docker container

usingHostApi;// Creates a base docker command linevardockerRun=newDockerRun().WithAutoRemove(true).WithInteractive(true).WithImage("mcr.microsoft.com/dotnet/sdk").WithPlatform("linux").WithContainerWorkingDirectory("/MyProjects").AddVolumes((ToAbsoluteLinuxPath(Environment.CurrentDirectory),"/MyProjects"));// Creates a new library project in a docker containerdockerRun.WithCommandLine(newDotNetCustom("new","classlib","-n","MyLib","--force")).Run().EnsureSuccess();// Builds the library project in a docker containervarresult=dockerRun.WithCommandLine(newDotNetBuild().WithProject("MyLib/MyLib.csproj")).Build().EnsureSuccess();stringToAbsoluteLinuxPath(stringpath)=>"/"+path.Replace(":","").Replace('\\','/');

Running in docker

usingHostApi;// Creates some command line to run in a docker containervarcmd=newCommandLine("whoami");// Runs the command line in a docker containervarresult=newDockerRun(cmd,"mcr.microsoft.com/dotnet/sdk").WithAutoRemove(true).Run().EnsureSuccess();

.NET CLI

Adding a NuGet package

usingHostApi;varresult=newDotNetAddPackage().WithWorkingDirectory("MyLib").WithPackage("Pure.DI").Run().EnsureSuccess();

Adding a NuGet source

usingHostApi;newDotNetNuGetAddSource().WithName("TestSource").WithSource(source).Run().EnsureSuccess();

Adding a project reference

usingHostApi;newDotNetAddReference().WithProject(Path.Combine("MyTests","MyTests.csproj")).WithReferences(Path.Combine("MyLib","MyLib.csproj")).Run().EnsureSuccess();newDotNetRemoveReference().WithProject(Path.Combine("MyTests","MyTests.csproj")).WithReferences(Path.Combine("MyLib","MyLib.csproj")).Run().EnsureSuccess();varlines=newList<string>();newDotNetListReference().WithProject(Path.Combine("MyTests","MyTests.csproj")).Run(output=>lines.Add(output.Line));lines.Any(i=>i.Contains("MyLib.csproj")).ShouldBeFalse();

Adding projects to the solution file

usingHostApi;newDotNetNew().WithTemplateName("sln").WithName("NySolution").WithForce(true).Run().EnsureSuccess();newDotNetSlnAdd().WithSolution("NySolution.sln").AddProjects(Path.Combine("MyLib","MyLib.csproj"),Path.Combine("MyTests","MyTests.csproj")).Run().EnsureSuccess();

Adding project-to-project (P2P) references

usingHostApi;varresult=newDotNetAddReference().WithProject(Path.Combine("MyTests","MyTests.csproj")).WithReferences(Path.Combine("MyLib","MyLib.csproj")).Run().EnsureSuccess();

Building a project

usingHostApi;varmessages=newList<BuildMessage>();varresult=newDotNetBuild().WithWorkingDirectory("MyTests").Build(message=>messages.Add(message)).EnsureSuccess();result.Errors.Any(message=>message.State==BuildMessageState.StdError).ShouldBeFalse(result.ToString());result.ExitCode.ShouldBe(0,result.ToString());

Building a project using MSBuild

usingHostApi;// Creates a new library project, running a command like: "dotnet new classlib -n MyLib --force"newDotNetNew().WithTemplateName("classlib").WithName("MyLib").WithForce(true).Build().EnsureSuccess();// Builds the library project, running a command like: "dotnet msbuild /t:Build -restore /p:configuration=Release -verbosity=detailed" from the directory "MyLib"varresult=newMSBuild().WithWorkingDirectory("MyLib").WithTarget("Build").WithRestore(true).AddProps(("configuration","Release")).WithVerbosity(DotNetVerbosity.Detailed).Build().EnsureSuccess();// The "result" variable provides details about a buildresult.Errors.Any(message=>message.State==BuildMessageState.StdError).ShouldBeFalse(result.ToString());result.ExitCode.ShouldBe(0,result.ToString());

Cleaning a project

usingHostApi;// Clean the project, running a command like: "dotnet clean" from the directory "MyLib"newDotNetClean().WithWorkingDirectory("MyLib").Build().EnsureSuccess();

Clearing the specified NuGet cache type

usingHostApi;newDotNetNuGetLocalsClear().WithCacheLocation(NuGetCacheLocation.Temp).Run().EnsureSuccess();

Creating a new project, configuration file, or solution based on the specified template

usingHostApi;newDotNetNew().WithTemplateName("classlib").WithName("MyLib").WithForce(true).Run().EnsureSuccess();

Deleting a NuGet package to the server

usingHostApi;newDotNetNuGetDelete().WithPackage("MyLib").WithPackageVersion("1.0.0").WithSource(repoUrl).Run().EnsureSuccess();

Disabling a NuGet source

usingHostApi;newDotNetNuGetDisableSource().WithName("TestSource").Run().EnsureSuccess();

Displaing template package metadata

usingHostApi;newDotNetNewDetails().WithTemplateName("CSharpInteractive.Templates").Run().EnsureSuccess();

Enabling a NuGet source

usingHostApi;newDotNetNuGetEnableSource().WithName("TestSource").Run().EnsureSuccess();

Enabling or disabling workload-set update mode

usingHostApi;newDotNetWorkloadConfig().WithUpdateMode(DotNetWorkloadUpdateMode.WorkloadSet).Run().EnsureSuccess();

Executing a dotnet application

usingHostApi;newDotNetExec().WithPathToApplication(Path.Combine(path,"MyApp.dll")).Run().EnsureSuccess();

Fixing (non code style) analyzer issues

usingHostApi;newDotNetFormatAnalyzers().WithWorkingDirectory("MyLib").WithProject("MyLib.csproj").AddDiagnostics("CA1831","CA1832").WithSeverity(DotNetFormatSeverity.Warning).Run().EnsureSuccess();

Fixing code style issues

usingHostApi;newDotNetFormatStyle().WithWorkingDirectory("MyLib").WithProject("MyLib.csproj").AddDiagnostics("IDE0005","IDE0006").WithSeverity(DotNetFormatSeverity.Information).Run().EnsureSuccess();

Formatting a code

usingHostApi;newDotNetFormat().WithWorkingDirectory("MyLib").WithProject("MyLib.csproj").AddDiagnostics("IDE0005","IDE0006").AddIncludes(".","./tests").AddExcludes("./obj").WithSeverity(DotNetFormatSeverity.Information).Run().EnsureSuccess();

Getting a value of a specified NuGet configuration setting

usingHostApi;string?repositoryPath=null;newDotNetNuGetConfigGet().WithConfigKey("repositoryPath").Run(output=>repositoryPath=output.Line).EnsureSuccess();

Installing a template package

usingHostApi;newDotNetNewInstall().WithPackage("Pure.DI.Templates").Run().EnsureSuccess();

Installing optional workloads

usingHostApi;newDotNetWorkloadInstall().AddWorkloads("aspire").Run().EnsureSuccess();

Installing the .NET local tools that are in scope for the current directory

usingHostApi;// Creates a local tool manifestnewDotNetNew().WithTemplateName("tool-manifest").Run().EnsureSuccess();newDotNetToolRestore().Run().EnsureSuccess();

Installing the specified .NET tool

usingHostApi;newDotNetToolInstall().WithLocal(true).WithPackage("dotnet-csi").WithVersion("1.1.2").Run().EnsureSuccess();

Installing workloads needed for a project or a solution

usingHostApi;newDotNetWorkloadRestore().WithProject(Path.Combine("MyLib","MyLib.csproj")).Run().EnsureSuccess();

Invoking a local tool

usingHostApi;varscript=Path.GetTempFileName();File.WriteAllText(script,"Console.WriteLine($\"Hello, {Args[0]}!\");");varstdOut=newList<string>();newDotNetToolRun().WithCommandName("dotnet-csi").AddArgs(script).AddArgs("World").Run(output=>stdOut.Add(output.Line)).EnsureSuccess();// Checks stdOutstdOut.Contains("Hello, World!").ShouldBeTrue();

Packing a code into a NuGet package

usingHostApi;// Creates a NuGet package of version 1.2.3 for the projectnewDotNetPack().WithWorkingDirectory("MyLib").WithOutput(path).AddProps(("version","1.2.3")).Build().EnsureSuccess();

Printing a dependency graph for NuGet package

usingHostApi;newDotNetNuGetWhy().WithProject(Path.Combine("MyLib","MyLib.csproj")).WithPackage("MyLib.1.2.3.nupkg").Run().EnsureSuccess();

Printing all .NET tools of the specified type currently installed

usingHostApi;newDotNetToolList().WithLocal(true).Run().EnsureSuccess();newDotNetToolList().WithGlobal(true).Run().EnsureSuccess();

Printing all configured NuGet sources

usingHostApi;newDotNetNuGetListSource().WithFormat(NuGetListFormat.Short).Run().EnsureSuccess();

Printing all projects in a solution file

usingHostApi;varlines=newList<string>();newDotNetSlnList().WithSolution("NySolution.sln").Run(output=>lines.Add(output.Line)).EnsureSuccess();

Printing available templates to be run using dotnet new

usingHostApi;newDotNetNewList().Run().EnsureSuccess();

Printing installed workloads

usingHostApi;newDotNetWorkloadList().Run().EnsureSuccess();

Printing nuget configuration files currently being applied to a directory

usingHostApi;varconfigPaths=newList<string>();newDotNetNuGetConfigPaths().Run(output=>configPaths.Add(output.Line)).EnsureSuccess();

Printing NuGet packages for a project

usingHostApi;newDotNetAddPackage().WithWorkingDirectory("MyLib").WithPackage("Pure.DI").Run().EnsureSuccess();varlines=newList<string>();newDotNetListPackage().WithProject(Path.Combine("MyLib","MyLib.csproj")).WithVerbosity(DotNetVerbosity.Minimal).Run(output=>lines.Add(output.Line));lines.Any(i=>i.Contains("Pure.DI")).ShouldBeTrue();

Printing project references for a project

usingHostApi;newDotNetAddReference().WithProject(Path.Combine("MyTests","MyTests.csproj")).WithReferences(Path.Combine("MyLib","MyLib.csproj")).Run().EnsureSuccess();varlines=newList<string>();newDotNetListReference().WithProject(Path.Combine("MyTests","MyTests.csproj")).Run(output=>lines.Add(output.Line));lines.Any(i=>i.Contains("MyLib.csproj")).ShouldBeTrue();

Printing the latest available version of the .NET SDK and .NET Runtime, for each feature band

usingHostApi;varsdks=newList<Sdk>();newDotNetSdkCheck().Run(output=>{if(output.Line.StartsWith("Microsoft.")){vardata=output.Line.Split(' ',StringSplitOptions.RemoveEmptyEntries);if(data.Length>=2){sdks.Add(newSdk(data[0],NuGetVersion.Parse(data[1])));}}}).EnsureSuccess();sdks.Count.ShouldBeGreaterThan(0);recordSdk(stringName,NuGetVersionVersion);

Printing the location of the specified NuGet cache type

usingHostApi;newDotNetNuGetLocalsList().WithCacheLocation(NuGetCacheLocation.GlobalPackages).Run().EnsureSuccess();

Publishing an application and its dependencies to a folder for deployment to a hosting system

usingHostApi;newDotNetPublish().WithWorkingDirectory("MyLib").WithFramework(framework).WithOutput("bin").Build().EnsureSuccess();

Pushing a NuGet package to the server

usingHostApi;newDotNetNuGetPush().WithWorkingDirectory("MyLib").WithPackage(Path.Combine("packages","MyLib.1.0.0.nupkg")).WithSource(repoUrl).Run().EnsureSuccess();

Removing a NuGet package

usingHostApi;newDotNetAddPackage().WithWorkingDirectory("MyLib").WithPackage("Pure.DI").Run().EnsureSuccess();newDotNetRemovePackage().WithWorkingDirectory("MyLib").WithPackage("Pure.DI").Run().EnsureSuccess();

Removing a project or multiple projects from the solution file

usingHostApi;newDotNetSlnRemove().WithSolution("NySolution.sln").AddProjects(Path.Combine("MyLib","MyLib.csproj")).Run().EnsureSuccess();

Removing an existing source from your NuGet configuration files

usingHostApi;newDotNetNuGetRemoveSource().WithName("TestSource").Run().EnsureSuccess();

Repairing workloads installations

usingHostApi;newDotNetWorkloadRepair().Run().EnsureSuccess();

Restoring the dependencies and tools of a project

usingHostApi;newDotNetRestore().WithProject(Path.Combine("MyLib","MyLib.csproj")).Build().EnsureSuccess();

Running a .NET application

// Adds the namespace "HostApi" to use .NET build APIusingHostApi;newDotNet().WithPathToApplication(Path.Combine(path,"MyApp.dll")).Run().EnsureSuccess();

Running a custom .NET command

usingHostApi;// Gets the dotnet version, running a command like: "dotnet --version"NuGetVersion?version=null;newDotNetCustom("--version").Run(message=>NuGetVersion.TryParse(message.Line,outversion)).EnsureSuccess();version.ShouldNotBeNull();

Running source code without any explicit compile or launch commands

usingHostApi;varstdOut=newList<string>();newDotNetRun().WithProject(Path.Combine("MyApp","MyApp.csproj")).Build(message=>stdOut.Add(message.Text)).EnsureSuccess();

Running tests from the specified assemblies

usingHostApi;// Runs testsvarresult=newVSTest().AddTestFileNames(Path.Combine("bin","MyTests.dll")).WithWorkingDirectory(path).Build().EnsureSuccess();// The "result" variable provides details about build and testsresult.ExitCode.ShouldBe(0,result.ToString());result.Summary.Tests.ShouldBe(1,result.ToString());result.Tests.Count(test=>test.State==TestState.Finished).ShouldBe(1,result.ToString());

Running tests under dotCover

usingHostApi;newDotNetToolInstall().WithLocal(true).WithPackage("JetBrains.dotCover.GlobalTool").Run().EnsureSuccess();// Creates a test commandvartest=newDotNetTest().WithProject("MyTests");vardotCoverSnapshot=Path.Combine("MyTests","dotCover.dcvr");vardotCoverReport=Path.Combine("MyTests","dotCover.html");// Modifies the test command by putting "dotCover" in front of all arguments// to have something like "dotnet dotcover test ..."// and adding few specific arguments to the endvartestUnderDotCover=test.Customize(cmd=>cmd.ClearArgs()+"dotcover"+cmd.Args+$"--dcOutput={dotCoverSnapshot}"+"--dcFilters=+:module=TeamCity.CSharpInteractive.HostApi;+:module=dotnet-csi"+"--dcAttributeFilters=System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage");// Runs tests under dotCovervarresult=testUnderDotCover.Build().EnsureSuccess();// The "result" variable provides details about a buildresult.ExitCode.ShouldBe(0,result.ToString());result.Tests.Count(i=>i.State==TestState.Finished).ShouldBe(1,result.ToString());// Generates a HTML code coverage report.newDotNetCustom("dotCover","report",$"--source={dotCoverSnapshot}",$"--output={dotCoverReport}","--reportType=HTML").Run().EnsureSuccess();

Searching all .NET tools that are published to NuGet

usingHostApi;newDotNetToolSearch().WithPackage("dotnet-csi").WithDetail(true).Run().EnsureSuccess();

Searching for a NuGet package

usingSystem.Text;usingSystem.Text.Json;usingHostApi;varpackagesJson=newStringBuilder();newDotNetPackageSearch().WithSearchTerm("Pure.DI").WithFormat(DotNetPackageSearchResultFormat.Json).Run(output=>packagesJson.AppendLine(output.Line)).EnsureSuccess();varresult=JsonSerializer.Deserialize<Result>(packagesJson.ToString(),newJsonSerializerOptions{PropertyNameCaseInsensitive=true});result.ShouldNotBeNull();result.SearchResult.SelectMany(i=>i.Packages).Count(i=>i.Id=="Pure.DI").ShouldBe(1);recordResult(intVersion,IReadOnlyCollection<Source>SearchResult);recordSource(stringSourceName,IReadOnlyCollection<Package>Packages);recordPackage(stringId,stringLatestVersion,intTotalDownloads,stringOwners);

Searching for optional workloads

usingHostApi;newDotNetWorkloadSearch().WithSearchString("maui").Run().EnsureSuccess();

Searching for the templates

usingHostApi;newDotNetNewSearch().WithTemplateName("build").Run().EnsureSuccess();

Setting the value of a specified NuGet configuration setting

usingHostApi;newDotNetNuGetConfigSet().WithConfigFile(configFile).WithConfigKey("repositoryPath").WithConfigValue("MyValue").Run().EnsureSuccess();

Signing with certificate

usingHostApi;newDotNetNuGetSign().AddPackages("MyLib.1.2.3.nupkg").WithCertificatePath("certificate.pfx").WithCertificatePassword("Abc").WithTimestampingServer("http://timestamp.digicert.com/").Run().EnsureSuccess();

Storing the specified assemblies in the runtime package store.

usingHostApi;newDotNetStore().AddManifests(Path.Combine("MyLib","MyLib.csproj")).WithFramework("net8.0").WithRuntime("win-x64").Build();

Testing a project using the MSBuild VSTest target

usingHostApi;// Runs tests via a commandvarresult=newMSBuild().WithTarget("VSTest").WithWorkingDirectory("MyTests").Build().EnsureSuccess();// The "result" variable provides details about a buildresult.ExitCode.ShouldBe(0,result.ToString());result.Summary.Tests.ShouldBe(1,result.ToString());result.Tests.Count(test=>test.State==TestState.Finished).ShouldBe(1,result.ToString());

Testing from the specified project

usingHostApi;// Runs testsvarresult=newDotNetTest().WithProject("MyTests").Build().EnsureSuccess();

Uninstalling a specified workload

usingHostApi;newDotNetWorkloadUninstall().AddWorkloads("aspire").Run().EnsureSuccess();

Uninstalling a template package

usingHostApi;newDotNetNewUninstall().WithPackage("Pure.DI.Templates").Run();

Uninstalling the specified .NET tool

usingHostApi;newDotNetToolUninstall().WithPackage("dotnet-csi").Run().EnsureSuccess();

Unsetting the value of a specified NuGet configuration setting

usingHostApi;newDotNetNuGetConfigUnset().WithConfigKey("repositoryPath").Run().EnsureSuccess();

Updating a NuGet source

usingHostApi;newDotNetNuGetUpdateSource().WithName("TestSource").WithSource(newSource).Run().EnsureSuccess();

Updating installed template packages

usingHostApi;newDotNetNewUpdate().Run().EnsureSuccess();

Updating installed workloads

usingHostApi;newDotNetWorkloadUpdate().Run().EnsureSuccess();

Updating the specified .NET tool

usingHostApi;newDotNetToolUpdate().WithLocal(true).WithPackage("dotnet-csi").WithVersion("1.1.2").Run().EnsureSuccess();

Working with development certificates

usingHostApi;// Create a certificate, trust it, and export it to a PEM file.newDotNetDevCertsHttps().WithExportPath("certificate.pem").WithTrust(true).WithFormat(DotNetCertificateFormat.Pem).WithPassword("Abc").Run().EnsureSuccess();

Running C# script

usingHostApi;varscript=Path.GetTempFileName();File.WriteAllText(script,"Console.WriteLine($\"Hello, {Args[0]}!\");");varstdOut=newList<string>();newDotNetCsi().WithScript(script).AddArgs("World").Run(output=>stdOut.Add(output.Line)).EnsureSuccess();// Checks stdOutstdOut.Contains("Hello, World!").ShouldBeTrue();

Shutting down build servers

usingHostApi;// Shuts down all build servers that are started from dotnet.newDotNetBuildServerShutdown().Run().EnsureSuccess();

TeamCity API

TeamCity integration via service messages

For more details how to use TeamCity service message API please seethis page. Instead of creating a root message writer like in the following example:

usingJetBrains.TeamCity.ServiceMessages.Write.Special;usingvarwriter=newTeamCityServiceMessages().CreateWriter(Console.WriteLine);

use this statement:

usingJetBrains.TeamCity.ServiceMessages.Write.Special;usingvarwriter=GetService<ITeamCityWriter>();

This sample opens a blockMy Tests and reports about two tests:

// Adds a namespace to use ITeamCityWriterusingJetBrains.TeamCity.ServiceMessages.Write.Special;usingvarwriter=GetService<ITeamCityWriter>();using(vartests=writer.OpenBlock("My Tests")){using(vartest=tests.OpenTest("Test1")){test.WriteStdOutput("Hello");test.WriteImage("TestsResults/Test1Screenshot.jpg","Screenshot");test.WriteDuration(TimeSpan.FromMilliseconds(10));}using(vartest=tests.OpenTest("Test2")){test.WriteIgnored("Some reason");}}

For more information on TeamCity Service Messages, seethis page.


[8]ページ先頭

©2009-2025 Movatter.jp