How to use WebReport in Single Page Application Angular 7


If you use FastReport.Net in your ASP.Net Core applications and want to switch to a single-page application (SPA), then this article is for you. Thanks to the symbiosis of Angular and ASP.Net Core, you can use your familiar MVC application architecture.
Let's take a look at the way to create a SPA application. This will be useful for those who are just going to learn Angular. To work with Angular, you need to install Node.js, a platform for executing JavaScript code on the server side. The easiest way is to download the installer from the developer’s website https://nodejs.org/en/. It also requires .Net Core SDK 2.0 or newer versions. If you have Microsoft Visual Studio 2017 installed, then the SDK is already installed.

Now we create a folder for our future application in the desired place. Run the command prompt. Go to the created directory using the cd command. And we execute the command:

dotnet new angular -o SPAWebReport

This command will create a three-page demo application.
Open the created project. First, we will need to install additional packages in the NuGet manager:

The FastReport.Core and FastReport.Web packages can be found in the NuGet folder in the FastReport.Net installation directory. To install these packages, you need to set up a local package repository. In the upper right corner of the package manager there is a drop-down list for selecting the source of packages and the gear icon. By clicking on this icon, you will see the settings window, where for the local source you will specify the path to the NuGet folder.
We need a report and a database for it. Add the App_Data folder to the project root and drag the Master-Detail.frx and nwind.xml files into it. These files can be found in the FastReport.Net installation directory in the Demos -> Reports folder.
At the root of the project is the Controllers directory, which already contains one controller. We use it. Add just one method:
using FastReport.Web;
[HttpGet("[action]")]
        public IActionResult ShowReport()
        {
            WebReport WebReport = new WebReport();
            WebReport.Width = "1000";
            WebReport.Height = "1000";
            WebReport.Report.Load("App_Data/Master-Detail.frx"); // Load the report into the WebReport object
            System.Data.DataSet dataSet = new System.Data.DataSet(); // Create a data source
            dataSet.ReadXml("App_Data/nwind.xml");  // Open the xml database            WebReport.Report.RegisterData(dataSet, "NorthWind"); // Registering the data source in the report
            ViewBag.WebReport = WebReport; // pass the report to View
            return View();
        }
Now you need to create a view for it. Add the Views folder to the project root. And in it one more SampleData. Now in this folder we will create the ShowReport.cshtml view with this code:
@await ViewBag.WebReport.Render()
In our demo SPA there are three unnecessary web pages. You can safely delete these pages; we are only interested in app.component.htm - this is the page template. For this template, there is a corresponding script app.component.ts. Here we are to work with him mainly.
You can set the page template in the app.component.htm file, or you can set it directly in the script, in the template parameter of the component.
Our task is to “cross” angular and ASP .Net Core. This means that we will use the controller and views for action. Quite a standard ASP .Net Core MVC application. The easiest solution is to pass a view in the iframe:
App.component.ts:
import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    template: `<div>
                    <iframe  id="report" height="1000" width="1000" src= "api/SampleData/ShowReport"></iframe>
               </div>`
})
export class AppComponent {
}

Such a simple code allows you to display the report immediately when loading the SPA application. This is suitable if you have selected a separate page for the report, but if you need more interactivity? For example, a button that, when clicked, loads the report. Let's add a button to the page template, as well as a button click event and its handler:

@Component({
    selector: 'app-root',
    template: `<div>
                    <input type="button" (click)="Clicked()" value = "Show Report"/>
                   <div *ngIf="show">
                    <iframe id="report" height="1000" width="1000" src= "api/SampleData/ShowReport"></iframe>
                    </div>
               </div>`
})
export class AppComponent {
    show: boolean = false;

    Clicked() {
        this.show = true;
    }
}
We added a button and a clicked event in its attributes. But how to hide the frame before the button is pressed? To do so, we wrapped the frame in a div that has a condition - check the ‘show’ variable for ‘true’. By default, this variable is set to false, so this div will not be shown when the page is displayed. Thus, the Clicked function simply sets the value of the show variable to true.
It would be good to put the src value for the frame into a variable and set it in the clicked function. However, if you just do this:
<iframe id="report" height="1000" width="1000" [src]="url | safeUrl"></iframe>
url: string;

    Clicked() {
        this.show = true;
        this.url = "api/SampleData/ShowReport";
    }

