Troubleshooting
Why a C# historian REST query returns an empty grid
Short answer
An empty grid after a C# historian REST query is a layer fault, not a connection verdict; finding the server proves reachability only. Test, in order, the documented base address and route, the authentication scheme, one known tag in an interval that holds data, typed deserialization, and the DataSource assignment on the UI thread. When 120 parsed records show as 120 grid rows, the path is proven end to end.
On this page
- Why does finding the historian server still leave the grid empty?
- Which symptom on screen points at which layer?
- What must you collect before writing the request?
- How should the C# request and grid binding be written?
- How do you test the whole chain with one known tag?
- Why does the grid stay empty when the response already holds records?
- When is an empty grid the correct result, not a fault?
- Questions asked
An empty DataGridView after a C# historian REST query is a layer fault, not a verdict that the historian is down. Finding the server proves only reachability; the query still has to clear the documented base address and route, the site's authentication scheme, a tag and interval that actually contain data, typed deserialization of the response, and the DataSource assignment on the UI thread. Work through those gates in that order, and at the end compare the parsed record count with the displayed row count. The first gate that breaks the chain is your fault, and the tests below isolate it.
Why does finding the historian server still leave the grid empty? #
Because finding the server proves only that name resolution and the network path work, and a historian host can run several services, while a working read needs the documented REST base address, the query route, the site's authentication scheme and a response your code can parse.
The request passes through a sequence of independent gates: network reachability, secure transport, service routing, authentication, authorization, query validation and response serialization. A failure at any gate can surface as the same empty grid in your application, because a default exception handler or an unassigned DataSource hides the detail. That is why the first fix is never a code change: it is capturing the status code and response body so the failing gate names itself.
Which symptom on screen points at which layer? #
Match the symptom on screen to the layer where the data flow stopped: columns with no rows point at the query or deserialization, blank cells point at binding, a frozen form points at network work running on the UI thread, and an early exception points at transport, route or authentication.
| Symptom | Layer that failed | First check |
|---|---|---|
| Grid has columns but zero rows | Query or deserialization | Log the raw response body; is the parsed record count nonzero? |
| Grid has rows with blank cells | Binding | Compare response property names and types with the bound columns |
| Form freezes or the grid never appears | Request ran on the UI thread | Move the HTTP call to async and await it from the event handler |
| Exception before any data | Transport, route or authentication | Record the status code and response body before changing code |
What must you collect before writing the request? #
Six items, all taken from the product's REST reference and the site's own security configuration: the base address, the data-query route, the authentication method, the tag identifier format, the start and end time format with its time zone, and the response schema.
| Setting | Where it is documented | What it decides |
|---|---|---|
| REST base address | Historian API reference or the server's API configuration | Which web service on the host receives the request |
| Data-query route | REST API reference | Current values, stored history, tag search or metadata |
| Authentication method | Site security configuration and API reference | Which header and credential the client must send |
| Tag identifier format | Tag browser and API reference | Which point the query addresses |
| Start and end time format | API reference | The requested interval and its time-zone interpretation |
| Response schema | API reference plus a captured response | Which properties map into grid columns |
Do not infer any of these from the server name. The authentication scheme comes from the site's configured policy; one historian documents token authentication that places a bearer token in the Authorization header of the retrieval request, while other products document basic or integrated Windows credentials. Build the query address only from documented message formats, the same discipline behind the rule that KEPServerEX REST templates use documented message settings, because a reconstructed route or field name fails at the server before any data comes back. URL-encode every query value instead of concatenating text into the address.
How should the C# request and grid binding be written? #
Build the request in this order: one shared HttpClient for the application, the documented base address plus route, the configured authentication header, an encoded query string, an awaited send, typed deserialization of the payload, and a DataSource assignment on the UI thread.
- Create one shared HttpClient for the application's lifetime instead of a new client per refresh.
- Store the documented base address and query route as separate constants so a wrong service path is visible at a glance.
- Attach the site's configured authentication header before the first send.
- Build the query from the documented tag and timestamp formats and URL-encode the values.
- Send with async and await, and read the status code and body even when the request fails.
- Deserialize a 200 response into a typed record list matching the captured schema.
- Assign the list to the DataSource on the UI thread and let the columns auto-generate.
// Illustrative example. The route text, tag name and record class below are
// examples; take the real route, query parameters and field names from your
// historian's REST reference. HttpClient, HttpRequestMessage, HttpResponseMessage,
// AuthenticationHeaderValue and JsonSerializer are documented .NET types.
public sealed class HistorianRecord
{
public string Tag { get; set; } = "";
public DateTime Timestamp { get; set; }
public double Value { get; set; }
}
private static readonly HttpClient historianClient = new HttpClient();
private async void LoadHistoryButton_Click(object sender, EventArgs e)
{
string baseAddress = "https://historianhost.plant.local"; // example base address
string queryRoute = "/example-values-route?tag=Line1_Temp" +
"&start=2024-06-03T08:00:00Z&end=2024-06-03T08:10:00Z"; // example route and window
string bearerToken = Environment.GetEnvironmentVariable("HISTORIAN_TOKEN") ?? "";
using var request = new HttpRequestMessage(HttpMethod.Get, baseAddress + queryRoute);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
HttpResponseMessage response = await historianClient.SendAsync(request);
string responseBody = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
throw new InvalidOperationException($"HTTP {(int)response.StatusCode}: {responseBody}");
List<HistorianRecord> records = JsonSerializer.Deserialize<List<HistorianRecord>>(responseBody)
?? new List<HistorianRecord>();
historyGrid.DataSource = records; // awaited on the UI thread, so this assignment is safe
}
Here historyGrid is the form's DataGridView field, and HistorianRecord is an illustrative class you reshape to the real response schema. Declare its members as public properties, not public fields: fields deserialize fine and then bind nothing. After binding, the test is one line of arithmetic: records.Count and historyGrid.Rows.Count must be equal, and if they are not, the numbers tell you which side to repair.
How do you test the whole chain with one known tag? #
Prove the chain with one tag you know is logging: a tag written every 5 s over a 10 min window holds 600 s / 5 s per sample = 120 samples, so a correct response carries 120 records and a correct grid shows 120 rows.
Run these checks in order, each one proving or removing exactly one cause:
- Call the documented route from a second client (a browser, curl or a REST tool) with the same identity and a narrow window on a tag you know is logging; expect a 200 status and a record count equal to the arithmetic result above.
- Run the C# request and log the resolved request address, status code, elapsed time and response body, with the token stripped from the log.
- Check the parsed record count is nonzero before touching the grid at all.
- Inspect one deserialized record: tag identity, timestamp, value, and the quality field if the documented schema has one.
- Bind the records and compare
historyGrid.Rows.Countwithrecords.Count. - Compare one displayed sample against the second client for the same tag and interval.
If the independent call returns 120 records while your application parses 0, the historian and the network are proven good, so stop looking at firewall rules and repair the C# side, starting with the authorization header and the deserialization types. This is layer-by-layer isolation in its plainest form, the same discipline described on the page about why each troubleshooting test should prove a single cause.
Why does the grid stay empty when the response already holds records? #
If the parsed record count is nonzero and the grid is still empty, the fault is binding, not the network: DataGridView binds public properties, so a record class built from public fields deserializes cleanly and then displays no columns and no rows at all.
Three binding faults cover almost every case here. First, the record class exposes public fields instead of public properties, which is the zero-column case above; change the class, not the grid. Second, columns were created manually in the designer with names that match no property, so either leave AutoGenerateColumns at its default and delete the manual columns, or map each manual column's data property name to the matching record property. Third, the assignment ran on a background thread; with the awaited pattern from a button handler this cannot happen, because the code after await resumes on the UI context, but an assignment made inside a Task.Run body needs a marshal back to the UI thread first. The decision is mechanical: correct the record class properties, rebind, and the parsed record count appears as rows.
When is an empty grid the correct result, not a fault? #
Sometimes zero rows is the correct answer: the tag was not logged during the window, the collector was offline, retention has expired, or a query row limit truncated the result — so compare a second client on the same tag and interval before writing any code.
A second client showing no data for the same tag and interval clears your code entirely and moves the fault to the collection and retention side. Watch one silent contributor in particular: many historian interfaces cap the rows a single query returns, and the same row-limit behavior that leaves a historian trend flat until you check the query row limit also truncates a REST query, so a window you assumed holds one unbroken series can return fewer records or an empty page. Widen nothing and change no code until you have confirmed with the second client that the interval genuinely holds data. The decision for each case: second client shows data and your parse count is 0, repair deserialization or authentication; parse count is nonzero and rows are 0, repair binding; second client shows nothing either, leave the application alone and chase collection, retention or the query row limit on the historian side.
Questions asked
Should each grid refresh create a new HttpClient?
No. Create one HttpClient for the application's lifetime and reuse it for every query. Creating a client per refresh can exhaust sockets under load, and it also drops the authentication header you configured once, so a later refresh can fail authorization even though the first query worked.
Where should the historian access token live?
In the site's credential store or a configuration source the application reads at startup, not in source code. Strip the token from every log line as well: a logged request address plus a captured Authorization header value is enough for someone to replay queries as your application.
Can I assign the raw JSON string to the grid's DataSource?
No. A string binds as a single column of text, so the grid looks broken even though the response is good. Deserialize into a typed record list first, then assign that list; the public property names on the record class define the columns the grid generates.
Do I need Control.Invoke when the query runs asynchronously?
Not when you use async and await from a UI event handler: the code after await resumes on the UI thread, so the DataSource assignment is safe. You need Invoke only when the assignment runs on a background thread you created yourself, for example inside Task.Run without marshalling back.
Which HTTP status codes point at which layer?
A working query returns 200 with a body. A 401 or 403 points at authentication or authorization, a 404 usually means the base address or route is wrong, and a 5xx points at the historian server itself. Record the code together with the response body before changing any code.