Back to Devexpress

Add a Report Storage (ASP.NET MVC)

xtrareports-400204-web-reporting-asp-net-mvc-reporting-end-user-report-designer-in-asp-net-mvc-applications-add-a-report-storage.md

latest24.4 KB
Original Source

Add a Report Storage (ASP.NET MVC)

  • Feb 16, 2026
  • 13 minutes to read

Design Considerations

When you add the End-User Report Designer for Web to your project, it operates without a report storage. You should consider whether your application requires a custom report storage and think ahead about the implementation details. The table below lists the functions that will be unavailable to end users without a report storage registered in your application.

Commands/FunctionsWith StorageWithout Storage
Save
Save As
Open
New
New via Wizard
Manage Subreports

As you can see in the table above, you can edit a report, but cannot manipulate multiple stored report definitions. If these limitations are suitable for your application, you can work with reports without a custom storage.

Operation without a Report Storage

Initially the Report Designer operates without the New via Wizard , Open and Save As menu commands. This operation mode also doesn’t allow end users to manage Subreports - a double click on a subreport has no effect.

The client-side API methods that allows you to load and save a report do not work without a report storage. Use the following server-side API to load a report to the End-User Designer and save user changes:

APIDescription
ASPxReportDesigner.OpenReportLoad a report layout into the Designer.
ASPxReportDesigner.OpenReportXmlLayout(Byte[])Load a report layout from the byte array of XML data (REPX format) into the Designer.
ReportDesignerSettings.SaveCallbackRouteValuesSpecifies the Controller and Action that allows you to get the report layout as a byte array of XML data and save a report to the REPX file.

Operation with a Report Storage

To save and load reports, the DevExpress Web Report Designer requires access to a storage medium (a database, file system, cloud service, etc.). To add a server-side report storage medium to your web application, you must create and register a custom report storage class.

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 use one of the following methods:

  • 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:

  • Click Add New Item in the Visual Studio Designer and select the DevExpress v25.2 Report Storage Web item in the Reporting section:

  • You can use the ASP.NET MVC extension wizard:

Override Class Methods

You need to implement the following methods:

MethodDescription
IsValidUrlDetermines 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.
CanSetDataDetermines 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 ).
SetDataSaves the specified report to the report storage with the specified URL (i.e., it saves existing reports only).
SetNewDataAllows 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.
GetDataUses 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.
GetUrlsReturns 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/CommandSave AsSaveOpen
GetUrls
(Open Report dialog)
IsValidUrl
CanSetData
(Save Report dialog)
SetNewData
SetData
GetData
GetUrls

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, item template, or smart tag to generate your report storage class. If you declared a ReportStorageWebExtension descendant manually, create a new instance and pass it to the static ReportStorageWebExtension.RegisterExtensionGlobal method at application startup:

csharp
public class MvcApplication : System.Web.HttpApplication {
    protected void Application_Start() {
        // ...
        DevExpress.XtraReports.Web.Extensions.ReportStorageWebExtension.RegisterExtensionGlobal(new CustomReportStorageWebExtension);
    // ...
    }
}
vb
Public Class MvcApplication
    Inherits System.Web.HttpApplication
    Sub Application_Start()
        ' ...
        DevExpress.XtraReports.Web.Extensions.ReportStorageWebExtension.RegisterExtensionGlobal(New CustomReportStorageWebExtension)
        ' ...
    End Sub
    ' ...
End Class

Report Storage Examples

Database Sample Storage

View Example: Web Reporting ASP.NET MVC Application with End-User Report Designer and Report Database Storage

csharp
using System;
using System.Linq;
using System.Collections.Generic;
using DevExpress.Xpo;
using DevExpress.XtraReports.UI;
using DevExpress.XtraReports.Web.Extensions;
using System.IO;
using Mvc_DbStorage_Sample.Services.DAL;

namespace Mvc_DbStorage_Sample.Services {
    public class CustomReportStorageWebExtension : ReportStorageWebExtension {
        public override bool CanSetData(string url) {
            // Check if the URL is available in the report storage.
            using (var session = SessionFactory.Create()) {
                return session.GetObjectByKey<ReportEntity>(url) != null;
            }
        }

