Skip to main content

Add a Report Storage (ASP.NET Core)

  • 10 minutes to read

Design Considerations

The End-User Report Designer for Web requires a report storage to operate correctly. The table below lists the functions that will be unavailable to users if a report storage is not registered in your application.

Commands/Functions With Storage Without Storage
Edit the report supplied from code Yes Yes
Save Yes
Save As Yes
Open Yes
New Yes
New via Wizard Yes
Manage Subreports Yes

As shown in this table, users can edit a report but cannot use multiple stored report definitions. If these limitations are suitable for your application, you can work with reports without a custom storage. Otherwise, create and register a report storage.

Create and Register a Report Storage

Follow the steps below to create a server-side storage for web reports.

Create a Report Storage Class

Create a class that inherits from the abstract ReportStorageWebExtension class. You can write a new class or use the DevExpress Project Wizard.

If you use the DevExpress Project Wizard, leave the Add Report Storage option checked. The wizard generates and registers a file system report storage. You can specify the class name in the Report Storage Name field:

Reporting Project Wizard

DevExpress Project Templates always create and register a file-based report storage if you create a project from the console (CLI).

Important

The template generates a sample storage (a ReportStorageWebExtension descendant) for demonstration purposes only. Create your own implementation for use in production.

Override Class Methods

You need to implement the following methods:

Method Description
IsValidUrl Determines whether the URL passed to the current report storage is valid. Implement your own logic to prohibit URLs that contain spaces or other specific characters. Return true if no validation is required.
CanSetData Determines whether a report with the specified URL can be saved. Add custom logic that returns false for reports that should be read-only. Return true if no valdation is required. This method is called only for valid URLs (if the IsValidUrl method returns true).
SetData Saves the specified report to the report storage with the specified URL (i.e., it saves existing reports only).
SetNewData Allows you to validate and correct the specified URL. This method also allows you to return the resulting URL and to save your report to a storage. The method is called only for new reports.
GetData Uses a specified URL to return report layout data stored within a report storage medium. This method is called if the IsValidUrl method returns true. You can use the GetData method to process report parameters sent from the client if the parameters are included in the report URL’s query string.
GetUrls Returns a dictionary that contains the report URLs and display names.

In the following table, select a column that describes the user action. Then, read the entries top to bottom for information on the order of method calls. The table also indicates the moments when the designer invokes Open Report and Save Report dialogs.

Method/Command Save As Save Open
GetUrls Yes Yes
(Open Report dialog) Yes
IsValidUrl Yes Yes
CanSetData Yes
(Save Report dialog) Yes
SetNewData Yes
SetData Yes
GetData Yes
GetUrls Yes

For more information on how the reports and documents are stored, review the following help topic: Store Report Layouts and Documents.

Register a Storage

Skip this step if you used a project template to generate your report storage class. If you declared a ReportStorageWebExtension descendant manually, register your web report storage medium as a service at application startup:

using DevExpress.XtraReports.Web.Extensions;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDevExpressControls();
// Register the storage after the AddDevExpressControls method call.
builder.Services.AddScoped<ReportStorageWebExtension, CustomReportStorageWebExtension>(); 

var app = builder.Build();

Important

Register the ReportStorageWebExtension after the AddDevExpressControls method.

Report Storage Examples

For a code example, create a new Web project from the DevExpress Visual Studio template and review the code for the CustomReportStorageWebExtension class in the Services folder.

For more information review the following help topic: Use Visual Studio Templates to Create an ASP.NET Core Application with a Report Designer

How to Store Reports in a SQLite database

This example implements the database report storage. Add the CustomReportStorageWebExtension class that inherits the ReportStorageWebExtension class. The CustomReportStorageWebExtension class uses the ReportDbContext class for database operations, and the ReportsFactory class for report name resolution. Add the ReportDbContext that inherits the DbContext class and interacts with the database. Add the ReportsFactory class that implements custom logic to translate a report name into a report instance. Register the report storage at the application startup. Register the database context as a service at the application startup, and initialize the database.

