Copied RSS Feed

Blazor

Blazor SSRS Report Viewer Component using Bold Reports

Yes, you read it right, we have provided a way to use Bold Report Viewer component in Blazor apps.

In this blog post, we will walk you through integrating Bold Reports JavaScript Report Viewer control into your Blazor apps. In Bold Reports, the report processing and rendering in-browser will be handled using a server-side ASP.NET Core controller and a client-side Razor view page, respectively. Let’s dive in to play with this new feature.

Prerequisites

The following are the prerequisites to work with Blazor:

  1. Visual Studio 2019 with ASP.NET and Web Development workloads.
  2. .NET Core 3.1 Framework.
  3. Bold Reports Embedded subscription.

Source code

The source code for this Blazor reporting components app is available on GitHub.

Create a Blazor application

To get started, create a Blazor Server App template application and name it BlazorReportingTools using Visual Studio 2019. If this template is not available for you, refer to the following link to configure the system environment to kick-start your Blazor development: Get started with ASP.NET Core Blazor.

Create a Web API for report processing

In this section, we are going to create a Web API controller that will be used to process the provided RDL reports.

  1. Install the following NuGet packages in the created Blazor application. These are used for processing the RDL reports.
Package Purpose
BoldReports.Net.Core Creates Web API service to process the reports.
System.Data.SqlClient Should be referenced in the project when the RDL report renders visual data from the SQL Server or SQL Azure data source based on the RDL design. The package version should be higher than 4.1.0.
Microsoft.AspNetCore.Mvc.NewtonsoftJson ASP.NET Core MVC features that use Newtonsoft.Json. Includes input and output formatters for JSON and JSON Patch. The package version should be higher than 3.1.2.
  1. Create an empty API controller by right-clicking the Data folder, choosing Add > Controller, and then naming it cs

    Add controller option

  1. We are going to implement the IReportController interface from the namespace BoldReports.Web.ReportViewer, which is used to process the reports in the wwwroot/resources folder. Refer to the following code sample for RDL report processing.
    using BoldReports.Web.ReportViewer;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Caching.Memory;
    
    namespace BlazorReportingTools.Data
    {
        [Route("api/{controller}/{action}/{id?}")]
        [ApiController]
        public class BoldReportsAPIController : ControllerBase, IReportController
        {
            // Report viewer requires a memory cache to store the information of consecutive client requests and
            // the rendered report viewer in the server.
            private IMemoryCache _cache;
    
            // IHostingEnvironment used with sample to get the application data from wwwroot.
            private IWebHostEnvironment _hostingEnvironment;
    
            public BoldReportsAPIController(IMemoryCache memoryCache, IWebHostEnvironment hostingEnvironment)
            {
                _cache = memoryCache;
                _hostingEnvironment = hostingEnvironment;
            }
            //Get action for getting resources from the report
            [ActionName("GetResource")]
            [AcceptVerbs("GET")]
            // Method will be called from Report Viewer client to get the image src for Image report item.
            public object GetResource(ReportResource resource)
            {
                return ReportHelper.GetResource(resource, this, _cache);
            }
    
            // Method will be called to initialize the report information to load the report with ReportHelper for processing.
            public void OnInitReportOptions(ReportViewerOptions reportOption)
            {
                string basePath = _hostingEnvironment.WebRootPath;
                // Here, we have loaded the sales-order-detail.rdl report from the application folder wwwroot\Resources. sales-order-detail.rdl should be in the wwwroot\Resources application folder.
                System.IO.FileStream reportStream = new System.IO.FileStream(basePath + @"\resources\" + reportOption.ReportModel.ReportPath + ".rdl", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                reportOption.ReportModel.Stream = reportStream;
            }
    
            // Method will be called when report is loaded internally to start the layout process with ReportHelper.
            public void OnReportLoaded(ReportViewerOptions reportOption)
            {
            }
    
            [HttpPost]
            public object PostFormReportAction()
            {
                return ReportHelper.ProcessReport(null, this, _cache);
            }
    
            // Post action to process the report from the server based on json parameters and send the result back to the client.
            [HttpPost]
            public object PostReportAction([FromBody] Dictionary<string, object> jsonArray)
            {
                return ReportHelper.ProcessReport(jsonArray, this, this._cache);
            }
        }
    
    }
    
  1. To request the report processing unit properly, we changed the router API attribute to include the controller and action names using [Route(“api/{controller}/{action}/{id?}”)].
  1. To invoke this Web API with the controller and action, include that information in the endPoint routing in the Startup.cs file.
    app.UseEndpoints(endpoints =>
    {
      endpoints.MapControllers();
      endpoints.MapBlazorHub();
      endpoints.MapFallbackToPage("/_Host");
    });
    
  1. Bold Reports processes the data between client and server using Newtonsoft.Json. Since we need to enable the Newtonsoft.Json features in our Blazor application, we need to include the following code section in the Startup.cs file’s ConfigureServices method.
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddRazorPages();
      services.AddServerSideBlazor();
      services.AddSingleton<WeatherForecastService>();
      services.AddControllers().AddNewtonsoftJson();
    }
    

Note: If you are facing the following issue, be sure to install the NuGet package Microsoft.AspNetCore.Mvc.NewtonsoftJson with version 3.1.2 or above. 

‘IMvcBuilder’ does not contain a definition for ‘AddNewtonsoftJson’ and no accessible extension method ‘AddNewtonsoftJson’ accepting a first argument of type ‘IMvcBuilder’ could be found (are you missing a using directive or an assembly reference?)

Everything is now ready for RDL report processing.

Initialize the Report Viewer

