Skip to main content

Using file-based C# apps

File-based apps let you run a single C# source file directly with the .NET SDK. It provides the same performance and many of the features of a full C# project, but without the .csproj boilerplate.

Simple example​

To create a simple program, we can create a example.cs file with the following contents:

#r "nuget: Unipi.Nancy@1.3.0"

using System.IO;
using Unipi.Nancy.NetworkCalculus;
using Unipi.Nancy.MinPlusAlgebra;
using Unipi.Nancy.Numerics;

// arrival curve for the traffic
var ac = new SigmaRhoArrivalCurve(2, 2);
// service curve for the traversed node
var sc = new RateLatencyServiceCurve(3, 1);

// worst-case delay bound computed with horizontal deviation
Console.WriteLine($"Delay bound: {Curve.HorizontalDeviation(ac, sc)}");
// worst-case backlog bound computed with vertical deviation
Console.WriteLine($"Backlog bound: {Curve.VerticalDeviation(ac, sc)}");

From the same directory, run

dotnet run app.cs

Behind the scenes, this command will restore the required packages, compile the code, and execute it. The workflow is thus similar to a scripting language.

How to plot​

Plotting now supports multiple targets, like TiKZ and png images, through the common interface in the Unipi.Nancy.Plots namespace. Each target is implemented in separate packages that can be installed independently depending on your needs.

One easy option is Unipi.Nancy.Plots.ScottPlot, which can plot as static images and can work also in headless environments (compared to plotly-based approaches, which require a modern browser to render a plot).

...
#r "nuget: Unipi.Nancy.Plots.ScottPlot@1.0.4"
...
using Unipi.Nancy.Plots.ScottPlot;
...

// plot the two curves and save the image to disk
var plotBytes = ScottPlots.ToScottPlotImage([ac, sc]);
var plotPath = Path.GetFullPath("plot.png");
File.WriteAllBytes(plotPath, plotBytes);
Console.WriteLine($"Plot written to {plotPath}");

Conversion to full C# projects​

File-based apps can quickly become too restrictive, e.g. when we move from a simple experiment with "fixed" expressions to compute to a more general tool that should process a network topology on its own, and having multiple classes spread into different files becomes a requirement.

To convert a file-based app into a C# project, you can use

dotnet project convert file.cs

Other recommendations​

For rich CLI apps, I recommend Spectre.Console. It makes easy to implement robust argument parsing, as well as rich console output.