using System.Collections.Generic;
using System.IO;
using System.Linq;
using DevExpress.XtraReports.UI;
using DXReportingCustomConnectionString.PredefinedReports;
using DXReportingCustomConnectionString.Data;
// ...
    public class CustomReportStorageWebExtension : DevExpress.XtraReports.Web.Extensions.ReportStorageWebExtension
    {
        protected ReportDbContext DbContext { get; set; }
        public CustomReportStorageWebExtension(ReportDbContext dbContext) {
            this.DbContext = dbContext;
        }

        public override bool CanSetData(string url) {
            // Determines whether a report with the specified URL can be saved.
            // Add custom logic that returns **false** for reports that should be read-only.
            // Return **true** if no valdation is required.
            // This method is called only for valid URLs (if the **IsValidUrl** method returns **true**).

            return true;
        }

        public override bool IsValidUrl(string url) {
            // Determines whether the URL passed to the current report storage is valid.
            // Implement your own logic to prohibit URLs that contain spaces or other specific characters.
            // Return **true** if no validation is required.

            return true;
        }

        public override byte[] GetData(string url) {
            // Uses a specified URL to return report layout data stored within a report storage medium.
            // This method is called if the **IsValidUrl** method returns **true**.
            // You can use the **GetData** method to process report parameters sent from the client
            // if the parameters are included in the report URL's query string.
            var reportData = DbContext.Reports.FirstOrDefault(x => x.Name == url);
            if(reportData != null)
                return reportData.LayoutData;

            if(ReportsFactory.Reports.ContainsKey(url)) {
                using var ms = new MemoryStream();
                using XtraReport report = ReportsFactory.Reports[url]();
                report.SaveLayoutToXml(ms);
                return ms.ToArray();
            }
            throw new DevExpress.XtraReports.Web.ClientControls.FaultException(string.Format("Could not find report '{0}'.", url));
        }

        public override Dictionary<string, string> GetUrls() {
            // Returns a dictionary that contains the report names (URLs) and display names. 
            // The Report Designer uses this method to populate the Open Report and Save Report dialogs.

            return DbContext.Reports
                .ToList()
                .Select(x => x.Name)
                .Union(ReportsFactory.Reports.Select(x => x.Key))
                .ToDictionary<string, string>(x => x);
        }

        public override void SetData(XtraReport report, string url) {
            // Saves the specified report to the report storage with the specified name
            // (saves existing reports only). 
            using var stream = new MemoryStream(); report.SaveLayoutToXml(stream);
            var reportData = DbContext.Reports.FirstOrDefault(x => x.Name == url);
            if(reportData == null) {
                DbContext.Reports.Add(new ReportItem { Name = url, LayoutData = stream.ToArray() });
            } else {
                reportData.LayoutData = stream.ToArray();
            }
            DbContext.SaveChanges();
        }

        public override string SetNewData(XtraReport report, string defaultUrl) {
            // Allows you to validate and correct the specified name (URL).
            // This method also allows you to return the resulting name (URL),
            // and to save your report to a storage. The method is called only for new reports.
            SetData(report, defaultUrl);
            return defaultUrl;
        }
    }
using System.Linq;
using Microsoft.EntityFrameworkCore;
// ...
    public class SqlDataConnectionDescription : DataConnection { }
    public class JsonDataConnectionDescription : DataConnection { }
    public abstract class DataConnection {
        public int Id { get; set; }
        public string Name { get; set; }
        public string DisplayName { get; set; }
        public string ConnectionString { get; set; }
    }

    public class ReportItem {
        public int Id { get; set; }
        public string Name { get; set; }
        public string DisplayName { get; set; }
        public byte[] LayoutData { get; set; }
    }

    public class ReportDbContext : DbContext {
        public DbSet<JsonDataConnectionDescription> JsonDataConnections { get; set; }
        public DbSet<SqlDataConnectionDescription> SqlDataConnections { get; set; }
        public DbSet<ReportItem> Reports { get; set; }
        public ReportDbContext(DbContextOptions<ReportDbContext> options) : base(options) {
        }
        public void InitializeDatabase() {
            Database.EnsureCreated();

            var nwindJsonDataConnectionName = "NWindProductsJson";
            if(!JsonDataConnections.Any(x => x.Name == nwindJsonDataConnectionName)) {
                var newData = new JsonDataConnectionDescription {
                    Name = nwindJsonDataConnectionName,
                    DisplayName = "Northwind Products (JSON)",
                    ConnectionString = "Uri=Data/nwind.json"
                };
                JsonDataConnections.Add(newData);
            }


            var nwindSqlDataConnectionName = "NWindConnectionString";
            if(!SqlDataConnections.Any(x => x.Name == nwindSqlDataConnectionName)) {
                var newData = new SqlDataConnectionDescription {
                    Name = nwindSqlDataConnectionName,
                    DisplayName = "Northwind Data Connection",
                    ConnectionString = "XpoProvider=SQLite;Data Source=|DataDirectory|/Data/nwind.db"
                };
                SqlDataConnections.Add(newData);
            }

            var reportsDataConnectionName = "ReportsDataSqlite";
            if(!SqlDataConnections.Any(x => x.Name == reportsDataConnectionName)) {
                var newData = new SqlDataConnectionDescription {
                    Name = reportsDataConnectionName,
                    DisplayName = "Reports Data (Demo)",
                    ConnectionString = "XpoProvider=SQLite;Data Source=|DataDirectory|/Data/reportsData.db"
                };
                SqlDataConnections.Add(newData);
            }
            SaveChanges();
        }
    }
