Recipe 11.6 · Python
RDLC and SSRS in Modern Apps
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
Many line-of-business systems have years of reports built as SSRS server reports or RDLC files rendered by the ReportViewer control in Web Forms or WinForms. When the application moves to ASP.NET Core, the ReportViewer web control does not come along, and rewriting fifty reports is not in anyone's budget.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
This works in a Web Forms page on .NET Framework and nowhere else.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""WebForms ReportViewer control rendering a local RDLC report
Source: ImproveCode, Chapter 11, Recipe 11.6 "RDLC and SSRS in Modern Apps"
Section: The way it's often written
Book page: 251 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
There is no Python ReportViewer; the control is modelled as a duck-typed object
so the page-bound, server-control pattern is visible.
"""
from collections.abc import Callable
from typing import Any
def bind_report(report_viewer: Any, map_path: Callable[[str], str],
get_lines_data_table: Callable[[int], Any], id: int) -> None:
report_viewer.processing_mode = "Local"
report_viewer.local_report.report_path = map_path("~/Reports/Invoice.rdlc")
report_viewer.local_report.data_sources.append(
("InvoiceLines", get_lines_data_table(id)))
report_viewer.local_report.refresh()
The improved recipe
There are two practical routes. For reports deployed to an SSRS (or Power BI Report Server) instance, call the server's URL access endpoint and stream the rendered file; that needs only HttpClient. For local RDLC files, the community package ReportViewerCore.NETCore ports the RDLC rendering engine to modern .NET and renders to PDF, Excel or Word on the server, without the viewer UI.
And the local RDLC route. NuGet package: ReportViewerCore.NETCore.
A usage snippet for registering the SSRS client with Windows authentication:
Requirements: Python 3.12+. Install: pip install httpx
"""Render an SSRS report through URL access and return the bytes
Source: ImproveCode, Chapter 11, Recipe 11.6 "RDLC and SSRS in Modern Apps"
Section: The improved recipe
Book page: 251-252 -- original C# listing
Converted from C# to Python.
HttpClient -> httpx.AsyncClient (base_url e.g. http://localhost/ReportServer);
Uri.EscapeDataString -> urllib.parse.quote(safe="").
"""
from __future__ import annotations
from collections.abc import Mapping
from urllib.parse import quote
import httpx
def _escape(value: str) -> str:
return quote(value, safe="")
class SsrsReportClient:
# base_url: e.g. http://localhost/ReportServer
def __init__(self, http: httpx.AsyncClient) -> None:
if http is None:
raise ValueError("http is required")
self._http = http
async def render_async(
self,
report_path: str,
format: str,
parameters: Mapping[str, str | None],
) -> bytes:
if not report_path or not report_path.strip():
raise ValueError("report_path must not be null or whitespace")
if not format or not format.strip():
raise ValueError("format must not be null or whitespace")
path = "/".join(_escape(p) for p in report_path.split("/") if p)
url = ["?/", path, "&rs:Command=Render&rs:Format=", _escape(format)]
for name, value in parameters.items():
url.append("&" + _escape(name))
url.append(":isnull=true" if value is None else "=" + _escape(value))
response = await self._http.get("".join(url))
response.raise_for_status()
type = response.headers.get("content-type", "").split(";")[0].strip()
if type == "text/html":
raise RuntimeError(f"SSRS returned an error page for {report_path}.")
return response.content
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Render a local RDLC report with data sources and parameters
Source: ImproveCode, Chapter 11, Recipe 11.6 "RDLC and SSRS in Modern Apps"
Section: The improved recipe
Book page: 252-253 -- original C# listing
Converted from C# to Python.
Python has no RDLC engine; Microsoft.Reporting.NETCore's LocalReport is
represented by a Protocol (e.g. backed by pythonnet or a .NET sidecar).
The calling sequence is kept identical.
"""
from __future__ import annotations
from collections.abc import Callable, Mapping
from typing import Any, BinaryIO, Protocol
class LocalReport(Protocol):
data_sources: list[tuple[str, Any]]
def load_report_definition(self, definition: BinaryIO) -> None: ...
def set_parameters(self, values: list[tuple[str, str]]) -> None: ...
def render(self, format: str) -> bytes: ...
def render(
rdlc_path: str,
format: str,
data_sources: Mapping[str, Any],
parameters: Mapping[str, str],
report_factory: Callable[[], LocalReport],
) -> bytes:
with open(rdlc_path, "rb") as definition:
report = report_factory()
report.load_report_definition(definition)
for name, data in data_sources.items():
report.data_sources.append((name, data))
values: list[tuple[str, str]] = []
for name, value in parameters.items():
values.append((name, value))
report.set_parameters(values)
return report.render(format)
Requirements: Python 3.12+. Install: pip install httpx httpx-negotiate-sspi · Needs at run time: Windows domain auth to the SSRS server. The module loads without them; calling the code does not work without them.
"""Register the SSRS client with base address, timeout and Windows credentials
Source: ImproveCode, Chapter 11, Recipe 11.6 "RDLC and SSRS in Modern Apps"
Section: The improved recipe
Book page: 253 -- original C# listing
Converted from C# to Python.
AddHttpClient<T> -> a factory building httpx.AsyncClient; UseDefaultCredentials
-> httpx-negotiate-sspi (Windows integrated auth for httpx).
"""
from __future__ import annotations
import httpx
from httpx_negotiate_sspi import HttpSspiAuth
from p251_r11_6_ssrs_url_access_render_client import SsrsReportClient
def create_ssrs_report_client() -> SsrsReportClient:
client = httpx.AsyncClient(
base_url="http://localhost/ReportServer",
timeout=httpx.Timeout(5 * 60),
auth=HttpSspiAuth(), # UseDefaultCredentials = true
)
return SsrsReportClient(client)
How it works
SSRS URL access has been part of Reporting Services since the beginning: a GET request to ReportServer?/Folder/Report&rs:Format=PDF with report parameters as query values returns the rendered file. The client escapes each path segment and parameter, and sends :isnull=true for null parameters, which is how SSRS expects them. Format names are SSRS's own: PDF, EXCELOPENXML, WORDOPENXML, CSV, IMAGE.
SSRS has a habit of returning an HTML error page with a success status when a parameter is wrong, so the client checks the content type and throws instead of handing a user an "Excel file" that is really HTML. The HttpClient comes from IHttpClientFactory (Chapter 13), with UseDefaultCredentials so the application pool or service account authenticates to the report server through Windows authentication. Grant that account the Browser role on the report folder and nothing more.
RdlcRenderer keeps existing .rdlc files working. LocalReport takes the definition, one ReportDataSource per dataset named in the report (the names must match), and the report parameters, then Render("PDF") returns the bytes. The data sources can be a DataTable or any IEnumerable of objects whose property names match the dataset fields, so a list of records from Dapper works.
Variations and pitfalls
- The package is unofficial.
ReportViewerCore.NETCoreis a community port, not a Microsoft product. Read its README for supported formats and platform limits, test every report you migrate, and treat it as a bridge while you move reports to SSRS or rewrite the important ones with QuestPDF. - No interactive viewer. Neither route gives you drill-down, sorting or paging in the browser. Most users just want the PDF or Excel file. For interactive reports, link to the SSRS web portal or Power BI.
- Timeouts. Big reports take minutes. Set the client timeout to match, and for anything slower, render in a background job (Chapter 14) and e-mail a link (Chapter 9).
- The REST API. SSRS 2017 and later also have a REST API at
/Reports/api/v2.0for managing catalog items and subscriptions. For rendering, URL access is still the simplest call.