In this section, we are going to integrate Bold Reports JavaScript controls by creating an interop file to initialize the report viewer with basic parameters.

  1. Create a Data/BoldReportOptions.cs class with the following code to hold the RDL report rendering properties.[Data/BoldReportOptions.cs]
    namespace BlazorReportingTools.Data
    {
        public class BoldReportViewerOptions
        {
            public string ReportName { get; set; }
            public string ServiceURL { get; set; }
        }
    }
    
  1. Create a boldreports-interop.js file inside the wwwroot/scripts folder and use the following code snippet to invoke the Bold Report Viewer JavaScript control.
    // Interop file to render the Bold Report Viewer component with properties.
    window.BoldReports = {
        RenderViewer: function (elementID, reportViewerOptions) {
            $("#" + elementID).boldReportViewer({
                reportPath: reportViewerOptions.reportName,
                reportServiceUrl: reportViewerOptions.serviceURL            
            });
        }
    }
    
  2. Create a folder named resources inside the wwwroot folder in your application to store the RDL reports. Now, add any RDL reports that have already been created to the newly created folder.

Note: In this tutorial, the sales-order-detail.rdl report is used, and it can be downloaded here. You can add the reports from the Bold Reports installation location. For more information, refer to the samples and demos section of the Bold Reports documentation.

  1. Reference the following online CDN links along with the boldreports-interop.js interop file in the head section of Pages/_Host.cshtml to use our JavaScript reporting controls in the Blazor application.
    <link href="https://cdn.syncfusion.com/2.2.23/bold-reports/material/bold.reports.all.min.css" rel="stylesheet" />
        <script src="https://cdn.syncfusion.com/js/assets/external/jquery-1.10.2.min.js" type="text/javascript"></script>
        <script src="https://cdn.syncfusion.com/2.2.23/bold-reports/common/bold.reports.common.min.js"></script>
        <script src="https://cdn.syncfusion.com/2.2.23/bold-reports/common/bold.reports.widgets.min.js"></script>
    
        <!--Used to render the chart item. Add this script only if your report contains the chart report item.-->
        <script src="https://cdn.syncfusion.com/2.2.23/bold-reports/data-visualization/ej.chart.min.js"></script>
    
        <!--Used to render the gauge item. Add this script only if your report contains the gauge report item. -->
        <script src="https://cdn.syncfusion.com/2.2.23/bold-reports/data-visualization/ej.lineargauge.min.js"></script>
        <script src="https://cdn.syncfusion.com/2.2.23/bold-reports/data-visualization/ej.circulargauge.min.js"></script>
    
        <!--Used to render the map item. Add this script only if your report contains the map report item.-->
        <script src="https://cdn.syncfusion.com/2.2.23/bold-reports/data-visualization/ej.map.min.js"></script>
    
        <!-- Report Viewer component script-->
        <script src="https://cdn.syncfusion.com/2.2.23/bold-reports/bold.report-viewer.min.js"></script>
    
    <script src="~/scripts/boldreports-interop.js"></script>
    
  2. Inject IJSRuntime and invoke this JavaScript interop with the sales-order-detail.rdl report and the created BoldReportsAPI URL in the Pages/Index.razor file to visualize the report using our viewer.
    [Pages/Index.razor]
    @page "/"
    
    @using Microsoft.JSInterop
    @using Microsoft.AspNetCore.Components
    @inject IJSRuntime JSRuntime
    @using BlazorReportingTools.Data;
    
    <div id="report-viewer" style="width: 100%;height:800px" />
    
    @code {
        // ReportViewer options
        BoldReportViewerOptions viewerOptions = new BoldReportViewerOptions();
    
    
        // Used to render the Bold Report Viewer component in Blazor page.
        public async void RenderReportViewer()
        {
            viewerOptions.ReportName = "sales-order-detail";
            viewerOptions.ServiceURL = "/api/BoldReportsAPI";
            await JSRuntime.InvokeVoidAsync("BoldReports.RenderViewer", "report-viewer", viewerOptions);
        }
    
        // Initial rendering of Bold Report Viewer
        protected override void OnAfterRender(bool firstRender)
        {
            RenderReportViewer();
        }
    }
    

Here we created and used BoldReportViewerOptions to pass the parameters for report rendering. In the future, if we need any additional parameters, we can just include them in the BoldReportsOptions.cs file and use it to render the reports.

Now, click the Run button. The report will be rendered and displayed as shown in the following screenshot.

Bold Report Viewer in a Blazor App

Register license

You have to include the license token in your application in order to use the Bold Reports assemblies. The token can be generated from the Downloads section of the Bold Reports site. You can register the license token in the Startup.cs file as shown in the following code.

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //Register Bold license
            Bold.Licensing.BoldLicenseProvider.RegisterLicense("YOUR LICENSE TOKEN HERE");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }
        ------
        ------
        ------

Summary

In this blog, we integrated our Bold Reports JavaScript Report Viewer control into a Blazor application and loaded a sales order details report.

Feel free to check out the Bold Reports Embedded demos and our documentation to explore demos of the tools and the various report customization features. If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our website. We are happy to assist you!

Bold Reports now comes with a 15-day free trial with no credit card information required. We welcome you to start a free trial and experience Bold Reports for yourself. Give it a try and let us know what you think!

Stay tuned to our official Twitter, Facebook, LinkedIn, Pinterest and Instagram pages for announcements about our releases.

The post Blazor Reporting Components appeared first on Bold Reports Blog.

Meet the Author

Karthick T

Software Product Manager at Syncfusion Inc., Blogger. Developed aurelia-syncfusion-bridge and Essential JS1 for Angular Core. Fond of frameworks Angular, Aurelia and Vue.