using DevExpress.XtraReports.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// ...
    public static class ReportsFactory
    {
        public static Dictionary<string, Func<XtraReport>> Reports = new Dictionary<string, Func<XtraReport>>()
        {
            ["TestReport"] = () => new TestReport()
        };
    }
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<ReportStorageWebExtension, CustomReportStorageWebExtension>();
builder.Services.AddDbContext<ReportDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("ReportsDataConnectionString")));

var app = builder.Build();

db.InitializeDatabase();

app.UseDevExpressControls();

app.Run();

How to Store Reports in Azure Cosmos DB

Review the following blog post: ASP.NET Core Reporting - Store Reports within a Database Using Azure Cosmos DB.

How to Store Reports in a File System

This example implements the file report storage. Add the CustomReportStorageWebExtension class that inherits the ReportStorageWebExtension class and register the file storage at the application startup.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using DevExpress.XtraReports.Web.Extensions;
using DevExpress.XtraReports.UI;
using ReportAtRuntimeMvcApp.PredefinedReports;
// ...
    public class CustomReportStorageWebExtension : DevExpress.XtraReports.Web.Extensions.ReportStorageWebExtension
    {
        readonly string reportDirectory;
        const string FileExtension = ".repx";
        public CustomReportStorageWebExtension(string reportDirectory) {
            if (!Directory.Exists(reportDirectory)) {
                Directory.CreateDirectory(reportDirectory);
            }
            this.reportDirectory = reportDirectory;
        }

        private bool IsWithinReportsFolder(string url, string folder) {
            var rootDirectory = new DirectoryInfo(folder);
            var fileInfo = new FileInfo(Path.Combine(folder, url));
            return fileInfo.Directory.FullName.ToLower().StartsWith(rootDirectory.FullName.ToLower());
        }

        public override bool CanSetData(string url) {
            // Determines whether a report with the specified URL can be saved.
            // Add custom logic that returns **false** for reports that should be read-only.
            // Return **true** if no valdation is required.
            // This method is called only for valid URLs (if the **IsValidUrl** method returns **true**).

            return true;
        }

        public override bool IsValidUrl(string url) {
            // Determines whether the URL passed to the current report storage is valid.
            // Implement your own logic to prohibit URLs that contain spaces or other specific characters.
            // Return **true** if no validation is required.

            return Path.GetFileName(url) == url;
        }

        public override byte[] GetData(string url) {
            // Uses a specified URL to return report layout data stored within a report storage medium.
            // This method is called if the **IsValidUrl** method returns **true**.
            // You can use the **GetData** method to process report parameters sent from the client
            // if the parameters are included in the report URL's query string.
            try {
                if (Directory.EnumerateFiles(reportDirectory).Select(Path.GetFileNameWithoutExtension).Contains(url))
                {
                    return File.ReadAllBytes(Path.Combine(reportDirectory, url + FileExtension));
                }
                if (ReportsFactory.Reports.ContainsKey(url))
                {
                    using (MemoryStream ms = new MemoryStream()) {
                        ReportsFactory.Reports[url]().SaveLayoutToXml(ms);
                        return ms.ToArray();
                    }
                }
            } catch (Exception) {
                throw new FaultException(new FaultReason("Could not get report data."), new FaultCode("Server"), "GetData");
            }
            throw new FaultException(new FaultReason(string.Format("Could not find report '{0}'.", url)), new FaultCode("Server"), "GetData");
        }

        public override Dictionary<string, string> GetUrls() {
            // Returns a dictionary that contains the report names (URLs) and display names. 
            // The Report Designer uses this method to populate the Open Report and Save Report dialogs.

            return Directory.GetFiles(reportDirectory, "*" + FileExtension)
                                     .Select(Path.GetFileNameWithoutExtension)
                                     .Union(ReportsFactory.Reports.Select(x => x.Key))
                                     .ToDictionary<string, string>(x => x);
        }

        public override void SetData(XtraReport report, string url) {
            // Saves the specified report to the report storage with the specified name
            // (saves existing reports only). 
            if(!IsWithinReportsFolder(url, reportDirectory))
                throw new FaultException(new FaultReason("Invalid report name."), new FaultCode("Server"), "GetData");
            report.SaveLayoutToXml(Path.Combine(reportDirectory, url + FileExtension));
        }

        public override string SetNewData(XtraReport report, string defaultUrl) {
            // Allows you to validate and correct the specified name (URL).
            // This method also allows you to return the resulting name (URL),
            // and to save your report to a storage. The method is called only for new reports.
            SetData(report, defaultUrl);
            return defaultUrl;
        }
    }