That will not work. The fact is that the link needs to be normalized using a special “cleaner” - DOMSanitizer. It is designed to make html code and url safe from malicious inclusions.
Let's create the safeUrl.pipe.ts script in the app folder:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({ name: 'safeUrl' })
export class SafeUrlPipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) { }
    transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}
This class will check the url for security in the correct format. In order to use this Pipe in the app.component, we need to add it to the modules in app.module.ts:
import { SafeUrlPipe } from "./safeUrl.pipe";

@NgModule({
  declarations: [
    AppComponent,
      SafeUrlPipe
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
      FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Let's go back to app.component.ts. Now we can use Pipe:
 import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    template: `<div>
                    <input type="button" (click)="Clicked()" value = "Show Report"/>
                   <div *ngIf="show">
                    <iframe id="report" height="1000" width="1000" [src]="url | safeUrl"></iframe>
                    </div>
               </div>`
})
export class AppComponent {
    show: boolean = false;
    url: string;

    Clicked() {
        this.show = true;
        this.url = "api/SampleData/ShowReport";
    }
}

Further developing the idea, you can add the parameter name of the report to the ShowReport method, and get the desired report at the output.
There is a final touch before launching the application. Open the Startup.cs file and add one line to the Configure () method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseFastReport();
        }
Thus, we connected to the application FastReportBuilderExtensions, which will allow rendering reports.
And now let's run our demo application:

By pressing the button, we got the desired report. As you can see, there is nothing difficult to use FastReport with Angular SPA. If, in addition to reports, you want to use an online designer, then pay attention to another article - How to use Online Designer in a Single Page Application Angular 7.


