0% found this document useful (0 votes)
6 views

Fast Report Com Blogs Use Net Asp Web Api

Uploaded by

madoslom
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Fast Report Com Blogs Use Net Asp Web Api

Uploaded by

madoslom
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Products Buy Support Company Partners

Home / Articles / How to use FastReport .NET with ASP .NET Web API

How to use FastReport .NET with ASP .NET Web API


The Web API allows you to quickly and easily create HTTP services. Unlike regular ASP.Net MVC projects, the Web API
does not work with views. A controller of a special type is used, the methods of which return model objects.

The task of such a controller is to transmit data, not representations.

Let's look at how to create a simple web service that provides FastReport reports.

1) First of all, we will create two reports, which we will display.

The simple list report template looks like this:

Note that the report header has the [Parameter] parameter. You need to add a report parameter with that name. Data
for this report can be taken from the Employee table of the demonstration database nwind.xml, which can be found
here: C: \ Program Files (x86) \ FastReports \ FastReport.Net \ Demos \ Reports.

The second report template will not contain data. You can take the ready-made template Barcodes.frx from the folder
C: \ Program Files (x86) \ FastReports \ FastReport.Net \ Demos \ Reports.

As mentioned above, we will use two reports and one database in our project. Add them to the folder App_Data.
Make a right click on this folder in the solution's browser. Choose Add-> Existing item. Thus we add three files:
Barcode.frx, Simple List.frx, nwind.xml. Alternatively, you can simply drag these files to the App_Data folder with the
mouse.

2) Create the ASP.NET application:

Click OK and go to the project type selection:

Select the Empty template. At the bottom mark MVC and Web API option. If you select a Web API template, you will
receive a project filled with demo data.

3) Add a link to the FastReport.dll library in the Reference.

4) Now, you need to add a data model. To do this, in the solution browser, select the Model folder and make a right
click. In the context menu, select Add-> Class:

Give the class name - Reports.cs. The default class type is Class. Click Add.

In the created class, add two variables with the get and set methods:
namespace FastReportWebApiDemo.Models
1
{
2
public class Reports
3
{
4
// Report ID
5
public int Id { get; set; }
6
// Report File Name
7
public string ReportName { get; set; }
8
}
9
}
10

5) Now add the controller to the project. Do the right click on the Controllers folder. From the context menu, select
Add-> Controller.

Select the controller template - Web API2 Controller - Empty:

Call it ReportsController:

Let's proceed to encoding the logic in the controller. The task is to provide a download in the browser or display the
report in one of the export formats: PDF, HTML, png.
using System;
1
using System.Collections.Generic;
2
using System.Linq;
3
using System.Net;
4
using System.Net.Http;
5
using System.Web.Http;
6
using FastReport;
7
using FastReport.Export.Image;
8
using FastReport.Export.Html;
9
using FastReport.Export.Pdf;
10
using FastReport.Utils;
11
using FastReportWebApiDemo.Models;
12
using System.Web.Hosting;
13
using System.Data;
14
using System.IO;
15
using System.Net.Http.Headers;
16
17
namespace FastReportWebApiDemo.Controllers
18
{
19
// The class of parameters in the query
20
public class ReportQuery
21
{
22
// Format of resulting report: png, pdf, html
23
public string Format { get; set; }
24
// Value of "Parameter" variable in report
25
public string Parameter { get; set; }
26
// Enable Inline preview in browser (generates "inline" or "attachment")
27
public bool Inline { get; set; }
28
}
29

30
public class ReportsController : ApiController
31
{ // Reports list
32
Reports[] reportItems = new Reports[]
33
{
34
new Reports { Id = 1, ReportName = "Simple List.frx" },
35
new Reports { Id = 2, ReportName = "Barcode.frx" }
36
};
37
38
// Get reports list
39
public IEnumerable<Reports> GetAllReports()
40
{
41
return reportItems;
42
}
43

44
// Get report on ID from request
45
public HttpResponseMessage GetReportById(int id, [FromUri] ReportQuery query)
46
{
47
// Find report
48
Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id);
49
if (reportItem != null)
50
{
51
string reportPath = HostingEnvironment.MapPath("~/App_Data/" + reportItem.ReportName);
52
string dataPath = HostingEnvironment.MapPath("~/App_Data/nwind-employees.xml");
53
MemoryStream stream = new MemoryStream();
54
try
55
{
56
using (DataSet dataSet = new DataSet())
57
{
58
//Fill data source
59
dataSet.ReadXml(dataPath);
60
//Enable web mode
61
Config.WebMode = true;
62
using (Report report = new Report())
63
{
64
report.Load(reportPath); //Load report
65
report.RegisterData(dataSet, "NorthWind"); //Register Data in report
66
if (query.Parameter != null)
67
{
68
report.SetParameterValue("Parameter", query.Parameter); // Set the value of the parameter in the report. The value we take from the URL
69
}
70
71
// Two phases of preparation to exclude the display of any dialogs
72
report.PreparePhase1();
73
report.PreparePhase2();
74

75
if (query.Format == "pdf")
76
{
77
//Export in PDF
78
PDFExport pdf = new PDFExport();
79
// We use the flow to store the report, so as not to produce files
80
report.Export(pdf, stream);
81
}
82
else if (query.Format == "html")
83
{
84
// Export in HTML
85
HTMLExport html = new HTMLExport();
86
html.SinglePage = true;
87
html.Navigator = false;
88
html.EmbedPictures = true;
89
report.Export(html, stream);
90
}
91
else
92
{
93
// Export in picture
94
ImageExport img = new ImageExport();
95
img.ImageFormat = ImageExportFormat.Png;
96
img.SeparateFiles = false;
97
img.ResolutionX = 96;
98
img.ResolutionY = 96;
99
report.Export(img, stream);
100
query.Format = "png";
101
}
102
}
103
}
104
// Create result variable
105
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
106
{
107
Content = new ByteArrayContent(stream.ToArray())
108
};
109
stream.Dispose();
110
111
result.Content.Headers.ContentDisposition =
112
new System.Net.Http.Headers.ContentDispositionHeaderValue(query.Inline ? "inline" : "attachment")
113
{
114
// Specify the file extension depending on the type of export FileName = String.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", qu
115
};
116
// Determine the type of content for the browser
117
result.Content.Headers.ContentType =
118
new MediaTypeHeaderValue("application/" + query.Format);
119
return result;
120
}
121
// We handle exceptions
122
catch
123
{
124
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
125
}
126
}
127
else
128
return new HttpResponseMessage(HttpStatusCode.NotFound);
129
}
130
}
131
}
132

