TExcelTAD
Home › .NET Builds: MSBuild & NuGet › .NET Build Exercises

.NET Build Exercises

Each exercise is a piece of logic that MSBuild or NuGet runs on every build, written as a pure function with the tests already in place. Run the starter first: it prints wrong answers (None, empty lists), which shows what the tests expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last exercise is a real dotnet session to fix.

Exercise 1: Parse a NuGet version range

Topics: Version Ranges & Resolution

Turn NuGet range notation into (min, min_inclusive, max, max_inclusive), with None for a missing bound. A bare version is a minimum. Versions have three numeric parts here; return them as tuples.

python · try it yourself
def parse_range(text):
    # TODO: handle "1.0", "[1.0]", "[1.0,2.0)", "(,1.0]", "(1.0,)"
    return None

def satisfies(version, rng):
    # TODO: use parse_range; compare tuples
    return None

for r in ["13.0.3", "[2.9.3]", "[1.0.0,2.0.0)", "(,1.4.0]", "(1.0.0,)"]:
    print(f"{r:14} {parse_range(r)}")
v = (1, 4, 0)
print("1.4.0 in", [r for r in ["1.0.0", "[1.0.0,1.4.0)", "(,1.4.0]", "[1.4.0]"] if satisfies(v, r)])
13.0.3         None
[2.9.3]        None
[1.0.0,2.0.0)  None
(,1.4.0]       None
(1.0.0,)       None
1.4.0 in []

Expected output:

text
13.0.3         ((13, 0, 3), True, None, False)
[2.9.3]        ((2, 9, 3), True, (2, 9, 3), True)
[1.0.0,2.0.0)  ((1, 0, 0), True, (2, 0, 0), False)
(,1.4.0]       (None, False, (1, 4, 0), True)
(1.0.0,)       ((1, 0, 0), False, None, False)
1.4.0 in ['1.0.0', '(,1.4.0]', '[1.4.0]']
Show solution
python
def ver(s):
    return tuple(int(x) for x in s.split(".")) if s else None

def parse_range(text):
    if text[0] not in "[(":
        return ver(text), True, None, False
    lo_inc, hi_inc = text[0] == "[", text[-1] == "]"
    body = text[1:-1]
    if "," not in body:                       # [1.0] exact
        return ver(body), True, ver(body), True
    lo, hi = body.split(",")
    return ver(lo.strip()), lo_inc, ver(hi.strip()), hi_inc

def satisfies(version, rng):
    lo, lo_inc, hi, hi_inc = parse_range(rng)
    if lo is not None and (version < lo or (version == lo and not lo_inc)):
        return False
    if hi is not None and (version > hi or (version == hi and not hi_inc)):
        return False
    return True

Python compares tuples element by element, which is exactly numeric version order; comparing the strings would put 13.0.10 before 13.0.9.

Exercise 2: Lowest applicable version

Topics: Version Ranges & Resolution, Push & Consume

Pick the version NuGet would restore: the lowest available version in the range, except that a range ending in * floats to the highest match. Prereleases (containing -) are only candidates when the range itself mentions a prerelease. Return None when nothing fits (NU1102).

python · try it yourself
def key(v):
    nums, _, pre = v.partition("-")
    # a release sorts after its prereleases
    return tuple(int(x) for x in nums.split(".")), pre == "", pre

def resolve(rng, available):
    # TODO
    return None

feed = ["1.0.0", "1.1.0-beta.1", "1.1.0", "1.2.0", "2.0.0"]
for r in ["1.0.0", "1.1.0", "1.1.0-beta.1", "1.*", "*", "3.0.0", "1.0.5"]:
    print(f"{r:13} -> {resolve(r, feed)}")
1.0.0         -> None
1.1.0         -> None
1.1.0-beta.1  -> None
1.*           -> None
*             -> None
3.0.0         -> None
1.0.5         -> None

Expected output:

text
1.0.0         -> 1.0.0
1.1.0         -> 1.1.0
1.1.0-beta.1  -> 1.1.0-beta.1
1.*           -> 1.2.0
*             -> 2.0.0
3.0.0         -> None
1.0.5         -> 1.1.0
Show solution
python
def resolve(rng, available):
    allow_pre = "-" in rng
    pool = [v for v in available if allow_pre or "-" not in v]
    if rng.endswith("*"):
        prefix = rng[:-1]
        matches = [v for v in pool if v.startswith(prefix)]
        return max(matches, key=key) if matches else None
    ok = [v for v in pool if key(v) >= key(rng)]
    return min(ok, key=key) if ok else None

1.0.5 isn't on the feed, so NuGet takes the lowest version above it, 1.1.0, and warns with NU1603. Note that 1.1.0-beta.1 is skipped for that range, although it is "above" 1.0.5: a stable range never resolves to a prerelease.

Exercise 3: Package source mapping

Topics: nuget.config, Feeds & Source Mapping

Given the packageSourceMapping patterns per source, return the sources NuGet may ask for a package id: those whose most specific matching pattern is the longest. An exact id beats any prefix pattern. Matching ignores case.

python · try it yourself
MAPPING = {
    "nuget":    ["*", "Contoso.Public.*"],
    "internal": ["Contoso.*", "Newtonsoft.Json"],
    "partner":  ["Fabrikam.*", "Contoso.Shared.*"],
}

def sources_for(package_id):
    # TODO
    return []

for pid in ["Serilog", "Contoso.Billing", "Contoso.Public.Http", "contoso.shared.models",
            "Newtonsoft.Json", "Newtonsoft.Json.Bson", "Fabrikam.Ui"]:
    print(f"{pid:22} -> {sources_for(pid)}")
