1. General information
- This guide describes the custom API – a web application programmed separately for each customer and running next to a full installation of NET Genium.
- NET Genium distinguishes two more kinds of API, which are not programmed and which this guide does not describe:
- The integrated API is part of every NET Genium instance and is intended for administrators – it consists of the integrated MCP server and the web services for the “NETGeniumConnection.dll” library (chapter 1.1).
- The partner API is intended for implementation partners and provides the Agent Kit and the complete framework documentation. A detailed description of the partner API is provided in the separate guide Partner MCP server.
- Next to its own tools, the MCP server of the custom API can also serve ready-made tools for the implementation model (within the rights of the connected user) and framework knowledge – the same ones the integrated MCP server of the instance serves (chapter 6.2).
- A comparison of all three kinds of API is provided on the page How integration works.
- The custom API is a web application located on a server, available at a specific address/domain for all devices that have access to the Internet.
- The custom API is used in cases where it is necessary to expose an endpoint that
- returns data read from a database,
- receives data from client applications and stores it in the database,
- returns the contents of file attachments,
- etc.
1.1. Integrated API for the NETGeniumConnection.dll library
- Each NET Genium has an implemented API that can be used from applications written in C# in conjunction with the “NETGeniumConnection.dll” library. It is part of the integrated API, so no custom API is programmed for it.
- This API is intended for clients that have full access to the database. The source code corresponds to this, which is written identically as if it were an application that connects to the database directly (not via web services).
- A typical example of such an application is a console application, but it can also be a desktop application, web application, etc.
- A detailed description of console applications is given in the separate article Console applications.
1.2. Custom API with limited access to the database
- The custom API can return data defined using SQL queries. These queries are configured by the NET Genium administrator in a separate application called “API”.
- Each SQL query has its own unique identifier “sqlid”, which clients use to display the URL request, for example “http://localhost/netgenium/api/data/{sqlid}”.
- The URL can contain multiple parameters, usually used to load a specific record, for example: “http://localhost/netgenium/api/data/{sqlid}/{id}”. These parameters are then accessible using the following variables:
- #path0#: data
- #path1#: {sqlid}
- #path2#: {id}
- The SQL query itself can contain server function calls or use variables to limit the range of data retrieved.
- Only some of the server functions are evaluated in it – for example “ADDDAYS”, “FORMATDATESQL”, “FORMATINTSQL”, “FORMATSTRINGSQL”, “SUBSTRING” or “SQL”.
- Of the variables, besides the “#path...#” variables, mainly the date and time variables (for example “#now#” and “#today#”), “#crlf#”, “#tab#”, “#comma#”, “#doublequotes#” and “#sharp#” are substituted.
- Examples of SQL queries:
- SELECT * FROM ng_apidata WHERE ng_identifier = FORMATSTRINGSQL(#path1#)
- SELECT * FROM ng_apidata WHERE id = FORMATINTSQL(#path2#)
- SELECT * FROM ng_apidata WHERE ng_createdon < FORMATDATESQL(#now#)
- A URL parameter is substituted into the SQL query as it is, without any escaping. When used in a condition, it must therefore always be wrapped in the “FORMATSTRINGSQL”, “FORMATINTSQL” or “FORMATDATESQL” server function, which converts it into a safe SQL literal. The “#” character is removed from a URL parameter.
- The API is implemented through a separate project in the “Visual Studio 2015” application and higher, or by programming the source codes of this project, followed by compiling the project into a “dll” format file.
2. Importing the application API into NET Genium
- In the first step, it is necessary to import “API.nga” into the NET Genium application, which is located in the “Install” directory of each NET Genium. The “API” application is used to define SQL queries that the resulting API will return to client devices, and to configure tokens that client devices must use to authenticate.
- On the “Tokens” view page, it is necessary to create at least one access token. This token must be passed on securely to client devices that will retrieve data using the API.
- At least one SQL query is required on the “Endpoints” view page, for example:
- Identifier: susers
- SQL: SELECT * FROM susers
3. Creating an API project in Visual Studio
- In the second step, it is necessary to create a new web application project in Visual Studio using the following steps:
- Start Visual Studio
- From the main menu bar, select “File / New / Project...” (Ctrl+Shift+N)
- Project type: ASP.NET Web Application (.NET Framework)
- Project name: api
- Location: optional project location
- Solution: Create new solution
- Place solution and project in the same directory: Yes
- Create directory for solution: No (Visual Studio 2015)
- Framework: .NET Framework 4.7.2
- Click the “Create” button
- Project Template: Empty
- Configure for HTTPS: No
- Click the “Create” button
- Right-click on “References”
- select “Manage NuGet Packages...”,
- select the tab “Installed”,
- select the item “Microsoft.CodeDom.Providers.DotNetCompilerPlatform”,
- click the “Uninstall” button.
- Open the “bin” directory in the explorer via “My Computer”,
- delete the file “Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll”,
- delete the file “Microsoft.CodeDom.Providers.DotNetCompilerPlatform.xml”.
- Right-click on the project name “api”,
- select “Add” / “New Item...” (Ctrl+Shift+A),
- select the folder “Installed / Visual C# / Web / General”,
- select the file type “Global Application Class”,
- check the contents of the “Name” field to have the value “Global.asax”, and confirm with the “Add” button.
- Select the “Debug” compilation mode
- “Debug” mode generates “dll” and “pdb” format files by default
- Thanks to the “pdb” format file, errors and breaks in the API are easily detected, because the “Stack Trace” of each error also includes the file name and line number where the break occurred
- “Release” mode is recommended only for the final version of the tuned source codes in the API. By default, “Release” mode generates only a “dll” format file.
- Start the project – from the menu on the main bar, select “Debug” / “Start Debugging” (F5)
3.1. Adding a reference to the “NETGeniumConnection.dll” library
- Right-click on “References”, select “Add Reference...”, and select the path to the “References\NETGeniumConnection.dll” file on the computer’s disk
3.2. Editing the “Web.config” configuration file
- Replace the contents of the “Web.config” file with the following code:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="ConnectionString" value="driver=firebird;datasource=localhost;user=SYSDBA;password=masterkey;database=C:\Firebird\netgenium.fdb;charset=WIN1250;collation=WIN_CZ" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<sessionState cookieless="false" />
<httpRuntime targetFramework="4.7.2" />
</system.web>
</configuration>
3.3. Editing the Global.asax.cs file and the Application_BeginRequest method
- Right-click on the file name “Global.asax”, and select “View Code” (F7)
- Replace the contents of the file “Global.asax.cs” with the following source code:
using NETGenium;
using Newtonsoft.Json.Linq;
using System;
using System.Net;
namespace api
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
NETGenium.Web.Page.Application_Start();
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
ApiResponse re = new ApiResponse();
if ((re.Request.Path[0] == "data" && (re.Request.Path.Length == 2 || re.Request.Path.Length == 3)) || re.Request.Path[0] == "import")
{
re.Request.LogUrl();
re.Request.LogBody();
using (DbConnection conn = DbConnection.UsingSettingsFromWebConfig(true))
using (DbCommand cmd = new DbCommand(conn))
try
{
string token = re.Request.AuthorizationToken;
if (token == null || !new DbRow("SELECT id FROM ng_apitoken WHERE ng_apitoken = " + conn.Format(token) + " AND ng_expiration > " + conn.Format(DateTime.Today), conn).Read())
{
throw new UnauthorizedAccessException();
}
if (re.Request.Path[0] == "data")
{
#region data
DbRow dr = new DbRow("SELECT ng_sql FROM ng_apidata WHERE ng_identifier = " + conn.Format(re.Request.Path[1]), conn);
if (!dr.Read())
{
throw new UnauthorizedAccessException();
}
string query = re.Request.ReplaceVariables(dr["ng_sql"].ToString(), conn);
if (!DbQuery.IsValidSelect(query))
{
throw new UnauthorizedAccessException(query);
}
re.LogVerbose(query);
re.DataTable = Data.Get(query, conn);
#endregion
}
else if (re.Request.Path[0] == "import")
{
#region import
var r = JObject.Parse(re.Request.Body);
if (r.ContainsKey("value"))
{
string guid = Guid.NewGuid().ToString();
DataSaver ds = new DataSaver("ng_data", 0, cmd);
ds.Add("ng_guid", guid);
ds.Add("ng_value", (string)r["value"]);
ds.Execute();
re.HTML = guid;
}
else
{
throw new Exception("Invalid request");
}
#endregion
}
}
catch (UnauthorizedAccessException ex)
{
re = new ApiResponse(HttpStatusCode.Unauthorized);
re.LogWarning("Application_BeginRequest", ex);
}
catch (ArgumentException ex)
{
re = new ApiResponse(HttpStatusCode.BadRequest);
re.LogWarning("Application_BeginRequest", ex);
}
catch (Exception ex)
{
re = new ApiResponse(HttpStatusCode.InternalServerError);
re.LogError("Application_BeginRequest", ex);
}
re.Flush();
}
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
NETGenium.Web.Page.Application_Error(out Exception ex);
if (ex != null)
{
L.E("Application_Error", ex);
Server.ClearError();
}
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
}
- In this pattern, client devices authorize themselves with a token from the “ng_apitoken” table. When the other party requires a client certificate instead of a token, the certificate is verified by the IIS web server before this code even runs – a detailed description is provided in the separate guide Client certificate authentication.
3.4. Testing the API using a console application
- Create an empty console application with a reference to the library “NETGeniumConnection.dll” see the Console applications guide
- Replace the contents of the file “Program.cs” with the following source code:
using NETGenium;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
NETGeniumConsole console = new NETGeniumConsole();
using (DbConnection conn = new DbConnection())
{
conn.Open("http://localhost/netgenium", "Administrator", File.ReadAllText(Config.RootPath + "password.txt"));
string token = Data.ExecuteScalar("SELECT ng_apitoken FROM ng_apitoken WHERE ng_expiration > " + conn.Format(DateTime.Today), conn), url, errorresponse = null;
if (true)
{
#region data
url = "http://localhost/netgenium/api/data/susers";
try
{
Uploader.LogToConsole = true;
Uploader.Upload(url, null, token, null, Encoding.UTF8, out errorresponse);
}
catch (Exception ex)
{
L.W(url, ex);
if (errorresponse != null)
{
L.V("RESPONSE: " + errorresponse);
}
}
#endregion
}
if (false)
{
#region import
url = "http://localhost/netgenium/api/import";
StringBuilder sb;
using (JsonWriter writer = new JsonTextWriter(new StringWriter(sb = new StringBuilder())))
{
writer.WriteStartObject();
writer.WritePropertyName("value");
writer.WriteValue("test");
writer.WriteEndObject();
}
try
{
Uploader.LogToConsole = true;
Uploader.UploadJSon(url, null, sb.ToString(), token, null, Encoding.UTF8, out errorresponse);
}
catch (Exception ex)
{
L.W(url, ex);
if (errorresponse != null)
{
L.V("RESPONSE: " + errorresponse);
}
}
#endregion
}
}
console.Exit();
}
}
}
4. Request serialization and deserialization
4.1. Changing the data parsing method
- Client-side serialization involves converting data from a specific class (DTO object) to a JSON-formatted text string instead of using the generic “JsonWriter” object.
- Server-side deserialization involves converting a JSON-formatted text string to a specific class (DTO object) instead of using the generic object using “JObject.Parse”.
4.2. Console application serialization
- Replace the contents of the “import” region in the “Program.cs” file with the following source code:
// Original code
StringBuilder sb;
using (JsonWriter writer = new JsonTextWriter(new StringWriter(sb = new StringBuilder())))
{
writer.WriteStartObject();
writer.WritePropertyName("value");
writer.WriteValue("test");
writer.WriteEndObject();
}
Uploader.UploadJSon(url, null, sb.ToString(), token, null, Encoding.UTF8, out errorresponse);
// New code
namespace ConsoleApp1.DTO
{
public class Request
{
public string data;
}
}
var request = new DTO.Request();
request.data = "test";
Uploader.UploadJSon(url, null, JsonConvert.SerializeObject(request), token, null, Encoding.UTF8, out errorresponse);
4.3. Deserialization in the server-side API
- Replace the content of the “import” region in the “Global.asax.cs” file with the following source code:
// Original code
var r = JObject.Parse(re.Request.Body);
if (r.ContainsKey("value"))
{
string guid = Guid.NewGuid().ToString();
DataSaver ds = new DataSaver("ng_data", 0, cmd);
ds.Add("ng_guid", guid);
ds.Add("ng_value", (string)r["value"]);
ds.Execute();
re.HTML = guid;
}
else
{
throw new Exception("Invalid request");
}
// New code
var r = JsonConvert.DeserializeObject<DTO.Request>(re.Request.Body);
string guid = Guid.NewGuid().ToString();
DataSaver ds = new DataSaver("ng_data", 0, cmd);
ds.Add("ng_guid", guid);
ds.Add("ng_value", r.data);
ds.Execute();
re.HTML = guid;
5. Response serialization and deserialization
5.1. ApiResponse
- Serialization on the server side is performed automatically in the “Flush” method of the “ApiResponse” object.
- Deserialization on the client side consists of converting the response to a specific class (DTO object).
- In a web application, the “Flush” method writes the response and ends it with the “EndResponseException” exception (enabled by calling “NETGenium.Web.Page.Application_Start()” in the “Application_Start” method). The code after the call of “Flush” therefore does not run, and a “catch (Exception)” block wrapping the call of “Flush” has to let the “EndResponseException” exception through:
try
{
// ...
re.Flush();
}
catch (EndResponseException)
{
throw;
}
catch (Exception ex)
{
re = new ApiResponse(HttpStatusCode.InternalServerError);
re.LogError("Application_BeginRequest", ex);
re.Flush();
}
5.2. Serialization in the API on the server side
- Automatic serialization of the “ApiResponse” object occurs if none of the following properties of the “ApiResponse” object are set:
- Dictionary – data type Dictionary<string, string>
- Automatic conversion to JSon
- The content of the “Content-Type” header is set to “application/json”
- DataTable – data type DataTable
- Automatic conversion to JSon
- The content of the “Content-Type” header is set to “application/json”
- DataView – data type DataView
- Automatic conversion to JSon
- The content of the “Content-Type” header is set to “application/json”
- DbRow – data type DbRow
- Automatic conversion to JSon
- The content of the “Content-Type” header is set to “application/json”
Details
- DataTable and DataView are converted to an array of objects, one object for each row, with the column names as the property names. An empty table is converted to an empty array “[]”.
- DbRow is converted to an array with one object. If the query finds no record, it is converted to an empty array “[]”. With DbRow, the property names are converted to lower case and, with a direct connection to the database, a repeated column name gets the suffix “_” (for example “id_”), so they can differ from the names that DataTable returns for the same query.
- A NULL value and a value of type float or double that is not a finite number (NaN, infinity) are written as null, other values of type int, long, float, double and decimal as numbers, binary data as Base64-encoded text, a nested table (DataTable) and an array of values as a JSON array, and other values as text. A date and time read from the database is written as text in the ISO 8601 format without a time zone designator (for example “2026-11-20T14:30:00.0000000”), that is, as it is stored in the database. A date and time that code put into the table and that carries time zone information (for example DateTime.Now or DateTime.UtcNow) is written with an offset from UTC or with the “Z” designator.
- FilePath, or FileName – data type string
- Automatic conversion to a stream, so the response result is a byte stream with the content of the downloaded file
- Header content “Content-Type” is set depending on the type of file being downloaded – for example “application/octet-stream”
- The content of the “Content-Disposition” header is set to “attachment; filename=” plus the file name in the “FileName” variable
- If the value of the “FileName” variable is null, the file name is automatically evaluated according to the file name in the “FilePath” variable
- HTML – data type string
- The response result is this string
- The content of the “Content-Type” header is set to “text/plain; charset=utf-8”
- XML – data type string
- The response result is this string
- The content of the “Content-Type” header is set to “text/xml; charset=utf-8”
- JSon – data type string
- The response result is this string
- The content of the “Content-Type” header is set to “application/json”
- If more than one of the above properties is set, the first one in this order is used: FilePath, JSon, HTML, XML, Dictionary, DataTable, DataView, DbRow
- If none of the above properties are set, the response results in automatic serialization of the “ApiResponse” object into JSON format
- The public fields and properties of the class derived from “ApiResponse” are serialized – the properties of the “ApiResponse” class itself do not get into the JSON
- The “Content-Type” header is set to “application/json”
- The typical usage is a custom response class derived from “ApiResponse”:
// Original code
ApiResponse re = new ApiResponse();
// ...
re.Flush();
// New code
public class MyResponse : ApiResponse
{
public string error;
}
// New code – option 1
MyResponse re = new MyResponse();
// ...
re.Flush();
// New code – option 2
ApiResponse re = new ApiResponse();
// ...
if (true)
{
re = new MyResponse();
}
re.Flush();
5.3. Deserialization in a console application
// Original code
Uploader.UploadJSon(url, null, JsonConvert.SerializeObject(request), token, null, Encoding.UTF8, out errorresponse);
// New code
public class MyResponse : ApiResponse
{
public string error;
}
string response = Uploader.UploadJSon(url, null, JsonConvert.SerializeObject(request), token, null, Encoding.UTF8, out errorresponse);
var r = JsonConvert.DeserializeObject<MyResponse>(response);
6. MCP server
- MCP (Model Context Protocol) is an open standard for communication between AI agents and tools that provide data or perform actions. An MCP server exposes a set of named tools that an AI agent can call.
- The API project makes it possible to expose an MCP server on the “/mcp” endpoint with minimal code – it is enough to implement one class.
- Not to be confused with the integrated MCP server of a NET Genium instance, which serves data, the model of the implementation and the knowledge of the framework – that one has the address “/mcp” in the root of the instance, the client proves its identity to it with a personal MCP token or by the sign-in of the user, and it requires no programming at all. The MCP server described here is, on the contrary, the server of a customer solution whose tools you program yourself. The tools for the implementation model and framework knowledge need not be programmed – the base class offers them ready-made (chapter 6.2).
6.1. Wiring the endpoint in Global.asax.cs
- Replace the content of “Global.asax.cs” with the following source code. Authentication works the same way as for the data API – the token is validated against the “ng_apitoken” table:
using NETGenium;
using System;
using System.Net;
namespace api
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
NETGenium.Web.Page.Application_Start();
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
ApiResponse re = new ApiResponse();
if (re.Request.Path[0] == "mcp")
{
using (DbConnection conn = DbConnection.UsingSettingsFromWebConfig(true))
re.HandleMcpRequest(new MyMcpServer(conn), conn);
}
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
NETGenium.Web.Page.Application_Error(out Exception ex);
if (ex != null)
{
L.E("Application_Error", ex);
Server.ClearError();
}
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
}
- The “HandleMcpRequest” method handles the whole request to the endpoint of the MCP server: it writes the address and the body of the request to the log, answers the “OPTIONS” request (CORS preflight) with status code 204 and refuses any other method than “POST” with status code 405. For a “POST” request it authenticates the caller by the “Authorize” method of the MCP server and only then passes the request to it. The default “Authorize” validates the personal MCP token of the user (chapter 7), the MCP server of the example overrides it by validating the shared token from the “ng_apitoken” table (chapter 6.2). “Authorize” reports an invalid token by the “UnauthorizedAccessException” exception, which the method answers with status code 401. It answers the “ArgumentException” exception with status code 400, other exceptions with status code 500, and writes all of them to the log.
- The answer to the “OPTIONS” request (CORS preflight) carries the “Access-Control-Allow-Origin”, “Access-Control-Allow-Methods”, “Access-Control-Allow-Headers” and “Access-Control-Max-Age” headers added by the “AppendCorsPreflightHeaders” method, and the answer to the “POST” request carries the “Access-Control-Allow-Origin” header added by the “AppendCorsHeaders” method. Both methods write the headers to the response right away, so they remain valid even after the “re” object is replaced with a new “ApiResponse” (on an error, for example) – except for a file response (“FilePath”), whose “Flush” clears the headers. Without them, clients running in a browser cannot connect to the server. Clients calling the server from another server send no preflight.
Details
- The “HandleJsonRpc” method, which “HandleMcpRequest” calls, handles the entire JSON-RPC 2.0 protocol: request deserialization (a body that is not valid JSON returns the -32700 Parse error), acknowledging notifications, catching “MethodNotFoundException” and “InvalidParamsException”, and response serialization. A notification sent on its own (a request with a “method” and without an “id”) is acknowledged with the status code 202 and an empty body and is not passed to the server class, so the server cannot react to notifications. It also automatically supports batch requests (a request body starting with “[”) – each request in the array with an “id” is processed independently and the results are returned as a JSON array. Items of the array without an “id” are skipped and a batch in which no item has an “id” is acknowledged with the status code 202 and an empty body.
6.2. The McpServer abstract class
- The “HandleMcpRequest” and “HandleJsonRpc” methods accept an instance of a class inheriting from “NETGenium.JsonRpc.McpServer”.
- The implementation requires overriding two abstract properties and two abstract methods:
| Member |
Description |
| ServerName |
Server name returned in the “initialize” response |
| ServerVersion |
Server version returned in the “initialize” response |
| HandleToolsList() |
Returns the list of tools for “tools/list” |
| HandleToolsCall(JToken) |
Processes a tool call for “tools/call” |
- The virtual “Authorize(request, conn)” method, which the “HandleMcpRequest” method calls before the request is handled, can be overridden as well. By default it validates the personal MCP token of the user (chapter 7). An implementation that authenticates the callers otherwise (by a shared token, for example) overrides it and reports an invalid token by the “UnauthorizedAccessException” exception.
- The “initialize” handler is implemented in the base class and does not need to be overridden. The base class negotiates the MCP protocol version during “initialize” – if the client requests one of the supported versions (2025-03-26, 2025-06-18, 2025-11-25), it is used. Otherwise the latest supported version is returned.
Details
- The base class also handles the “ping” request (an empty answer) and the “resources/list”, “resources/templates/list” and “prompts/list” requests (an empty list). Any other method ends with the -32601 error. The answers can be changed by overriding the virtual methods “HandleInitialize”, “HandlePing”, “HandleResourcesList”, “HandleResourceTemplatesList” and “HandlePromptsList”. The base class cannot read resources or prompts (the “resources/read” and “prompts/get” requests), so the server cannot publish resources or prompts.
- The base class provides the following helper methods:
| Method |
Description |
| ReadTool(name, title, description, inputSchema, openWorld) |
Builds a descriptor of a tool that only reads and never changes anything (readOnlyHint) |
| WriteTool(name, title, description, inputSchema, openWorld, idempotent) |
Builds a descriptor of a tool that only adds data and never overwrites or destroys anything (destructiveHint false) |
| DestructiveTool(name, title, description, inputSchema, openWorld, idempotent) |
Builds a descriptor of a tool that may overwrite or destroy data or change it irreversibly (destructiveHint true) |
| Tool(name, description, inputSchema) |
Builds a tool descriptor without a title and annotations |
| Str(description) |
Builds a JSON Schema string property |
| Arg(parameters, key) |
Extracts a named string argument from “tools/call” and safely returns an empty string when the argument is missing, is null or “arguments” is not an object (resilience against a malformed request). A Boolean value is returned as “true” or “false”, an argument of the object or array type as its JSON notation |
| ArgDate(parameters, key) |
Extracts a required date argument written as yyyy-MM-dd. When it is missing, empty or written in another form (also a date with a time or written by a culture), the call ends with error -32602, which the language model corrects by itself – the date is never guessed |
| ArgDate(parameters, key, defaultValue) |
The same for an optional argument – when it is missing or empty, “defaultValue” is returned |
| ArgList(parameters, key) |
Extracts a list argument – a JSON array, or a text with the items separated by commas, as language models send it. The items are trimmed and empty items left out, a missing argument gives an empty list |
| RecordUrl(value, out formId, out id) |
Reads a link to a NET Genium record that a user copied from the browser – the ID of the record from the “id” parameter and the ID of the edit form from the “form” parameter (0 without it). Returns false when the value is not a link with the “id” parameter – it is then usually an ID or a number of the record |
| ToolHtml(html) |
Prepares the HTML content of a record (RichTextBox, e-mail) for the result of a tool – links to attachments are replaced by “attachment:<id>”, the head and styles of a whole HTML document are removed and images embedded as Base64 are replaced by a short placeholder with their size |
| TextToHtml(text, conn) |
Converts the text a language model sent to a tool into HTML to be stored in a RichTextBox control – plain text is encoded and its line breaks are converted to “<br>”, comments and unsafe tags are removed from HTML |
| AttachmentResult(id, conn) |
Returns the content of an attachment as the result of a tool – a text file (by its extension) as JSON with the ID, file name, content type, size and the text, other files as Base64. The text is decoded by its byte order mark (BOM), without one as UTF-8, and when it is not valid UTF-8 by the code page of the server. An attachment that does not exist, a file larger than 10 MB or missing on the server ends with error -32602. Access rights are not checked |
| AttachmentResult(id, path, conn) |
The same from the given file – for an implementation that resolves the file of the attachment itself |
| AddAttachment(attachments, id, source) and AddAttachments(attachments, html, source) |
Builds the list of the attachments of a record – the ID of an attachment from a File or Image column, or all the attachments an HTML value refers to (embedded images and links), together with where in the record they are. Every attachment is listed once |
| AttachmentsTable(sb, attachments, conn) |
Writes the attachments of a record as a Markdown table – the ID, where in the record, the file name, the type, the size and whether the file is on the server. A tool that reads an attachment then gives only an attachment from this list |
| UserNames(logins, conn) and UserName(login, names) |
Looks up the full names of users by their login names and writes a user as “login (Full name)” |
| RecordHistory(table, id, columns, htmlColumns, fullVersions, skip, toolName, conn) |
Writes the change history of a record from the oldest change – when and by whom the record was saved and the new values of the given columns that changed at that save. HTML columns are written whole in the first version and then as a line diff against the previous version. Output over 300,000 characters is cut, and the language model is told to continue with the “skip” parameter. Neither access rights nor the permissibility of the columns are checked |
| Value(value) and Value(row, column) |
Writes the value of a column for the result of a tool – an empty value as an empty string, a date as yyyy-MM-dd (with a time yyyy-MM-dd HH:mm), other values regardless of the culture |
| Id(row, column) |
Writes an ID stored in a column (typically a foreign key) – an empty value and zero as an empty string |
| Cell(value) |
Prepares a value for a cell of a Markdown table – the vertical bar is escaped and tabs and line breaks are replaced so that the value stays on one line |
| TableRow(sb, name, value) |
Appends a row of a two-column Markdown table with the name of a field and its value. An empty value leaves the row out |
| ToolResult(content) |
Wraps text in the standard MCP tool-result envelope |
| ToolResult(fileName, base64) |
Wraps a file given by its Base64 content in the standard MCP tool-result envelope. The content type is derived from the extension of the file name – PNG, JPEG, GIF and WebP images are returned as an image block, other files as an embedded resource |
- Register the tools with the “ReadTool”, “WriteTool” and “DestructiveTool” methods – besides the name they publish a readable title and all four behaviour annotations (“readOnlyHint”, “destructiveHint”, “idempotentHint” and “openWorldHint”) the client decides by when to ask the user for confirmation. The Anthropic connectors directory requires both the title and the hint for every tool and the OpenAI plugins directory requires every annotation to be set explicitly to true or false – none of them may be missing – so use the “Tool” method without them only for a server that is headed to no directory at all. What decides between “WriteTool” and “DestructiveTool” is whether the tool only adds: one that overwrites existing values (an update of a record, typically) or removes them belongs to “DestructiveTool”. An annotation that does not match what the tool really does is the most common reason for a rejection in the OpenAI plugins directory, where each of them is justified as well.
- The last two parameters are optional and false by default. All three methods take “openWorld” – set it to true only for a tool that reaches outside of the application it belongs to: it calls a service on the internet, publishes content or sends a message out. A tool working only with the data of its own implementation keeps it false. Only “WriteTool” and “DestructiveTool” take “idempotent” (a tool registered through “ReadTool” always has it true) – set it to true when calling the tool again with the same arguments changes nothing further, as with deleting an already deleted record or renaming to the same name. A tool that creates a new record on every call keeps it false.
- The base class also offers ready-made tools for reading the NET Genium framework documentation – a custom api can hand it to the users it wants to give it to. Register their descriptors in the “HandleToolsList” method and pass the calls to the handlers, which return the finished result including the MCP envelope. A handler is named after its tool, the method of its descriptor has the “_tool” suffix on top:
| Tool |
Descriptor and handler |
| list_framework_docs |
list_framework_docs_tool() and list_framework_docs(conn) – lists all the documentation pages (id, title and size in characters) |
| search_framework_docs |
search_framework_docs_tool() and search_framework_docs(args, conn) – returns the sections matching a query together with a snippet |
| get_framework_doc |
get_framework_doc_tool(conn) and get_framework_doc(args, conn) – returns a page, the table of contents of a large page, or a single section |
- They read the documentation from the “Config\Resources\<language>\05-framework-core.txt” file of the NET Genium instance whose root path the connection carries (the “NgRootPath” key of the “Web.config” file), in the language of the user of the connection. It is the same selection of the documentation the integrated MCP server of the instance publishes – it matches the version of NET Genium the instance runs on. Who gets the tools is up to the implementation: check the rights of the caller the same way as with the other tools, and neither offer a tool in “tools/list” nor handle its call for a user without them.
Details
- The language comes from the user of the connection (“conn.User.Language”), whom the “AuthorizedUser” method assigns to the connection (chapter 7). A user with Czech or Slovak as the language gets the documentation in Czech, a user with another language and a connection without an authenticated user get it in English.
- The search compares the words of the query with the documentation in this language, so a query in another language usually finds nothing.
- When the file is missing (a custom api running on a server without NET Genium needs a copy of it), the call ends with the error -32602 saying that the documentation is not available. The parsed content of the file is kept in the memory of the process and read again as soon as the file changes, that is after an update of NET Genium.
- Ready-made the same way are the tools for reading the documentation of the customer solution itself – the application documentation (DOK), the administration and operations documentation (APD) and other documents from the “docs” directory of the project. A user assistant finds in it how the customer applications are used, without anyone copying it into the instructions of the agent:
| Tool |
Descriptor and handler |
| list_docs |
list_docs_tool() and list_docs(conn) – lists all the pages of the solution documentation (id, title and size in characters) |
| search_docs |
search_docs_tool() and search_docs(args, conn) – returns the sections matching a query together with a snippet |
| get_doc |
get_doc_tool() and get_doc(args, conn) – returns a page, the table of contents of a large page, or a single section |
- They read the documentation from the “docs-core.txt” file embedded as a resource in the library of the custom api. The file is built on every build of the project by the “ai-model.exe” utility with the “/docs” switch, which gets the “docs” directory and the path of the output file – the project file gets a “BeforeBuild” target for it and an “EmbeddedResource” item with the logical name “docs-core.txt”. Every chapter of a document is a page of its own with an id such as “DOK/03-procesy”, and the “00-index” start page lists the documents. A change of the documentation reaches the users only with a new build and deployment of the custom api.
- The tools publish the pages of the administration and operations documentation only to a user with administrator rights and answer everyone else as if the page did not exist. Otherwise they do not check rights – who gets the tools is up to the implementation, the same as with the tools of the framework documentation.
Details
- A document is every subdirectory of the “docs” directory with a “00-index.md” file – typically “DOK”, “DOK_<part>” and “APD”. The utility skips subdirectories starting with an underscore or a dot, as well as a subdirectory without the “00-index.md” file and standalone files in the root of the “docs” directory. The order of chapters is given by the file map in “00-index.md” – a chapter missing from it is added at the end of the document. The utility prints a skipped subdirectory and a chapter outside the map as a warning.
- It removes comments, navigation lines and help tags in headings from the text, leaves out the “[DOPLNIT]” tag and replaces the “[ZKONTROLOVAT]” tag with the note “(neověřeno)”. It turns links to other chapters into page ids and replaces images with their description.
- When the utility finds no document in the directory, it ends with an error and the build of the project fails.
- When the “docs-core.txt” resource is missing in the library of the api, the call of the tools ends with the error -32602 saying that the documentation of the solution is not available.
- The “get_model” tool is ready-made the same way. It returns the implementation model of the instance (application groups, applications, edit forms, view pages, controls, scripts and database queries) in JSON – the same model the integrated MCP server of the instance returns. “get_model_tool()” builds the descriptor and “get_model(args, conn)” handles the call. Without the “app” and “form” parameters it returns the overview of application groups, applications and edit forms, with them the inventory of the application or the edit form, always including the scripts and the database queries of controls.
- The model is published only within the rights of the user of the connection: an administrator gets the whole model including the lists of rights, other users only the application groups, applications, categories, edit forms, view pages and controls they have rights to, and never their lists of rights. The rights are evaluated from the top down – without the right to an application group the user gets nothing below it, even with the right to it. Who gets the tool is up to the implementation, the same as with the documentation tools.
Details
- Evaluating the rights from the top down is stricter than the portal itself, where a user opens an edit form by its address even without the right to its application.
- An entity without rights is accessible to administrators only. References to entities outside the accessible part of the model (for example to the edit form a query of a control reads) are published to users without administrator rights without their names, at most with their IDs.
- Names of controls and edit forms in the steps of scripts are published in the default language of the instance (the “Config\DefaultLanguage.txt” file), other texts in the language of the user of the connection.
- The ready-made “get_app_help” tool is intended for an assistant that answers the users of the applications – it returns a brief description of the applications in the language of the user of the connection and within their rights (evaluated the same way as with “get_model”), without implementation details, so it is an order of magnitude smaller than the model. “get_app_help_tool()” composes the descriptor and “get_app_help(args, conn)” serves the call. Without the “app” and “form” parameters it returns the navigation – application groups, applications, categories, view pages and edit forms with their help texts. With the “app” parameter it returns the application with its view pages (each with its titles, tabs, view tables with the edit form whose records they list, and buttons) and the description of its edit forms, with the “form” parameter only the description of the edit form: sections by tabs and titles, visible controls (name, type, required, the values of a list and the help text), buttons and the messages the scripts of the events of the form show. For every button it states what it does (saves the record, runs a script, opens an edit form or a view page, creates a document from a print template, or an action in the browser) and the messages its script shows. The assistant of the users is therefore offered “get_app_help”, while “get_model” remains for developers.
Details
- The values of a list are published only for ComboBox, ListBox, MultiListBox and Radio controls with values entered, not from a query. Hidden controls and the Space, HTML, JavaScript and History controls are not published; a RichText control is published as its text without HTML tags. The messages of scripts are the texts of the “Throw exception” steps in the language of the user.
- The texts of the applications (names, the values of a list, help texts and messages) are in the language of the user. The labels that structure the description (for example “Page”, “Form”, “values”, “message” or the actions of a button) are always in English – the description is read by an assistant that answers the user in their language, and the tool thus does not need the NET Genium dictionary, which may be missing on the server of a custom API.
- Besides its own tools, the assistant of the users is offered “get_app_help” together with the framework documentation tools. Without them the assistant cannot answer where to find things in the applications, what a button does, what a message of a script means or how to work with a view table (export, filters).
- The “get_user_activity_log” tool is ready as well. It returns the work of users in a period of at most 31 days as the database logging records it – every load of an edit form or a view page on the server. For every user and day it states the time of the first and the last load, the numbers of loads of edit forms and view pages (of them submits), the blocks of continuous activity and the most frequent forms and pages, with the “detail” parameter also the chronological list of loads. The descriptor is built by “get_user_activity_log_tool()” and the call is handled by “get_user_activity_log(args, conn)”. The tool returns the work of any user regardless of the access rights of the user of the connection – the implementation therefore offers it only to those who may see the work of others, and checks the right also when it is called.
Details
- Without the database logging turned on, the tool returns nothing. The log does not record reading an already open page without a click, work outside NET Genium or requests of other pages (attachments, printing, portlets of the home page). The labels of the output are in English, the names of edit forms and view pages in the language of the user of the connection.
- The “whoami” tool (descriptor “whoami_tool()”, handler “whoami(conn)”), which returns the identity of the user of the connection – ID, login name, name, e-mail, administrator rights and user groups – and can be offered to everyone, and the “get_group_members” tool (“get_group_members_tool()”, “get_group_members(args, conn)”), which returns the members of a user group including the members through a rights group, are ready as well. Anyone the tool is offered to sees the members of the groups, so the implementation offers and handles it only for authorised users.
- The “read_attachment” tool (“read_attachment_tool()”, “read_attachment(args, conn)”) returns the content of any attachment of the instance by its ID, as “AttachmentResult” does. It checks no access rights, so it is offered only to those who may read all the attachments – otherwise the implementation first checks that the attachment belongs to a record the user may open and only then calls “AttachmentResult”.
- The “get_record_history” tool (“get_record_history_tool()”, “get_record_history(args, conn)”) returns the change history of any record of an edit form by the “table” and “id” parameters – when and by whom the record was saved and the new values of the changed columns, the columns of RichTextBox controls as a line diff against the previous version. It checks no access rights and returns all columns except those whose name contains “password” or “md5”, so it is offered only to those who may read all the data. A history limited to the records and columns the user may see is built by the implementation in its own tool with the “RecordHistory” helper method.
- The “list_logs” and “get_log” tools (“list_logs_tool()”, “get_log_tool()”, “list_logs(args, conn)”, “get_log(args, conn)”) list the files of the Logs directory of the instance and return the lines of a log. The handlers with a connection give them only to a user with administrator rights and return an error to anyone else, as if the tool did not exist – the logs contain personal data, SQL statements and addresses of the users.
using NETGenium;
using Newtonsoft.Json.Linq;
using System;
namespace api
{
internal partial class MyMcpServer : NETGenium.JsonRpc.McpServer
{
private DbConnection conn;
public MyMcpServer(DbConnection conn) { this.conn = conn; }
protected override string ServerName { get { return "my-server"; } }
protected override string ServerVersion { get { return "1.0.0"; } }
protected override void Authorize(ApiRequest request, DbConnection conn)
{
string token = request.AuthorizationToken;
if (token == null || !new DbRow("SELECT id FROM ng_apitoken WHERE ng_apitoken = " + conn.Format(token) + " AND ng_expiration > " + conn.Format(DateTime.Today), conn).Read())
{
throw new UnauthorizedAccessException();
}
}
protected override object HandleToolsList()
{
return new { tools = new[] { get_data_tool() } };
}
protected override object HandleToolsCall(JToken parameters)
{
string toolName = Arg(parameters, "name");
JToken args = parameters is JObject ? parameters["arguments"] : null;
if (toolName.Length == 0)
throw new NETGenium.JsonRpc.InvalidParamsException("Missing tool name");
switch (toolName)
{
case "get_data": return get_data(args);
default: throw new NETGenium.JsonRpc.MethodNotFoundException(toolName);
}
}
}
}
using NETGenium;
using Newtonsoft.Json.Linq;
namespace api
{
internal partial class MyMcpServer
{
private object get_data_tool()
{
return ReadTool("get_data", "Get data", "Returns data from the system.",
new
{
type = "object",
required = new[] { "id" },
properties = new { id = Str("Record identifier") }
});
}
private object get_data(JToken args)
{
string id = Arg(args, "id");
return ToolResult(Data.ExecuteScalar("SELECT ng_value FROM ng_data WHERE ng_identifier = " + conn.Format(id), conn));
}
}
}
- The class of the MCP server is split into parts (partial class) as with external functions. The main file is only a router: the list of descriptors in the “HandleToolsList” method and one-line branches in the “HandleToolsCall” method (case "get_data": return get_data(args);). Each tool lies in the “Tools” directory in a file named the same as the tool (Tools\get_data.cs) and holds both the descriptor “get_data_tool()” and the handler “get_data(args)”, which returns the result including the MCP envelope. Helper methods shared by several tools belong to another file of the same class next to the main one. A tool can thus be found by the name the client and the log see, without any conversion, and the ready-made tools of the base class are named the same way.
6.3. Exceptions for error states
- The “NETGenium.JsonRpc” namespace contains two exceptions that map to standard JSON-RPC error codes:
| Exception |
JSON-RPC code |
When to use |
| MethodNotFoundException |
-32601 |
Unknown method or tool |
| InvalidParamsException |
-32602 |
Missing or invalid parameter |
- Any other exception maps to code -32603 (Internal error). The client receives only a generic message without the message of the exception. The message is written only to the log (see the next bullet). The messages of “MethodNotFoundException” and “InvalidParamsException”, on the other hand, are returned to the client in the response, so they must not contain sensitive information.
Details
- An exception mapped to -32603 is additionally logged as an error (via “LogError”) and, if the “Web.config” file of the “api” project has the “smtpServer” and “errorFrom” keys filled in, may trigger an e-mail to the address in the “errorTo” key (if it is not filled in, to NetGenium support). Expected errors (invalid input, a failed database query, an unknown column, etc.) should therefore be caught in the tool implementation and rethrown as “InvalidParamsException”, which is returned as -32602 and is not logged as an error – so a merely malformed request never bubbles up as a hard exception.
7. NET Genium user identity
- Access tokens from the “ng_apitoken” table are shared – all client devices presenting the same token are indistinguishable to the API. When the API needs to know the identity of a specific NET Genium user (offer MCP server tools according to their permissions, write records on their behalf, log who performed an action), the caller can present their personal MCP token in the “ngt_...” format instead of the shared token.
- The personal MCP token is generated by the user directly in NET Genium – after clicking the avatar on the right side of the header, the user chooses “Change password” in the personal menu and goes to the “MCP token” tab (an administrator can choose “MCP token” in the menu directly). To be usable for authentication against a custom API, the token must have the “Access via a custom API” permission checked – any user can have it, and for a regular user it is enabled automatically when the token is generated.
- The token is sent the same way as the shared token – in the “Authorization” HTTP header (Bearer).
- Validating the token and obtaining the identity takes a single call:
NETGeniumUser user = re.Request.AuthorizedUser(conn);
- The method validates the token from the “Authorization” header against the NET Genium database (validity, expiration, the “Access via a custom API” permission) and returns the identity of the token owner as a “NETGeniumUser” object. It also assigns the identity to the connection (“conn.User”), so the ready-made tools of the “McpServer” base class (chapter 6.2) serve the model within the rights of the token owner and the framework knowledge in their language. When the header is missing or the token is invalid, expired or lacks this permission, the method throws an “UnauthorizedAccessException” – so the request ends with HTTP status code 401 through the standard error handling (see chapter 3.3).
- Validating the token does not log the user into NET Genium – it does not consume a license and does not create a session. The API only obtains the identity of the token owner. It therefore evaluates neither the “IP addresses allowed” list from the NET Genium settings nor the blocking of logins after repeated invalid attempts – a restriction of access by IP address has to be ensured by the custom API itself.
- The “NETGeniumUser” object carries the complete user identity including group membership:
| Property |
Description |
| ID |
The user ID (a record in the “susers” table) |
| LoginName |
The login name |
| Name |
The full name |
| Email |
The e-mail address |
| Language |
The user's language |
| GroupIds, GroupNames |
The IDs and names of the user groups the user is a member of |
| AdministratorRights |
Determines whether the user has administrator rights |
- The “IsLoginName(login)” method compares a login name stored in a record (the author or an assignee, for example) with the user regardless of letter case and surrounding spaces, the “IsInLoginNames(loginNames)” method looks for the user in a list of login names. The static “NETGeniumUser.LoginNames” method splits the list by tabs, line breaks, semicolons and commas.
- Typical use in an MCP server – the MCP server does not override the “Authorize” method and the tools read the identity of the user from “conn.User”:
using (DbConnection conn = DbConnection.UsingSettingsFromWebConfig(true))
re.HandleMcpRequest(new MyMcpServer(conn), conn);
- The default “Authorize” method validates the token by the “AuthorizedUser” method, which assigns the identity of the user to the connection. The “HandleMcpRequest” method refuses an invalid token with status code 401.
- Both authentication mechanisms can be combined in one API project – each endpoint chooses its own: endpoints for client devices validate the shared token against the “ng_apitoken” table, endpoints requiring the user identity call “AuthorizedUser”.
- An agent of Microsoft Copilot Studio presents a Microsoft Entra ID access token instead of a personal MCP token – see chapter 7.1.
7.1. A Microsoft Copilot Studio agent in Teams
- An agent of Microsoft Copilot Studio published to Microsoft Teams and Microsoft 365 Copilot cannot send each user their own personal MCP token. It can, however, obtain a Microsoft Entra ID access token on behalf of the signed-in user and send it in the “Authorization” header. The custom API validates the token and finds the user in NET Genium by the e-mail address, so every user works with the agent under their own identity and with their own permissions.
- The setup of the agent, the app registration in Microsoft Entra ID and the connector in Power Apps is shared by the custom API and the integrated MCP server of the instance. A detailed description of the procedure is provided in the separate guide Microsoft Copilot Studio. This chapter describes only what a custom API needs on top.
- The tenant ID and the client ID of the app registration are in the “Config\CopilotOAuth.json” file of the NET Genium instance – both the integrated MCP server of the instance and the custom API read it, so they share one configuration:
{
"tenant_id": "<tenant ID>",
"client_id": "<client ID>"
}
- The key in the “Web.config” file of the API with the full path to this file:
<add key="CopilotOAuthFile" value="C:\inetpub\wwwroot\<instance>\Config\CopilotOAuth.json" />
- The default “Authorize” method of the MCP server (chapter 7) reads the key itself and, when it is filled in, authenticates the caller by the “AuthorizedUser(copilotOAuthFile, conn)” overload. An API that handles the request itself calls instead of “AuthorizedUser(conn)”:
string copilotOAuthFile = Config.AppSettings("CopilotOAuthFile");
NETGeniumUser user = string.IsNullOrEmpty(copilotOAuthFile) ? re.Request.AuthorizedUser(conn) : re.Request.AuthorizedUser(copilotOAuthFile, conn);
re.HandleJsonRpc(new MyMcpServer(user, conn));
- An API that uses the “HandleMcpRequest” method starts accepting Microsoft Entra ID tokens as soon as the key is added to the “Web.config” file. An API with its own handling of the request has to be modified and deployed.
- The overload accepts both a Microsoft Entra ID token and a personal MCP token. A token starting with “ngt_” is validated exactly as by “AuthorizedUser(conn)”, so the same endpoint serves Copilot as well as other clients. Until the path to the file is filled in the “Web.config” file, the example validates only the personal MCP token.
- The rules for validating a Microsoft Entra ID token (the tenant, the app registration, the scope, matching the user by the e-mail) are described in the guide Microsoft Copilot Studio. A custom API does not require the “Access via a custom API” permission for a Microsoft Entra ID token. An invalid token as well as a user not found end with the “UnauthorizedAccessException” exception, that is with the status code 401.
Details
- The reason for rejecting a token is written to the log of the API in a line “Microsoft Entra ID token rejected (...)”, it is not returned to the client. An unavailable address of the Microsoft keys ends with the status code 500, not 401.
- When the API returns the status code 401 and the line “Microsoft Entra ID token rejected” is missing in the log, it validates only the personal MCP token – the path to the “CopilotOAuth.json” file is missing in the “Web.config” file of the deployed API, or an older version of the API runs on the server.
- A path to a “CopilotOAuth.json” file that does not exist ends with the “FileNotFoundException” exception, that is with the status code 500, even for a personal MCP token. A tenant ID or client ID that is not a GUID ends with the “ArgumentException” exception.
- The “AuthorizedUser(entraTenantId, entraClientId, requiredScope, conn)” overload takes the tenant ID, the client ID and the scope directly, without a file. An ID that is not a GUID and an empty scope end with the “ArgumentException” exception.
8. A third-party REST API client generated from an OpenAPI specification
- Chapters 4 and 5 describe the serialization and deserialization of DTO objects when communicating with a custom API. The same pattern applies in the opposite direction as well – that is, when a console application, a service or an external function calls a third-party REST API whose interface is described by an OpenAPI (formerly Swagger) specification in YAML or JSON format.
- Such a client does not have to be written by hand. The specification contains all endpoints as well as the schemas of their objects, so the client can be generated by artificial intelligence – all it needs is the specification and the conventions listed in chapter 8.2.
8.1. The shape of the client class
- The whole client is a single class containing:
- the “Url” property with the server address, populated in the constructor,
- a private “Upload” method that sends the request,
- one public method per endpoint,
- nested DTO classes and any converters.
- The outgoing HTTP request is always sent using the “Uploader” class. Unlike a hand-built request, it reads the body of the error response, which carries the reason for the rejection on a 400 or 500 error, and it can log both the request and the response – just enable the “Uploader.DebugMode” field (writing to the verbose log) or “Uploader.LogToConsole” (writing to the console). There is no need to write custom request logging into the client. Keys, passwords and tokens are not masked in this log, so debug logging should be switched off again after debugging.
- On an error response, the “Uploader” method stores the response body in the “errorresponse” parameter and rethrows the exception – it returns no value and the code after the call does not run. The body of the error response can therefore be read only in the “catch” block, and the “errorresponse” variable is declared before the “try” block.
using NETGenium;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
internal class RestClient
{
#region Properties
public string Url;
public string Authorization;
#endregion
#region Constructor
public RestClient(string url, string authorization = null)
{
Url = url;
Authorization = authorization;
}
#endregion
#region Upload
private string Upload(string url, string json)
{
string errorresponse = null;
try
{
return Uploader.UploadJSon(url, null, json, Authorization, null, Encoding.UTF8, out errorresponse);
}
catch (Exception ex)
{
if (errorresponse != null)
{
throw new Exception(errorresponse, ex);
}
throw;
}
}
#endregion
#region Methods
public RegistrationResponse Registration(RegistrationRequest request)
{
return JsonConvert.DeserializeObject<RegistrationResponse>(Upload(Url + "/registration", JsonConvert.SerializeObject(request)));
}
#endregion
#region DTO
public class RegistrationRequest
{
public int id;
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public int organizationID;
public string firstName;
public string lastName;
[JsonConverter(typeof(DateConverter))]
public DateTime validFrom;
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
[JsonConverter(typeof(DateConverter))]
public DateTime validTo;
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public DateTime filledOn;
public List<Attachment> attachments;
}
public class Attachment
{
public string fileName;
public string file;
}
public class RegistrationResponse
{
public string status;
public string message;
}
#endregion
#region Converters
public class DateConverter : IsoDateTimeConverter
{
public DateConverter()
{
DateTimeFormat = "yyyy-MM-dd";
}
}
#endregion
}
}
- Calling the client from a console application:
RestClient client = new RestClient("https://server/api");
var request = new RestClient.RegistrationRequest();
request.id = 1;
request.firstName = "John";
request.lastName = "Smith";
request.validFrom = DateTime.Today;
var response = client.Registration(request);
8.2. Conventions for mapping an OpenAPI schema to C#
- DTO class names – input objects end with the word “Request”, output objects with the word “Response”. Nested objects that the specification uses as a shared schema keep their name from the specification.
- DTO objects are public fields, not properties – never write “{ get; set; }”. This is the same notation used by the DTO objects of a custom API (see chapters 4.2 and 5.3).
- Method names start with a capital letter, do not contain the request type (so no “Get” and no “Post”), and their body is a single line – serializing the request, sending it and deserializing the response in one expression.
- Foreign keys are mapped to “int”, never to “int?”. An optional foreign key gets the “[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]” attribute, so an unfilled value (zero) is not serialized into the request at all.
- A date without a time – a value of type “string” with the format “date” is mapped to “DateTime” together with the “[JsonConverter(typeof(DateConverter))]” attribute, where “DateConverter” inherits from “IsoDateTimeConverter” and sets the format to “yyyy-MM-dd”.
- A date with a time – a value of type “string” with the format “dateTime” is mapped to “DateTime” without a converter. The default format of the Newtonsoft.Json library follows ISO 8601.
- Whether a value is required is determined in the OpenAPI specification by the “required” field of the given schema. Every value that is not listed there gets the “[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]” attribute – for a date, the attribute is combined with the converter.
8.3. The prompt for artificial intelligence
- The conventions from chapter 8.2 are simply handed to the artificial intelligence together with the specification file. A proven wording of the prompt:
Following the pattern in the RestClient.cs file, create a new client based on the
specification in the attached OpenAPI file.
Input DTO objects must end with the word "Request", output objects with the word
"Response". DTO objects must not contain "{ get; set; }".
Foreign keys must not be "int?", only "int". Optional foreign keys must be combined
with "[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]".
Dates of type "string" with the format "date", i.e. "yyyy-MM-dd", must be of type
"DateTime" combined with "[JsonConverter(typeof(DateConverter))]", which you define
as "public class DateConverter : IsoDateTimeConverter { public DateConverter()
{ DateTimeFormat = "yyyy-MM-dd"; } }".
Dates of type "string" with the format "dateTime" must be of type "DateTime" without
a converter.
Optional dates must be combined with
"[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]";
required dates are defined in the specification in the "required" field.
The names of the methods that use these DTO objects must start with a capital letter,
must not contain the method type (for example GET or POST), and the body of these
methods must be minimized, ideally to a single line.
- The generated client always has to be reviewed – in particular, check that it sends the request using the “Uploader” class and that it evaluates the body of the error response in the “catch” block. Artificial intelligence tends to add its own request sending using “HttpWebRequest” or “HttpClient”, or to merely outline the body of the “Upload” method.