Devexpress Dashboard Control Integration In Angular

Hello Friends, In this article, we will learn how to integrate Dev-Express dashboard control in an angular application with .NET Core backend configuration.

Now First, we need to create API Project; In Visual Studio, create a new project and select ASP.NET Core Web Application on the start page, and then select Create.

In the NuGet Package Manager, install the following package:

DevExpress.AspNetCore.Dashboard

1. Open package manages settings.


2. Add a new item in the package source
Name: DevExpres
       Source: https://nuget.devexpress.com/<https://nuget.devexpress.com/{your-feed-authorization-key}>/api


3. Open manage NuGet packages


4. Select package source


5. Add package “DevExpress.AspNetCore.Dashboard“.

Now add the below code in Startup.cs file under ConfigureServices method.

services.AddControllersWithViews();
services.AddRazorPages();
services
   .AddCors(options =>
   {
       options.AddPolicy("CorsPolicy", builder =>
       {
           builder.AllowAnyOrigin();
           builder.AllowAnyMethod();
           builder.WithHeaders("Content-Type");
       });
   })
   .AddDevExpressControls()
   .AddControllers()
   .AddDefaultDashboardController((configurator, serviceProvider) =>
   {
       configurator.SetConnectionStringsProvider(new DashboardConnectionStringsProvider(Configuration));
       configurator.SetDashboardStorage(new DashboardFileStorage(FileProvider.GetFileInfo("App_Data/Dashboards").PhysicalPath));
       configurator.SetDataSourceStorage(CreateDataSourceStorage());
       configurator.SetConnectionStringsProvider(new DashboardConnectionStringsProvider(Configuration));
       configurator.ConfigureDataConnection += Configurator_ConfigureDataConnection;
   });

Now, create a new method under Startup.cs file CreateDataSourceStorage for Dashboard data source

public DataSourceInMemoryStorage CreateDataSourceStorage()
{
    DataSourceInMemoryStorage dataSourceStorage = new DataSourceInMemoryStorage();
    
    DashboardJsonDataSource jsonDataSourceUrl = new DashboardJsonDataSource("Dashboard Data Source");
    string baseURL = "https://localhost:44395/";
    jsonDataSourceUrl.JsonSource = new UriJsonSource(new Uri($"{baseURL}api/home/dashboard"));
    dataSourceStorage.RegisterDataSource("jsonDataSourceUrl", jsonDataSourceUrl.SaveToXml());

    return dataSourceStorage;
}
private void Configurator_ConfigureDataConnection(object sender, ConfigureDataConnectionWebEventArgs e)
{
}

Now, add the below code under Configure method of Startup.cs file

app.UseDevExpressControls();
            
app.UseCors("CorsPolicy");

app.UseAuthentication();

app.UseEndpoints(endpoints =>
{
    EndpointRouteBuilderExtension.MapDashboardRoute(endpoints, "api/dashboard");

    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller}/{action=Index}/{id?}");
    endpoints.MapRazorPages();


    // Requires CORS policies.
    endpoints.MapControllers().RequireCors("CorsPolicy");
});

Finally, our Startup.cs look like below

public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment hostingEnvironment)
        {
            Configuration = configuration;
            FileProvider = hostingEnvironment.ContentRootFileProvider;
        }

        public IConfiguration Configuration { get; }
        public IFileProvider FileProvider { get; }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
            services.AddControllersWithViews();
            services.AddRazorPages();
            services
               .AddCors(options =>
               {
                   options.AddPolicy("CorsPolicy", builder =>
                   {
                       builder.AllowAnyOrigin();
                       builder.AllowAnyMethod();
                       builder.WithHeaders("Content-Type");
                   });
               })
               .AddDevExpressControls()
               .AddControllers()
               .AddDefaultDashboardController((configurator, serviceProvider) =>
               {
                   configurator.SetConnectionStringsProvider(new DashboardConnectionStringsProvider(Configuration));
                   configurator.SetDashboardStorage(new DashboardFileStorage(FileProvider.GetFileInfo("App_Data/Dashboards").PhysicalPath));
                   configurator.SetDataSourceStorage(CreateDataSourceStorage());
                   configurator.SetConnectionStringsProvider(new DashboardConnectionStringsProvider(Configuration));
                   configurator.ConfigureDataConnection += Configurator_ConfigureDataConnection;
               });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            if (!env.IsDevelopment())
            {
                app.UseSpaStaticFiles();
            }

            app.UseRouting();

            app.UseDevExpressControls();
            
            app.UseCors("CorsPolicy");

            app.UseAuthentication();
            
            app.UseEndpoints(endpoints =>
            {
                EndpointRouteBuilderExtension.MapDashboardRoute(endpoints, "api/dashboard");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
                endpoints.MapRazorPages();


                // Requires CORS policies.
                endpoints.MapControllers().RequireCors("CorsPolicy");
            });

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }

        public DataSourceInMemoryStorage CreateDataSourceStorage()
        {
            DataSourceInMemoryStorage dataSourceStorage = new DataSourceInMemoryStorage();
            
            DashboardJsonDataSource jsonDataSourceUrl = new DashboardJsonDataSource("Dashboard Data Source");
            string baseURL = "https://localhost:44395/";
            jsonDataSourceUrl.JsonSource = new UriJsonSource(new Uri($"{baseURL}api/home/dashboard"));
            dataSourceStorage.RegisterDataSource("jsonDataSourceUrl", jsonDataSourceUrl.SaveToXml());

            return dataSourceStorage;
        }
        private void Configurator_ConfigureDataConnection(object sender, ConfigureDataConnectionWebEventArgs e)
        {
        }
    }

Now, we are adding dashboard controls in the Angular application:

First, we need to install dashboard control using the following npm command:

npm install devexpress-dashboard@20.2-next devexpress-dashboard-angular@20.2-next @devexpress/analytics-core@20.2-next devextreme@20.2-next  devextreme-angular@20.2-next --save

Import the Dashboard Module In the app.module.ts file, import the DxDashboardControlModule module.

// ...
import { DxDashboardControlModule } from 'devexpress-dashboard-angular';

@NgModule({
  imports: [
    // ...
      DxDashboardControlModule
  ],
  // ...
})
export class AppModule { }

Now add the dashboard control in the app.component.html file.

<dx-dashboard-control style="display: block;width:100%;height:800px;" endpoint="/api/dashboard"
    (onDashboardInitialized)="reloadData()" [workingMode]="workingMode">
</dx-dashboard-control>

Now add the below code in the app.component.ts file.

@ViewChild(DxDashboardControlComponent, { static: false }) dashboardComponent: DxDashboardControlComponent
  workingMode: string = "ViewerOnly";
  dashboardControl: any;


  constructor(
    private http: HttpClient
  ) { }

  reloadData() {
    if(this.dashboardComponent)
      this.dashboardComponent.instance.reloadData();
  }

Now add the following global styles to the styles.css file:

@import url("../node_modules/jquery-ui/themes/base/all.css");
@import url("../node_modules/devextreme/dist/css/dx.light.css");  
@import url("../node_modules/@devexpress/analytics-core/dist/css/dx-analytics.common.css");  
@import url("../node_modules/@devexpress/analytics-core/dist/css/dx-analytics.light.css");  
@import url("../node_modules/@devexpress/analytics-core/dist/css/dx-querybuilder.css");  
@import url("../node_modules/devexpress-dashboard/dist/css/dx-dashboard.light.css");

Now Run the application and see the output look likes below.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories