Search code examples
c#console-applicationtelerik-reporting

How to request report from c# console application using Telerik REST API


I have Telerik REST API and at client side i'm using html5 report-viewer. Report are generating successfully in a report viwer in html. Now i want to request for the reports from same API through c# console application. I have search but didn't fine any solution. Please suggest me a way how can i request a report using C# console application.

html5 report-viewer Library

Note: I'm very beginner in telerik reporting.

Update 1:

I have manage to send request to the server using this API documentation. Telerik Document for Getting Report

on Server side i have written the CustomReportResolver . But now its now sending the InstanceId to the console client.

CustomReportResolver

public class CustomReportResolver : IReportResolver
    {
        public ReportSource Resolve(string reportJsonString)
        {
            var reportDto = JsonConvert.DeserializeObject<ReportDTO>(reportJsonString);

            var connectionStringHandler = new CustomConnectionStringManager(reportDto.CompanyId);


            var reportsPath = HttpContext.Current.Server.MapPath($"~/Reports/{reportDto.ReportPath}");


            var sourceReportSource = new UriReportSource { Uri = reportsPath  + reportDto.ReportName };

         //   sourceReportSource.Parameters.Add(new Telerik.Reporting.Parameter("companyId", reportDto.CompanyId));
            var reportSource = connectionStringHandler.UpdateReportSource(sourceReportSource);
            return reportSource;
        }
    }

Note if i use default ReportResolver self hosted telerik service sending the pdf report to console successfully but if i use CustomReportResolver it's not generating instanceId.

What could be the problem ?


Solution

  • After wasting a lot of time then found a solution how to get PDF(Or any other report format) documents from Telerik Self hosted Web Service. Following are the general steps to be followed.

    1. Get Client Id
    2. Get Instance Id
    3. Get Document Id
    4. Download Document

    Below is a step wise code:

    static HttpClient client = new HttpClient();
            static string reportServerAddress = "http://localhost:60031/";
            static string serverREStAPI = reportServerAddress + "api/";
    
            static void Main(string[] args)
            {
                try
                {
                    Console.WriteLine("Demo started");
    
                    RunAsync().Wait();
    
                    Console.WriteLine("Demo ended");
                    Console.ReadLine();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    Console.ReadKey();
                }
            }
    
            static async Task RunAsync()
            {
               // readFile();
               // return;
                client.BaseAddress = new Uri(serverREStAPI);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
    
    
    
                /*
                 * Steps To get PDF documents from Telerik Self hosted Web Service
                 * Step 1) Get Client Id,
                 * Step 2) Get Instance Id
                 * Step 3) Get Document Id
                 * Step 4) Download Document
                 * 
                 * */
    
                var clientId = await GetClientIdAsync(serverREStAPI + "reports/clients", "clientId");
    
                var instanceId =
                    await GetInstanceAsync(serverREStAPI + $"reports/clients/{clientId}/instances", "instanceId");
                var documentId =
                    await GetDocumentAsync(serverREStAPI + $"reports/clients/{clientId}/instances/{instanceId}/documents",
                        "documentId");
    
                  await DownloadPDF(serverREStAPI + $"reports/clients/{clientId}/instances/{instanceId}/documents/{documentId}", true);
    
    
            }
    
    
    
    
    
            static async Task<string> GetClientIdAsync(string path, string paramName)
            {
    
                HttpResponseMessage response = await client.PostAsJsonAsync(path, "");
                response.EnsureSuccessStatusCode();
    
                var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                dynamic result = serializer.DeserializeObject(response.Content.ReadAsStringAsync().Result);
                return result[paramName];
            }
    
            static async Task<string> GetInstanceAsync(string path, string paramName)
            {
    
                /*
                 * For Default resolver in Service
                 * */
                var paramterValues = new {CompanyId = 1};
                // var data = new { report = "{ \"ReportName\":\"test.trdx\",\"CompanyId\":\"1\"}", parameterValues = "{\"CompanyId\": \"1\"}" };    
                var data = new
                {
                    report = "{\"ReportName\":\"test.trdx\",\"CompanyId\":\"1\"}",
                    parameterValues = paramterValues
                };
    
    
    
    
    
                HttpResponseMessage response = await client.PostAsJsonAsync(path, data);
                response.EnsureSuccessStatusCode();
    
                var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                dynamic result = serializer.DeserializeObject(response.Content.ReadAsStringAsync().Result);
                return result[paramName];
            }
    
            static async Task<string> GetDocumentAsync(string path, string paramName)
            {
    
    
    
                var data = new {format = "PDF"}; //PDF,XLS,MHTML
                HttpResponseMessage response = await client.PostAsJsonAsync(path, data);
                response.EnsureSuccessStatusCode();
    
                var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                dynamic result = serializer.DeserializeObject(response.Content.ReadAsStringAsync().Result);
                return result[paramName];
            }
    
    
    
            static async Task DownloadPDF(string path, bool asAttachment)
            {
                var queryString = "";
    
                // if (asAttachment)
                //  {
                //  queryString += "?content-disposition=attachment";
                //  }
    
    
    
                var filePathAndName = @"D:\testing\tet.html";
                //   File.Create(filePathAndName);
    
                //  string filePath = System.IO.Path.Combine(folderName, fileName);
    
                //System.IO.File.WriteAllText(filePathAndName, result);
    
    
                using (System.Net.WebClient myWebClient = new System.Net.WebClient())
                {
                    await myWebClient.DownloadFileTaskAsync(new Uri(path + queryString), filePathAndName);
                }
    
    
    
                System.Diagnostics.Process.Start(filePathAndName);
            }