Search code examples
c#telerik-reporting

How to assign data in telerik report dynamically from c#?


I have designed the report trdp file using the designer and added web service as data source. My plan is, when the report will be requested, instead of the web source, I want to pull the data using linq and want to inject that data in the report data source and want to pass it through the report processor. What I have done is: ``

        var rng = new Random();
        var datas = Enumerable.Range(1, 100).Select(index => new WeatherForecast
            {
                Category = Summaries[rng.Next(Summaries.Length)],
                Date = DateTime.Now.AddDays(index),
                TemperatureC = 1
            }).ToList();

        DataTable dataTable = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(Newtonsoft.Json.JsonConvert.SerializeObject(datas));
        Telerik.Reporting.Report report = null;
        using (var sourceStream = System.IO.File.OpenRead("Reports\\DemoReport.trdp"))
        {
            var reportPackager = new ReportPackager();
            report = (Report)reportPackager.UnpackageDocument(sourceStream);
            var dtsrc = new ObjectDataSource();
            dtsrc.DataSource = dataTable;
            report.DataSource = dtsrc;
        }
        

        Telerik.Reporting.Processing.ReportProcessor reportProcessor = new Telerik.Reporting.Processing.ReportProcessor();
        System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable();
        Telerik.Reporting.Processing.RenderingResult result = reportProcessor.RenderReport("PDF", report, deviceInfo);

        var fileName = "adreport.pdf";
        using (FileStream fs = new FileStream(fileName, FileMode.Create))
        {
            fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
        }
        return Ok();

``

This generates the report but instead of a few pages, the generated pdf report contains a few hundreds of page with the same data repeatedly which is unusual. Can anyone explain why this is happening.


Solution

  • I am going to answer this question with as details as possible. For telerik reporting with angular and dynamically data assignment from backend code,follow the steps:-

    1. Design the report template from Report designer
    2. Place the templace in c# folter
    3. Include report viewer in angular project
    4. When report viewer will request for the report, handle it using the CustomReportResolver Sample code is provided below.
    Angular
    
    <tr-viewer #viewer1 
        [containerStyle]="viewerContainerStyle"
        [serviceUrl]="'https://localhost:5001/api/reports/'"
        [reportSource]="{
            report: 'DemoListReport.trdp',
            parameters:
            {
    
            }
        }"
        [viewMode]="'INTERACTIVE'"
        [scaleMode]="'SPECIFIC'"
        [scale]="1.0"
        [ready]="ready"
        [viewerToolTipOpening]="viewerToolTipOpening"
        [enableAccessibility]="false">
    </tr-viewer>
    <button (click)="viewer1.refreshReport()">Refresh</button>
    <button (click)="viewer1.commands.print.exec()">Print</button>
    
    
    .NET Core 3.1
    Startup.cs
    
     services.TryAddScoped<IReportSourceResolver, CustomReportResolver>();
                // Configure dependencies for ReportsController.
                services.TryAddSingleton<IReportServiceConfiguration>(sp =>
                    new ReportServiceConfiguration
                    {
                        // The default ReportingEngineConfiguration will be initialized from appsettings.json or appsettings.{EnvironmentName}.json:
                            ReportingEngineConfiguration = sp.GetService<IConfiguration>(),
                            // In case the ReportingEngineConfiguration needs to be loaded from a specific configuration file, use the approach below:
                            // ReportingEngineConfiguration = ResolveSpecificReportingConfiguration(sp.GetService<IHostingEnvironment>()),
                            HostAppId = "Html5DemoAppCore",
                            Storage = new Telerik.Reporting.Cache.File.FileStorage(),
                            ReportSourceResolver = new CustomReportResolver()
                    });
    
    
    CustomReportResolver.cs
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Telerik.Reporting;
    using Telerik.Reporting.Services;
    using Telerik.Reporting.Services.Engine;
    
    namespace MyProject.API.Controllers
    {
        public class CustomReportResolver: IReportSourceResolver
        {
            private static readonly string[] Summaries = new[]
            {
                "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
            };
            
    
            public ReportSource Resolve(string report, OperationOrigin operationOrigin, IDictionary<string, object> currentParameterValues)
            {
                //data
                var rng = new Random();
                var datas = Enumerable.Range(1, 500).Select(index => new WeatherForecast
                {
                    Category = Summaries[rng.Next(Summaries.Length)],
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = 1
                }).ToList();
                
                
    
                var reportPackager = new ReportPackager();
                Report reportt = null;
                using (var sourceStream = System.IO.File.OpenRead($"Reports\\{report}"))
                {
                    reportt = (Report)reportPackager.UnpackageDocument(sourceStream);
                }
    
                DetailSection detail = (DetailSection)reportt.Items["detailSection1"];
                Table table = (Table)detail.Items["table1"];
                table.DataSource = datas.Take(5);
    
    
                Graph graph = (Graph)detail.Items["graph1"];
                graph.DataSource = datas;
    
    
                InstanceReportSource instanceReportSource = new InstanceReportSource();
                instanceReportSource.ReportDocument = reportt;
    
                return instanceReportSource;
            }
        }
    }
    
    
    

    Here datas will pass your data to the report. Hopefully this will help others later.