RingDotNetfor Ring

Settings

Programs should remember how the user likes them. This lesson stores settings in a JSON file with defaults, handles a damaged file, and shows where programs keep such files.

What you will learn#

Where do settings live?#

The system has a folder for every kind of file; .NET finds them with Environment.GetFolderPath:

NameFor
MyDocumentsfiles the user creates
ApplicationDatasettings that follow the user to other computers
LocalApplicationDatasettings and caches of this computer
Desktopthe desktop

A program normally keeps its settings in a file inside its own folder under ApplicationData, for example …\ApplicationData\MyProgram\settings.json. The tutorial uses the temp folder so that it leaves nothing behind.

The design#

RuleWhy
every setting has a defaultthe first run, and a missing key, work
the file is JSON, readable by peopleusers and support can read and edit it
loading never fails the programa damaged file must not stop the application
saving happens when the user changes somethinga crash does not lose the choices

The program#

samples/UsingDotNet/tutorials/ch09_settings.ring
# settings - defaults, a JSON file, loading, saving, and special folders
load "dotnet.ring"

using {
	"System"
	"System.IO"
	"System.Text.Json"
}

func main

	# Where do programs keep their files? .NET knows the special folders of the user.
	oEnvironment = new Environment()
	? "Special folders exist:"
	for cFolder in ["MyDocuments","ApplicationData","LocalApplicationData","Desktop"]
		? "   " + cFolder + " : " + (len(oEnvironment.GetFolderPath(cFolder)) > 0)
	next

	# For this tutorial the file is in the temp folder
	cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_settings-settings.json"])
	if new File().Exists(cFile)
		new File().Delete(cFile)
	ok

	# 1. The first run: there is no file, so the settings have their default values
	oSettings = new Settings(cFile)
	? nl + "First run"
	showSettings(oSettings)

	# 2. The user changes some settings, the program saves them
	oSettings.setValue("name","Ann")
	oSettings.setValue("fontSize",14)
	oSettings.setValue("darkMode",1)
	oSettings.save()
	? nl + "The file now contains: " + new File().ReadAllText(cFile)

	# 3. The next run: a new Settings object reads the file again
	oAgain = new Settings(cFile)
	? nl + "Second run"
	showSettings(oAgain)

	# 4. A file that is damaged must not stop the program: use the defaults
	new File().WriteAllText([ :path = cFile, :contents = "this is not json {" ])
	oBroken = new Settings(cFile)
	? nl + "A damaged file: the defaults are used, error was: " + (len(oBroken.cLoadError) > 0)
	showSettings(oBroken)
	new File().Delete(cFile)

func showSettings oSettings

	? "   name     = " + oSettings.getValue("name")
	? "   fontSize = " + oSettings.getValue("fontSize")
	? "   darkMode = " + oSettings.getValue("darkMode")

# A class for settings: a list of [key, value], defaults, loading and saving
class Settings

	aValues = []
	cFile = ""
	cLoadError = ""

	func init cPath

		cFile = cPath
		# the defaults: the keys that exist, and what they are before the user changes them
		aValues = [["name","Guest"],["fontSize",11],["darkMode",0]]
		readFile()

	func getValue cKey

		for aPair in aValues
			if aPair[1] = cKey
				return aPair[2]
			ok
		next
		return ""

	func setValue cKey, xValue

		for nIndex = 1 to len(aValues)
			if aValues[nIndex][1] = cKey
				aValues[nIndex][2] = xValue
			ok
		next

	# the file holds a JSON object: {"name":"Ann","fontSize":14,"darkMode":1}
	func save

		cJson = "{"
		for nIndex = 1 to len(aValues)
			if nIndex > 1
				cJson += ","
			ok
			xValue = aValues[nIndex][2]
			if isstring(xValue)
				xValue = '"' + xValue + '"'
			ok
			cJson += '"' + aValues[nIndex][1] + '":' + xValue
		next
		cJson += "}"
		new File().WriteAllText([ :path = cFile, :contents = cJson ])

	# read the file and replace the defaults with the values that it has
	func readFile

		cLoadError = ""
		if not new File().Exists(cFile)
			return
		ok
		try
			oDocument = new JsonDocument().Parse(new File().ReadAllText(cFile))
			oRoot = oDocument.RootElement
			for nIndex = 1 to len(aValues)
				aFound = oRoot.TryGetProperty(aValues[nIndex][1])         # [found, element]
				if aFound[1]
					if isstring(aValues[nIndex][2])
						aValues[nIndex][2] = aFound[2].GetString()
					else
						aValues[nIndex][2] = aFound[2].GetInt32()
					ok
				ok
			next
			oDocument.Dispose()
		catch
			cLoadError = cCatchError
		done
Output
Special folders exist:
   MyDocuments : 1
   ApplicationData : 1
   LocalApplicationData : 1
   Desktop : 1

First run
   name     = Guest
   fontSize = 11
   darkMode = 0

The file now contains: {"name":"Ann","fontSize":14,"darkMode":1}

Second run
   name     = Ann
   fontSize = 14
   darkMode = 1

A damaged file: the defaults are used, error was: 1
   name     = Guest
   fontSize = 11
   darkMode = 0

How it works#

A class for settings#

Everything about settings is in one Ring class, Settings, so the rest of the program only says oSettings.getValue("name") and oSettings.setValue("fontSize",14). The class keeps a list of [key, value] pairs: its starting content is the list of defaults, so the keys that exist are defined in one place.

Saving#

save writes a JSON object by hand: texts in quotes, numbers without. For real data with arbitrary text use JsonSerializer (the tutorial JSON and XML), which also escapes quotes and line breaks.

Loading#

readFile first checks that the file exists. Then, inside try, it parses the JSON and, for every known key, asks TryGetProperty(key), which returns [found, element]: if found, the value replaces the default, read as a text (GetString) or a number (GetInt32) depending on the default. Keys that are in the file but unknown are ignored; keys missing from the file keep their default. That makes it safe to add a new setting in a later version.

The damaged file#

The program writes this is not json { to the file and creates a Settings object. The parse raises an error, the catch remembers it in cLoadError, and the defaults stay in place. A real program would also tell the user, or keep the bad file as settings.json.bad and start fresh.

What you learned#

Exercises#

  1. Move the file to ApplicationData\TutorialApp\settings.json (create the folder if needed with Directory.CreateDirectory).
  2. Add a recentFiles setting that holds a list of up to five names.
  3. Make setValue refuse an unknown key with an error.
  4. Use the settings in a window: remember its position and size, and restore them when it opens (the tutorial A small text editor).

Next#

Configuration

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.