Serilog                -> []
Contoso.Billing        -> []
Contoso.Public.Http    -> []
contoso.shared.models  -> []
Newtonsoft.Json        -> []
Newtonsoft.Json.Bson   -> []
Fabrikam.Ui            -> []

Expected output:

text
Serilog                -> ['nuget']
Contoso.Billing        -> ['internal']
Contoso.Public.Http    -> ['nuget']
contoso.shared.models  -> ['partner']
Newtonsoft.Json        -> ['internal']
Newtonsoft.Json.Bson   -> ['nuget']
Fabrikam.Ui            -> ['partner']
Show solution
python
def score(pattern, pid):
    p, i = pattern.lower(), pid.lower()
    if p.endswith("*"):
        return len(p) - 1 if i.startswith(p[:-1]) else -1
    return 10_000 if p == i else -1          # exact ids win outright

def sources_for(package_id):
    best = {src: max(score(p, package_id) for p in pats) for src, pats in MAPPING.items()}
    top = max(best.values())
    return sorted(src for src, s in best.items() if s == top and s >= 0)

The result is a list because two sources may map the same pattern; NuGet then asks both. Newtonsoft.Json.Bson doesn't match the exact id Newtonsoft.Json, so only * applies.

Exercise 4: Should this target run?

Topics: Incremental Targets: Inputs & Outputs

Implement MSBuild's up-to-date check for a target whose Outputs are a one-to-one transform of its Inputs. Return the inputs that must be processed: all of them if any output is missing, else only those newer than their own output. A missing input is an error: return the string "error: missing input <name>".

python · try it yourself
def stale_inputs(pairs, mtime):
    """pairs: list of (input, output); mtime: file -> modification time."""
    # TODO
    return None

mtime = {"a.md": 5, "b.md": 9, "c.md": 5, "a.html": 6, "b.html": 6, "c.html": 6}
pairs = [("a.md", "a.html"), ("b.md", "b.html"), ("c.md", "c.html")]
print(stale_inputs(pairs, mtime))
print(stale_inputs(pairs, {**mtime, "b.md": 5}))
print(stale_inputs(pairs + [("d.md", "d.html")], {**mtime, "d.md": 1}))
print(stale_inputs(pairs + [("e.md", "e.html")], mtime))
None
None
None
None

Expected output:

text
['b.md']
[]
['b.md', 'd.md']
error: missing input e.md
Show solution
python
def stale_inputs(pairs, mtime):
    for i, _ in pairs:
        if i not in mtime:
            return f"error: missing input {i}"
    return [i for i, o in pairs if o not in mtime or mtime[i] > mtime[o]]

With a one-to-one mapping, a missing output only makes its own input stale: the third call processes d.md (no output yet) and b.md (still newer than its output), but not a.md or c.md. That's MSBuild's partial build.

Exercise 5: Fix the build

Topics: Central Package Management, SDK-Style Project Files

This repository uses Central Package Management, but the app doesn't build. Read the errors and fix two lines of App/App.csproj (don't touch Directory.Packages.props or the C# code).

bash · try it yourself
mkdir repo && cd repo
cat > Directory.Packages.props <<'XML'
<Project>
  <PropertyGroup>
    <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
  </PropertyGroup>
  <ItemGroup>
    <PackageVersion Include="Humanizer.Core" Version="2.14.1" />
  </ItemGroup>
</Project>
XML
mkdir -p App/Text
cat > App/App.csproj <<'XML'
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Humanizer.Core" Version="2.14.1" />
    <Compile Include="Text/Titles.cs" />
  </ItemGroup>
</Project>
XML
cat > App/Text/Titles.cs <<'CS'
using Humanizer;
public static class Titles { public static string Of(string s) => s.Humanize(LetterCasing.Title); }
CS
echo 'System.Console.WriteLine(Titles.Of("central_package_management"));' > App/Program.cs
dotnet run --project App 2>&1 | grep -E 'error' | awk '!seen[$0]++' | sed 's|/home/learner/repo/||; s|/usr/share/dotnet/sdk/10.0.402/Sdks/Microsoft.NET.Sdk/targets/|<sdk>/|'
App/App.csproj : error NU1008: The following PackageReference items cannot define a value for Version: Humanizer.Core. Projects using Central Package Management must define a Version value on a PackageVersion item. For more information, visit https://aka.ms/nuget/cpm/gettingstarted
The build failed. Fix the build errors and run again.

Expected output once fixed (dotnet run --project App):

text
Central Package Management
Show solution
  1. Under CPM a PackageReference must not carry a Version (NU1008): write <PackageReference Include="Humanizer.Core" />.
  2. Restore stops at the first problem, so the second one only shows once the first is fixed: Text/Titles.cs is already included by the SDK's **/*.cs glob, so the explicit <Compile Include> duplicates it (NETSDK1022). Delete that line.
xml
<ItemGroup>
  <PackageReference Include="Humanizer.Core" />
</ItemGroup>

Test yourself

In Exercise 2, why does the range 1.0.5 resolve to 1.1.0 and not 1.1.0-beta.1?

  1. Prereleases are sorted last
  2. A range without a prerelease part never selects prerelease versions
  3. beta versions are deleted
  4. 1.1.0 is newer than 1.0.5

In Exercise 3, which source may serve Contoso.Public.Http?

  1. internal, because Contoso.* matches
  2. nuget, because Contoso.Public.* is the longer, more specific pattern
  3. Both
  4. None