Start learning free

LESSON 148 OF 173 · BACKEND: SHIPPING IT

Settings from the Environment

Practice

The shop's code is the same on your computer and on the server, but a few settings differ: the port it listens on, and where the database file is. Don't write them into the code. The server hands them to the program as environment variables: named text values that every program it starts can read.

In C#, Environment.GetEnvironmentVariable(name) gives you a variable's text, or null when it isn't set, and ?? swaps that null for a default. The values are always text, so a number needs int.Parse. For example, a script that reads how many times to retry and how to greet:

var retries = int.Parse(Environment.GetEnvironmentVariable("RETRIES") ?? "3");
var greeting = Environment.GetEnvironmentVariable("GREETING") ?? "Hello";

Your file prints the settings the server would use. Then the check calls your LoadSettings() three times, with different variables set, and prints what it returns as JSON:

Port: 8000
Database: shop.db
Nothing set (your computer):
{"port":8000,"database_path":"shop.db"}
PORT=5000 and DATABASE_PATH=/data/shop.db (the server):
{"port":5000,"database_path":"/data/shop.db"}
Only PORT=10000:
{"port":10000,"database_path":"shop.db"}

Your task: write the local function LoadSettings(). It reads PORT as a number, with the default "8000", and DATABASE_PATH, with the default "shop.db", and returns them in a Dictionary<string, object> with the keys "port" and "database_path". Below it, call it once and print the two settings after Port: and Database:.


Assignment
Follow the Coding Tutorial to read PORT and DATABASE_PATH from the environment with defaults, return them in a dictionary, and print the settings the server would use.


Hint
Put ?? default right after GetEnvironmentVariable(...). Put the port inside int.Parse( ), but not the path: a path is text. Until the function has its return, C# stops with error CS0161.


STEP 1 OF 7
    Ctrl + Enter to check