# TBMANLIB_Diagnostic Package
{: .no_toc }

**Author:** woeoio. **Version:** 1.0.0.1

The **TBMANLIB_Diagnostic** contributed package makes a diagnostic report of a Windows computer and of the processes that run on it, and writes the report as text, JSON or HTML. The package has three parts. A [**DiagnosticEngine**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticEngine.md) runs *collectors*, classes that each find one kind of information (the operating system, the processor and its load, the memory, the disks, the network, the running processes, the regional settings, the environment variables, the installed runtimes and the uptime), and each returns a [**DiagnosticResult**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticResult.md), a list of pairs of text. A *formatter* turns the results into one string. [**FileHelper**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FileHelper.md) can save the string as a UTF-8 file. The package is written in twinBASIC and calls the Windows API directly. It uses no other library, and none of its collectors asks for administrator rights.

The package is the reusable part of woeoio's entry for [twinBASIC Monthly Challenge #1](/Challenges/1.md), *Self-Contained Diagnostic Tool*. The entry is a console program that shows the values on a live screen, or writes a report when it is started with an argument such as `/json`. That program is not in the package; [**FormatterFactory.CreateFormatterFromArg**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FormatterFactory.md#createformatterfromarg) reads such an argument.

This section documents version 1.0.0.1, published on TWINSERV on 3 February 2026 under the MIT licence. The package compiles in BETA 1034, as a 32-bit and as a 64-bit program. The repository [woeoio/tbman](https://github.com/woeoio/tbman), the toolkit of the same author whose package is [**TBMANLIB**](/tB/Packages/Contributed/TBMANLIB/index.md), does not hold the code of this package.

The package has defects: the **Dictionary** class cannot be used, and several members give a wrong result without an error. [Known problems in version 1.0.0.1](#known-problems-in-version-1001) lists them. The sample below uses the parts that work.

```tb check_build check_run
Dim engine As New DiagnosticEngine
engine.RegisterCollector New OSInfoCollector
engine.RegisterCollector New MemoryInfoCollector
engine.RegisterCollector New UptimeCollector

Dim formatter As IOutputFormatter
Set formatter = FormatterFactory.CreateFormatter("json")

Dim report As String
report = FormatterFactory.FormatResults(engine.RunAll(), formatter)

Dim path As String
path = Environ$("TEMP") & "\diag-report" & formatter.FileExtension
Debug.Print FileHelper.WriteFile(report, path)
Debug.Print FileHelper.GetFileSize(path) > 0
Debug.Print Left$(report, 1)
Debug.Print InStr(report, """memory"": {") > 0
FileHelper.DeleteFile path
' Output:
' True
' True
' {
' True
```

* TOC
{:toc}

## How a report is made

1. **Register collectors.** A new [**DiagnosticEngine**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticEngine.md) has none. A program registers an object of each collector class that it wants with [**RegisterCollector**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticEngine.md#registercollector). The order of registration is the order of the report. The [eleven collectors](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md) of the package are classes with names such as **OSInfoCollector** and **MemoryInfoCollector**, and a program can write its own, see [**IDiagnosticCollector**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/IDiagnosticCollector.md).
2. **Run them.** [**RunAll**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticEngine.md#runall) runs every collector and returns a list of results. [**RunCategory**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticEngine.md#runcategory) runs one by its name, and [**RunByRefreshMode**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticEngine.md#runbyrefreshmode) runs those that change at one rate. The engine raises events and calls callbacks while it works, so a program can show the progress or cancel.
3. **Format.** [**FormatterFactory.CreateFormatter**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FormatterFactory.md#createformatter) makes a [formatter](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Formatters.md) from the name `text`, `json` or `html`, and [**FormatResults**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FormatterFactory.md#formatresults) returns the report as a string. A formatter only builds the string.
4. **Save.** [**FileHelper.WriteFile**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FileHelper.md#writefile) writes the string, and the formatter's **FileExtension** property gives the extension for the file name.

A result can also be read directly, without a formatter. Each [item](/tB/Packages/Contributed/TBMANLIB_Diagnostic/KeyValuePair.md) has a key and a value, both text: the key is the label of the line, such as `Total Physical`, and the value is its text, such as `15.9 GB`.

## Summary reports

[**RunAll**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticEngine.md#runall) takes an argument that asks for the short form. Four collectors have one: [**EnvironmentCollector**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md#environmentcollector), [**RuntimesCollector**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md#runtimescollector), [**ProcessInfoCollector**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md#processinfocollector) and [**NetworkInfoCollector**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md#networkinfocollector). For the process list it gives the counts instead of every process, and for the environment only three variables. The other seven collectors return their full data also in a summary run.

## What a report contains
{: #what-a-report-contains }

> [!NOTE] timeless
> A full report names the user and the computer, the folders in the environment variables such as `USERPROFILE` and `PATH`, every running program, the drives, and the names and IPv4 addresses of the network adapters. Read a report before it goes to someone else.

## Failures

A collector never ends a run. An error that a collector raises, and a failure that it reports itself, give a result with [**Success**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticResult.md#success) set to **False** and a message, and the run goes on; see [A collector that raises an error](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticEngine.md#a-collector-that-raises-an-error). A formatter prints such a result as one line with the key `Error`. The functions of [**FileHelper**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FileHelper.md) that write and read return a text that describes the failure and do not raise an error, and [**List**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/List.md), [**StringBuilder**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/StringBuilder.md) and [**RegisterCollector**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticEngine.md#registercollector) raise run-time errors, which their pages list.

## The Windows functions and the registry

The package declares the Windows functions it calls, in a module of its own, and uses no component that has to be installed. Its references are the OLE Automation library and the **App** object that every twinBASIC project has. These are the libraries and the functions the collectors and the helpers call:

| Library | Functions |
|:--------|:----------|
| `kernel32.dll` | `GetNativeSystemInfo`, `GetComputerNameW`, `GlobalMemoryStatusEx`, `GetSystemTimes`, `GetTickCount64`, `GetLogicalDrives`, `GetDriveTypeW`, `GetDiskFreeSpaceExW`, `CreateToolhelp32Snapshot`, `Process32FirstW`, `Process32NextW`, `CloseHandle`, `GetCurrentProcessId`, `GetTimeZoneInformation`, `GetACP`, `GetOEMCP`, `GetUserDefaultLCID`, `GetLocaleInfoW`, `RtlMoveMemory` |
| `ntdll.dll` | `RtlGetVersion` |
| `advapi32.dll` | `GetUserNameW`, `RegOpenKeyExW`, `RegQueryValueExW`, `RegCloseKey` |
| `shell32.dll` | `IsUserAnAdmin` |
| `iphlpapi.dll` | `GetAdaptersInfo` |
| `ws2_32.dll` | `WSAStartup`, `gethostname`, `WSACleanup` |

The registry is read, never written, with the access `KEY_READ`. The keys are named on the page of the collector that reads them: [CPUInfoCollector](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md#cpuinfocollector) and [RuntimesCollector](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md#runtimescollector).

## Using the package with the Scripting Runtime

The package declares a generic class named **Dictionary**, and the Scripting Runtime (`scrrun.dll`) has a class of that name. The package's class is written with its two type arguments, as in `Dictionary(Of String, Long)`, and the Scripting Runtime's has none. The name with type arguments is the package's class in a project that references both libraries, whichever is listed first. A name without type arguments depends on the order of the references:

| Declaration | Scripting Runtime listed first | Package listed first |
|:------------|:-------------------------------|:---------------------|
| `Dim a As New Dictionary` | the class of the Scripting Runtime | error TB5136, *Unable to bind to generic class 'Dictionary'; no generic specifiers given* |
| `Dim b As Dictionary(Of String, Long)` | the class of the package | the class of the package |
| `Dim c As New Scripting.Dictionary` | the class of the Scripting Runtime | the class of the Scripting Runtime |
| `Dim d As New TBMANLIB_Diagnostic.Dictionary(Of String, Long)` | the class of the package | the class of the package |

A project that wants the Scripting Runtime's class writes `Scripting.Dictionary`, which does not depend on the order. The package's class cannot be created in version 1.0.0.1 (see [**Dictionary**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Dictionary.md)), so a project has no reason to write its name. A project with only the package, which has no `Scripting` library, shows the first row of the table:

```tb check_build expect-error=TB5136
Dim a As New Dictionary
```

```tb check_build
Dim b As Dictionary(Of String, Long)
Dim d As TBMANLIB_Diagnostic.Dictionary(Of String, Long)
```

The modules of the package are public, so a project that references it can use their names without the name of the module: `GetTickCount64`, `FILETIME` and `KEY_READ` of the **WinAPI** modules are visible, and so is `FileTimeToLongLong`. Where a name is declared in the project as well, such as its own `Declare` of `CloseHandle`, its own `Type FILETIME` or its own `Const KEY_READ`, written **Private** or **Public**, the project compiles and uses its own declaration. A call of **FormatDateTime** without the module name reaches the function of the runtime library, not the one of [**FormatHelper**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FormatHelper.md#formatdatetime). Write the name of the module before a name of the package that another declaration has too, as in `WinAPIStructures.KEY_READ` and `FormatHelper.FormatDateTime`.

## Types that have no page

The package has four modules whose contents a program has no need for:

- **WinAPI** declares the Windows functions that the package calls, eight console and registry functions that it does not call (`GetStdHandle`, `SetConsoleCursorPosition`, `SetConsoleTextAttribute`, `GetConsoleScreenBufferInfo`, `SetConsoleCtrlHandler`, `FillConsoleOutputCharacterW`, `FillConsoleOutputAttribute` and `RegEnumKeyExW`), and four helper procedures: `MakeCOORD`, `FileTimeToLongLong`, `GetStringFromBuffer` and `GetStringFromByteBuffer`. [The WinAPI helpers](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md#the-winapi-helpers) describes the two that matter to the results.
- **WinAPIStructures** declares the record types and the constants of those functions: `OSVERSIONINFOEXW`, `SYSTEM_INFO`, `MEMORYSTATUSEX`, `FILETIME`, `PROCESSENTRY32W`, `IP_ADDR_STRING`, `IP_ADAPTER_INFO`, `TIME_ZONE_INFORMATION`, `SYSTEMTIME`, `COORD`, `SMALL_RECT` and `CONSOLE_SCREEN_BUFFER_INFO`.
- **DelegatesModule** declares the four delegate types. Three are the types of the callbacks of the engine, see [Delegates](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticEngine.md#delegates), and the fourth is [**FormatterFactoryDelegate**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FormatterFactory.md#formatterfactorydelegate).
- **RefreshModeModule** holds only the enumeration [**RefreshMode**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/RefreshMode.md).

## Known problems in version 1.0.0.1

> [!WARNING] 1.0.0.1
> The package gives a wrong result without an error, or loses data, in these cases.
>
> - **[List.Insert](/tB/Packages/Contributed/TBMANLIB_Diagnostic/List.md#insert) puts the new item one place too late**, and **[List.SetItem](/tB/Packages/Contributed/TBMANLIB_Diagnostic/List.md#setitem) with the index 0 puts it in the second place.** `SetItem` with the index 0 on a list of one item removes the item and then raises error 5, so the list is empty afterwards.
> - **[FileHelper.WriteFile](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FileHelper.md#writefile) does not shorten an existing file.** The bytes after the new content stay: writing `ab` over a file of 13 bytes leaves a file of 13 bytes.
> - **[ReadFile](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FileHelper.md#readfile) and [GetFileSize](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FileHelper.md#getfilesize) create a file that does not exist.** **ReadFile** returns an empty string and **GetFileSize** returns 0, as for an empty file, so a missing file is not told from an empty one.
> - **ReadFile does not decode UTF-8 or remove the byte-order mark that WriteFile writes.** The text `café` written with **WriteFile** is read back as 8 characters.
> - **[NormalizePath](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FileHelper.md#normalizepath) and [GetFullPath](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FileHelper.md#getfullpath) turn a UNC path into a relative one.** `\\server\share\f.txt` becomes `server\share\f.txt`, and the file functions then open a file of that relative name.
> - **[EscapeJson](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FormatHelper.md#escapejson) leaves the control characters 1 to 31, other than line feed, carriage return and tab, unescaped**, so [**JsonFormatter**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Formatters.md#jsonformatter) can write JSON that a parser rejects.
> - **[FormatBytes](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FormatHelper.md#formatbytes) with no decimals leaves the decimal separator in the text**, as in `4. KB`. The `Page Size` item of [**CPUInfoCollector**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md#cpuinfocollector) is written this way.
> - **[NetworkInfoCollector](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md#networkinfocollector) lists the first adapter only in a 64-bit program.** It reads the adapters in steps of 640 bytes, and the records are 704 bytes apart in a 64-bit program. The summary may then have no `Primary IP`. A 32-bit program lists every adapter.

> [!WARNING] 1.0.0.1
> **[LocaleCollector](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md#localecollector) reports the offset of standard time as `Timezone` all year.** In summer time the item is behind the clock by the daylight saving offset: `UTC+1` where the clock is at UTC+2, as in Central European Summer Time.

> [!NOTE] 1.0.0.1
> The package has these other problems. Each raises an error.
>
> - **A [Dictionary](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Dictionary.md) cannot be created.** `New Dictionary(Of TKey, TValue)` raises run-time error 91, *Object variable or With block variable not set*.
> - **[List.Contains](/tB/Packages/Contributed/TBMANLIB_Diagnostic/List.md#contains), [IndexOf](/tB/Packages/Contributed/TBMANLIB_Diagnostic/List.md#indexof) and [Remove](/tB/Packages/Contributed/TBMANLIB_Diagnostic/List.md#remove) raise error 438**, *Object doesn't support this property or method*, for a list of objects of a class that has no default member.
> - **[List.Insert](/tB/Packages/Contributed/TBMANLIB_Diagnostic/List.md#insert) with the index 0 raises error 5 on an empty list.**
> - **[WriteFile](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FileHelper.md#writefile) and [AppendFile](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FileHelper.md#appendfile) make only the last folder of a path.** For a path whose parent folder is missing they return the error text `Error -2147467259: Unspecified error` and the path. The **Open** statement raises error 76, *Path not found*, for it in VB6.

Two behaviours follow from the code and can look like defects. [**CPULoadCollector**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md#cpuloadcollector) reports 0 for its first reading, because it measures between two calls. [**JsonFormatter**](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Formatters.md#jsonformatter) writes every value as a string and turns `PATH` into `pATH`.

## Pages

**Engine and results**

- [DiagnosticEngine](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticEngine.md) -- registers collectors, runs them, and raises events and callbacks
- [DiagnosticResult](/tB/Packages/Contributed/TBMANLIB_Diagnostic/DiagnosticResult.md) -- the items, the time and the success of one collection
- [KeyValuePair](/tB/Packages/Contributed/TBMANLIB_Diagnostic/KeyValuePair.md) -- one key with one value
- [RefreshMode](/tB/Packages/Contributed/TBMANLIB_Diagnostic/RefreshMode.md) -- how often the data of a collector changes

**Collectors**

- [IDiagnosticCollector](/tB/Packages/Contributed/TBMANLIB_Diagnostic/IDiagnosticCollector.md) -- the contract of a collector
- [Collectors](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Collectors.md) -- the eleven collectors of the package, what each reports and which Windows functions it calls

**Formatters**

- [IOutputFormatter](/tB/Packages/Contributed/TBMANLIB_Diagnostic/IOutputFormatter.md) -- the contract of a formatter
- [Formatters](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Formatters.md) -- the text, JSON and HTML formatters
- [FormatterFactory](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FormatterFactory.md) -- creates a formatter by name, and formats a list of results

**Helpers**

- [FormatHelper](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FormatHelper.md) -- formats sizes, durations, percentages, dates and text, and escapes text for JSON and HTML
- [FileHelper](/tB/Packages/Contributed/TBMANLIB_Diagnostic/FileHelper.md) -- writes, appends to and reads text files, tests for files and folders, and takes paths apart
- [List](/tB/Packages/Contributed/TBMANLIB_Diagnostic/List.md) -- a list with a 0-based index
- [Dictionary](/tB/Packages/Contributed/TBMANLIB_Diagnostic/Dictionary.md) -- values found by a key; it cannot be created in version 1.0.0.1
- [StringBuilder](/tB/Packages/Contributed/TBMANLIB_Diagnostic/StringBuilder.md) -- builds a long string from parts

## See Also

- [TBMANLIB](/tB/Packages/Contributed/TBMANLIB/index.md) package -- the toolkit of the same author
- [VBA_JSON](/tB/Packages/Contributed/VBA_JSON/index.md) package -- reads JSON, such as the report that **JsonFormatter** writes
- [Importing a package from TWINSERV](/Features/Packages/Importing-TWINSERV.md) -- adding a published package to a project

## Test cases

The notes and warnings of this section are checked by the test cases in [TBMANLIB_Diagnostic-tests.twinproj](TBMANLIB_Diagnostic-tests.twinproj), a twinBASIC project. It uses TBMANLIB_Diagnostic as a [linked package](/Features/Packages/Linked.md#manual-management): put the package's `.twinpack` in `%APPDATA%\twinBASIC\packages`, then run the project, and each case prints whether it passes.