As you can see, we added another class to the controller. The ReportQuery class defines the HTTP request
parameters. This is format, parameter and inline. The first determines the format of the report export, the second one
- the parameter value in the report, the third one - whether the report is opened directly in the browser.

In the ReportsController class, we created an array of reports and two methods. The names and report identifiers are
defined in the array. The first method GetAllReports () returns a list of available reports. In our case, two reports. The
second method GetReportById (int id, [FromUri] ReportQuery query) returns a report on the identifier. From the
query attribute, we can get the parameters format, inline, and parameter. They determine: the export format of the
report, whether the report will be opened directly in the browser, the value of the parameter to be sent to the report.

6) Add a web page to the report. With it, we will send requests to the server with the necessary parameters. To do
this, right click on the project name. Choose Add-> HTML Page:

Set the name – Index:

Add the following code to the page:


<!DOCTYPE html>
1
<html>
2
<head>
3
<title>FastReport.Net Web Api Demo</title>
4
<meta charset="utf-8" />
5
</head>
6
<body>
7
<h1>FastReport.Net Web Api Demo</h1>
8
<hr />
9
<a href="/api/reports/">List Of All Reports</a><br />
10
<a href="/api/reports/1">Get First Report</a><br />
11
<a href="/api/reports/2">Get Second Report</a><br />
12
<a href="/api/reports/1?format=pdf">Get First Report in PDF</a><br />
13
<a href="/api/reports/2?format=html">Get Second Report in HTML</a><br />
14
<a href="/api/reports/1?format=pdf&inline=true">Get First Report in PDF inline</a><br />
15
<a href="/api/reports/2?format=html&inline=true">Get Second Report in HTML inline</a><br />
16
<a href="/api/reports/1?format=pdf&inline=true&parameter=REPORT">Get First Report in PDF inline with Parameter=REPORT</a><br />
17
<a href="/api/reports/1?format=html&inline=true&parameter=REPORT">Get First Report in HTML inline with Parameter=REPORT</a><br />
18
</body>
19
</html>
20

As can be understood from the titles, we can:

1. Get a list of reports;

2. Get the first report. Based on our code in the controller, if we do not explicitly pass the format of the format, the
report will be displayed in png format;

3. Receive a second report;

4. Get the first report in PDF format;

5. Get the second report in HTML format;

6. Get the first report in PDF format and display it in the browser;

7. Get the second report in HTML format and display it in the browser;

8. Get the first report in PDF format and display it in the browser, and also transfer it to the report.

9. Get the second report in HTML format and display it in the browser, and send it to the report.

7) Open the file WebApiConfig.cs from the folder App_Start. Add one more MapHttpRoute for the Index page:
public static void Register(HttpConfiguration config)
1
{
2
// Web API configuration and services
3
// Web API routes
4
config.MapHttpAttributeRoutes();
5
config.Routes.MapHttpRoute(
6
name: "Index",
7
routeTemplate: "{id}.html",
8
defaults: new { id = "index" }
9
);
10

11
config.Routes.MapHttpRoute(
12
name: "DefaultApi",
13
routeTemplate: "api/{controller}/{id}",
14
defaults: new { id = RouteParameter.Optional }
15
);
16
}
17

In the same folder, the RouteConfig.cs file is located. It can be deleted.

8) The last step. Open the file Global.asax. Delete the line:
RouteConfig.RegisterRoutes(RouteTable.Routes);
1

Now routing will be carried out only through WebApiConfig.

9) Run the application. In the browser we see a list of commands:

The first link opens a list of reports in the form of an XML document:

The second and third links will result in downloading the first and second reports in the png format;
The fourth link leads to the download of the first report in PDF format;
The fifth link results in the download of the second report in HTML format;
The sixth link opens the first PDF report directly in the browser:

The seventh link opens the second report in HTML format directly in the browser:
The eighth link opens the first report in PDF format in the browser and transmits the REPORT parameter:

The ninth link opens the first report in HTML format in the browser and transmits the REPORT parameter;
That's all. Working with FastReport in WebAPI is not more difficult than in the common ASP Net MVC project.

Products Support Company

Buy Online support About


800-985-8986 (English, US) Demo Support SLA Resellers
+4930568373928 (German) Documentation FAQ Contacts us
+55 19 98147-8148 (Portuguese) How to uninstall Tutorial Video

[email protected] Licenses Forum


Articles
901 N Pitt Str #325 Alexandria VA
22314 News

© 1998-2024 Fast Reports Inc.

You might also like