        public override byte[] GetData(string url) {
            // Get the report data from the storage.
            using (var session = SessionFactory.Create()) {
                var report = session.GetObjectByKey<ReportEntity>(url);
                return report.Layout;
            }

        }

        public override Dictionary<string, string> GetUrls() {
            // Get URLs and display names for all reports available in the storage
            using (var session = SessionFactory.Create()) {
                return session.Query<ReportEntity>().ToDictionary<ReportEntity, string, string>(report => report.Url, report => report.Url);
            }
        }

        public override bool IsValidUrl(string url) {
            // Check if the specified URL is valid for the current report storage.
            // In this example, a URL should be a string containing a numeric value that is used as a data row primary key.
            return true;
        }

        public override void SetData(XtraReport report, string url) {
            // Write a report to the storage under the specified URL.
            using (var session = SessionFactory.Create()) {
                var reportEntity = session.GetObjectByKey<ReportEntity>(url);

                MemoryStream ms = new MemoryStream();
                report.SaveLayoutToXml(ms);
                reportEntity.Layout = ms.ToArray();

                session.CommitChanges();
            }
        }

        public override string SetNewData(XtraReport report, string defaultUrl) {
            // Save a report to the storage under a new URL. 
            // The defaultUrl parameter contains the report display name specified by a user.
            if (CanSetData(defaultUrl))
                SetData(report, defaultUrl);
            else
                using (var session = SessionFactory.Create()) {
                    MemoryStream ms = new MemoryStream();
                    report.SaveLayoutToXml(ms);

                    var reportEntity = new ReportEntity(session) {
                        Url = defaultUrl,
                        Layout = ms.ToArray()
                    };

                    session.CommitChanges();
                }
            return defaultUrl;
        }
    }
}
vb
Imports System
Imports System.Linq
Imports System.Collections.Generic
Imports DevExpress.Xpo
Imports DevExpress.XtraReports.UI
Imports DevExpress.XtraReports.Web.Extensions
Imports System.IO
Imports Mvc_DbStorage_Sample_VB.Services.DAL

Public Class CustomReportStorageWebExtension
    Inherits ReportStorageWebExtension

    Public Overrides Function CanSetData(ByVal url As String) As Boolean
        ' Check if the URL is available in the report storage.
        Using session = SessionFactory.Create()
            Return session.GetObjectByKey(Of ReportEntity)(url) IsNot Nothing
        End Using
    End Function

    Public Overrides Function GetData(ByVal url As String) As Byte()
        ' Get the report data from the storage.
        Using session = SessionFactory.Create()
            Dim report = session.GetObjectByKey(Of ReportEntity)(url)
            Return report.Layout
        End Using

    End Function

    Public Overrides Function GetUrls() As Dictionary(Of String, String)
        ' Get URLs and display names for all reports available in the storage
        Using session = SessionFactory.Create()
            Return session.Query(Of ReportEntity)().ToDictionary(Function(report) report.Url, Function(report) report.Url)
        End Using
    End Function

    Public Overrides Function IsValidUrl(ByVal url As String) As Boolean
        ' Check if the specified URL is valid for the current report storage.
        ' In this example, a URL should be a string containing a numeric value that is used as a data row primary key.
        Return True
    End Function

    Public Overrides Sub SetData(ByVal report As XtraReport, ByVal url As String)
        ' Write a report to the storage under the specified URL.
        Using session = SessionFactory.Create()
            Dim reportEntity = session.GetObjectByKey(Of ReportEntity)(url)

            Dim ms As New MemoryStream()
            report.SaveLayoutToXml(ms)
            reportEntity.Layout = ms.ToArray()

            session.CommitChanges()
        End Using
    End Sub

    Public Overrides Function SetNewData(ByVal report As XtraReport, ByVal defaultUrl As String) As String
        ' Save a report to the storage under a new URL. 
        ' The defaultUrl parameter contains the report display name specified by a user.
        If CanSetData(defaultUrl) Then
            SetData(report, defaultUrl)
        Else
            Using session = SessionFactory.Create()
                Dim ms As New MemoryStream()
                report.SaveLayoutToXml(ms)

                Dim reportEntity = New ReportEntity(session) With {
                    .Url = defaultUrl,
                    .Layout = ms.ToArray()
                }

                session.CommitChanges()
            End Using
        End If
        Return defaultUrl
    End Function