Comments

  1. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my website as well.

    p2gamer
    Freelancers Marketplace

    Thank you..

    ReplyDelete
  2. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my website as well.

    Hire an Expert to take an Online Exam

    Thank you..

    ReplyDelete
  3. Thanks for sharing this wonderful content. its very interesting. Many blogs I see these days do not really provide anything that attracts others but the way you have clearly explained everything it's really fantastic. There are lots of posts But your way of Writing is so Good & Knowledgeable. keep posting such useful information and have a look at my site as well

    Rowe Rowe yahoo news
    Rowe Rowe Royal interval it shows

    Thank you..

    ReplyDelete
  4. Great, thank you so much for sharing such amazing information with us. Visit OGEN Infosystem for professional Website Designing and UI/UX Designing Services at an affordable price in Delhi, India.
    Website Designing Company in Delhi

    ReplyDelete
  5. Much obliged for sharing this superb substance. its extremely intriguing. Numerous web journals I see these days don't actually give whatever pulls in others however the manner in which you have plainly clarified everything it's truly phenomenal. There are loads of posts But your method of Writing is so Good and Knowledgeable. continue to post such helpful data and view my site also

    Rehab Nashville

    Thank you..

    ReplyDelete
  6. Specialized centre for immediate dental implants. We develop successful dental tourism in Bulgaria and offer our services in 12 languages to restore your smile beauty just in a single visit. We gathered all you need in one place, using the most advanced technologies (ISO certificate under EU rules): Radiography centre with the scanner, Panoramic X-Ray by 3D analysis, Dental x-ray machine for intraoral pictures. A dental laboratory specializing in prosthetics of dental implants. Eight dental cabinets with one VIP cabinet.
    Our team consists of Implantologists-specialized in Basal implant, Oral Surgeons, Dentists, assistants, qualified Interpreters, cardiologists, radiologists, and anaesthetists who are at your disposal during the treatment. Want to know ?

    Dental implants price
    How much do dental implants cost

    Visit us now! Thank you..

    ReplyDelete
  7. Thanks for sharing this wonderful content.its very interesting .Many blogs I see these days do not really provide anything that attracts others but the way you have clearly explained everything it's really fantastic.There are lots of posts But your way of Writing is so Good & Knowledgeable.keep posting such useful information and have a look at my site as well

    Promo Codes,Coupon Codes,Coupons
    Voucher Codes,Discount Codes,Online Promo Codes,Online Coupon Codes

    Thank you..

    ReplyDelete
  8. Present in the advanced market for in any event 20 years, we have improved the destinations of in excess of 400 customers. Do you need a unique, reasonable and significant Site creation and referencing ? You are in the perfect spot! With ID Design ( Marketing agency ) we acknowledge your activities. We cautiously dissect your objectives and solicitations. We start work after a few trades.

    We will probably assemble an imaginative and productive site to expand your turnover . We subsequently focus on straightforwardness and furnish you with all our advanced promoting abilities. Come see us or call us, you won’t be frustrated!

    ReplyDelete
  9. It would be easy for me to understand it if you make a video with every steps. You could post your video on tiktok. I know from here https://www.myfrugalbusiness.com/2020/05/how-to-buy-paid-views-tiktok-videos.html how to get views and can advise you.

    ReplyDelete
  10. Precision Outdoors provides lightning fast shipping on the most trusted brands in gun parts & accessories like Ar 15 accessories, Ar stock, Law tactical folders, red dot sights, rifle scopes, magazines, frames, barrels, triggers, stocks, and much more...

    So don't wait anymore Visit us now!

    ReplyDelete
  11. Cosmetic Formulators has been in the cosmetic contract manufacturing industry long enough to understand your unique product needs, and can help you launch your new product in a way that ensures optimum results.

    So don't wait anymore Visit us now!

    ReplyDelete
  12. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my article as well.

    Erectile dysfunction treatment in India

    Thanks..

    ReplyDelete
  13. Avalanche provides a host of online services to businesses & influencers in Ireland & around the world including web design in Kerry, Cork, Limerick and pretty much all over Ireland, eCommerce solutions, SEO, graphic design, social media marketing, video production & more. We capture our client's unique personalities in their website as it is so important to stand out in today's saturated online world.

    Avalanche is much more than a service provider, we provide high end technical support to all our clients & become their digital partners to ensure that they are successful online. We would love to hear from you and help in any way we can.

    ReplyDelete
  14. IEEE Final Year Project centers make amazing deep learning final year projects ideas for final year students Final Year Projects for CSE to training and develop their deep learning experience and talents.

    IEEE Final Year projects Project Centers in India are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation.

    corporate training in chennai corporate training in chennai

    corporate training companies in india corporate training companies in india

    corporate training companies in chennai corporate training companies in chennai

    I have read your blog its very attractive and impressive. I like it your blog. Digital Marketing Company in Chennai Project Centers in Chennai

    ReplyDelete
  15. We are an independent Australian pet food online store based in Queensland. We deliver premium pet food brands like Prime100 kangaroo , ivory cat kitten plus medications, toys, accessories and treats, offering free same day delivery to certain Queensland metro areas.

    ReplyDelete
  16. Tennis shop uk is the UK's leading online Tennis Shop. We supply the best range of equipment including Babolat tennis rackets, Head tennis rackets , clothing bags and balls from Babolat, HEAD, Dunlop, MANTIS, Yonex and Tecnifibre.

    ReplyDelete
  17. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my website as well.

    Clothes & Thrift Shop
    Occasion

    Thank You!

    ReplyDelete
  18. Looking for an experienced professional emcee in Singapore who is known in the world of weddings and events? Introducing Emcee James Yang, one of Singapore’s most sought-after Emcees & a veteran in the corporate world and wedding industry.

    Singapore Emcee James Yang is a dynamic emcee whose magnetic personality engages the audience unlike any other master of ceremonies. Events hosted by him are like a dialogue between himself the audience. He speaks, they laugh, he charms, they respond in kind; every moment is compelling and interactive.

    His reputation as a Professional Singapore Emcee has gradually risen over the years and his career is proof of his versatility- from celebrities to military personnel and countless event/wedding companies, he’s collaborated with them all. Whichever the occasion, James is often the Top Choice Emcee amongst clients.

    ReplyDelete

Post a Comment

Popular posts

How to use FastReport Open Source in ASP.NET Core Web API application

FastReport Open Source - what is it and how to use it

FastReport Designer Community Edition