End Class

File System Sample Storage

Note

You can create a sample Reporting ASP.NET MVC application using Visual Studio project template. The sample application includes a file-based report storage. Review the following help topic for more information: : Use DevExpress Visual Studio Templates to Create an ASP.NET MVC Reporting App with a Report Designer.

csharp
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.Reportsurl.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;
        }
    }
vb
Imports System
Imports System.Collections.Concurrent
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Reflection
Imports System.ServiceModel
Imports DevExpress.XtraReports.Web.Extensions
Imports DevExpress.XtraReports.UI
Imports ReportAtRuntimeMvcApp.PredefinedReports
' ...
    Public Class CustomReportStorageWebExtension
        Inherits DevExpress.XtraReports.Web.Extensions.ReportStorageWebExtension

        Private ReadOnly reportDirectory As String
        Private Const FileExtension As String = ".repx"
        Public Sub New(ByVal reportDirectory As String)
            If Not Directory.Exists(reportDirectory) Then
                Directory.CreateDirectory(reportDirectory)
            End If
            Me.reportDirectory = reportDirectory
        End Sub

        Private Function IsWithinReportsFolder(ByVal url As String, ByVal folder As String) As Boolean
            Dim rootDirectory = New DirectoryInfo(folder)
            Dim fileInfo = New FileInfo(Path.Combine(folder, url))
            Return fileInfo.Directory.FullName.ToLower().StartsWith(rootDirectory.FullName.ToLower())
        End Function

        Public Overrides Function CanSetData(ByVal url As String) As Boolean
            ' 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
        End Function

        Public Overrides Function IsValidUrl(ByVal url As String) As Boolean
            ' 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
        End Function

        Public Overrides Function GetData(ByVal url As String) As Byte()
            ' 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(AddressOf Path.GetFileNameWithoutExtension).Contains(url) Then
                    Return File.ReadAllBytes(Path.Combine(reportDirectory, url & FileExtension))
                End If
                If ReportsFactory.Reports.ContainsKey(url) Then
                    Using ms As New MemoryStream()
                        ReportsFactory.Reports(url)().SaveLayoutToXml(ms)
                        Return ms.ToArray()
                    End Using
                End If
            Catch e1 As Exception
                Throw New FaultException(new FaultReason("Could not get report data."), new FaultCode("Server"), "GetData")
            End Try
            Throw New FaultException(New FaultReason(String.Format("Could not find report '{0}'.", url)), New FaultCode("Server"), "GetData")
        End Function

        Public Overrides Function GetUrls() As Dictionary(Of String, String)
            ' 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(AddressOf Path.GetFileNameWithoutExtension).Concat(ReportsFactory.Reports.Select(Function(x) x.Key)).ToDictionary(Function(x) x)
        End Function

        Public Overrides Sub SetData(ByVal report As XtraReport, ByVal url As String)
            ' Saves the specified report to the report storage with the specified name
            ' (saves existing reports only). 
            If Not IsWithinReportsFolder(url, reportDirectory) Then Throw New FaultException(New FaultReason("Invalid report name."), New FaultCode("Server"), "GetData")
            report.SaveLayoutToXml(Path.Combine(reportDirectory, url & FileExtension))
        End Sub

        Public Overrides Function SetNewData(ByVal report As XtraReport, ByVal defaultUrl As String) As String
            ' 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
        End Function
    End Class

Access the ASP.NET Session

If the ASP.NET End-User Report Designer works with a custom report storage, it uses a separate HTTP handler module for open and save operations. This means that the HttpContext.Session and HttpContext.User properties are not available from custom report storage code.

For more information, review the following help topic: Access HttpContext.Session in Services (ASP.NET Web Forms).