Skip to main content
A newer version of this page is available. .

Add a Report Storage

  • 11 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/Functions With Storage Without Storage
Save Yes Yes
Save As Yes
Open Yes
New Yes
New via Wizard Yes
Manage Subreports Yes

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:

API Description
ASPxReportDesigner.OpenReport Load 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.
ASPxReportDesigner.SaveReportLayout Fires when end-users invoke the Save command in the End-User Designer. The event contains a ReportLayout parameter that stores the current layout as a byte array.

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:

    Reporting Project Wizard

    Important

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

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

    item-template-devexpress-report-storage-web-application

  • You can click the Report Designer’s smart tag and select Add report storage.

    Html5DocumentzViewer_AddReportStorage

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

public class Global : System.Web.HttpApplication {
    protected void Application_Start(object sender, EventArgs e) {
        // ...
        DevExpress.XtraReports.Web.Extensions.ReportStorageWebExtension.RegisterExtensionGlobal(new CustomReportStorageWebExtension()); 
    }
    // ...
}

Report Storage Examples

  • How to store reports in a Microsoft SQL Server database:

    Note

    The complete sample project is available in the following DevExpress Examples repository on GitHub: How to Integrate Web Report Designer in a Web Application.

    Show code
    using DevExpress.XtraReports.UI;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Linq;
    
    namespace SimpleWebReportCatalog
    {
        public class CustomReportStorageWebExtension : 
            DevExpress.XtraReports.Web.Extensions.ReportStorageWebExtension
        {
            private DataTable reportsTable = new DataTable();
            private SqlDataAdapter reportsTableAdapter;
            string connectionString = "Data Source=localhost;Initial Catalog=Reports;Integrated Security=True";
            public CustomReportStorageWebExtension()
            {
                reportsTableAdapter = 
                    new SqlDataAdapter("Select * from ReportLayout", new SqlConnection(connectionString));
                SqlCommandBuilder builder = new SqlCommandBuilder(reportsTableAdapter);
                reportsTableAdapter.InsertCommand = builder.GetInsertCommand();
                reportsTableAdapter.UpdateCommand = builder.GetUpdateCommand();
                reportsTableAdapter.DeleteCommand = builder.GetDeleteCommand();
                reportsTableAdapter.Fill(reportsTable);
                DataColumn[] keyColumns = new DataColumn[1];
                keyColumns[0] = reportsTable.Columns[0];
                reportsTable.PrimaryKey = keyColumns;
            }
            public override bool CanSetData(string url)
            {
                return true;
            }
            public override byte[] GetData(string url)
            {
                // Get the report data from the storage.
                DataRow row = reportsTable.Rows.Find(int.Parse(url));
                if (row == null) return null;
    
                byte[] reportData = (Byte[])row["LayoutData"];
                return reportData;
            }
            public override Dictionary<string, string> GetUrls()
            {
                reportsTable.Clear();
                reportsTableAdapter.Fill(reportsTable);
                // Get URLs and display names for all reports available in the storage.
                var v = reportsTable.AsEnumerable()
                      .ToDictionary<DataRow, string, string>(dataRow => ((Int32)dataRow["ReportId"]).ToString(),
                                                             dataRow => (string)dataRow["DisplayName"]);
                return v;
            }
            public override bool IsValidUrl(string url)
            {
                return true;
            }
            public override void SetData(XtraReport report, string url)
            {
                // Write a report to the storage under the specified URL.
                DataRow row = reportsTable.Rows.Find(int.Parse(url));
                if (row != null)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        report.SaveLayoutToXml(ms);
                        row["LayoutData"] = ms.GetBuffer();
                    }
                    reportsTableAdapter.Update(reportsTable);
                }
            }
            public override string SetNewData(XtraReport report, string defaultUrl)
            {
                // Save a report to the storage with a new URL. 
                // The defaultUrl parameter is the report name that the user specifies.
                DataRow row = reportsTable.NewRow();
                row["ReportId"] = 0;
                row["DisplayName"] = defaultUrl;
                using (MemoryStream ms = new MemoryStream())
                {
                    report.SaveLayoutToXml(ms);
                    row["LayoutData"] = ms.GetBuffer();
                }
                reportsTable.Rows.Add(row);
                reportsTableAdapter.Update(reportsTable);
                // Refill the dataset to obtain the actual value of the new row's autoincrement key field.
                reportsTable.Clear();
                reportsTableAdapter.Fill(reportsTable);
                return reportsTable.AsEnumerable().
                    FirstOrDefault(x => x["DisplayName"].ToString() == defaultUrl)["ReportId"].ToString();
            }
        }
    }
    
  • How to store reports in a file system:

    Note

    If you’d like to store reports in a file system, please refer to the following help topic for additional information/guidance: Create an ASP.NET Web Forms Application with a Report Designer.

    Show code
    using DevExpress.XtraReports.UI;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.ServiceModel;
    
    namespace DXWebApplication1.Services
    {
        public class ReportStorageWebExtension1 : 
            DevExpress.XtraReports.Web.Extensions.ReportStorageWebExtension
        {
            readonly string reportDirectory;
            const string FileExtension = ".repx";
            public ReportStorageWebExtension1(string reportDirectory) {
                if (!Directory.Exists(reportDirectory)) {
                    Directory.CreateDirectory(reportDirectory);
                }
                this.reportDirectory = reportDirectory;
            }
            public override bool CanSetData(string url) {
                return true;
            }
            public override bool IsValidUrl(string url) {
                return true;
            }
            public override byte[] GetData(string url) {
                // Gets the report layout data stored in a Report Storage by the specified URL. 
                try {
                    if (Directory.EnumerateFiles(reportDirectory).Select(Path.GetFileNameWithoutExtension).Contains(url))
                    {
                        return File.ReadAllBytes(Path.Combine(reportDirectory, url + FileExtension));
                    }
                    if (PredefinedReports.ReportsFactory.Reports.ContainsKey(url))
                    {
                        using (MemoryStream ms = new MemoryStream()) {
                            PredefinedReports.ReportsFactory.Reports[url]().SaveLayoutToXml(ms);
                            return ms.ToArray();
                        }
                    }
                    throw new FaultException(new FaultReason(string.Format("Could not find report '{0}'.", url)), new FaultCode("Server"), "GetData");
                } catch (Exception) {
                    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 report URLs and display names. 
                // This method is called when running the Report Designer, 
                // before the Open Report and Save Report dialogs and after a new report is saved to a storage.
    
                return Directory.GetFiles(reportDirectory, "*" + FileExtension)
                                         .Select(Path.GetFileNameWithoutExtension)
                                         .Concat(PredefinedReports.ReportsFactory.Reports.Select(x => x.Key))
                                         .ToDictionary<string, string>(x => x);
            }
            public override void SetData(XtraReport report, string url) {
                // Saves a report to the Report Storage with the specified URL. 
                report.SaveLayoutToXml(Path.Combine(reportDirectory, url + FileExtension));
            }
            public override string SetNewData(XtraReport report, string defaultUrl) {
                // Stores the report with a new URL. . 
                // Validate and correct the specified URL in the SetNewData method
                // and return the resulting URL that is used to save a report in the storage.
                SetData(report, defaultUrl);
                return defaultUrl;
            }
        }
    }
    

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.

To access values stored in HttpContext/Session, use the technique described in the following help topic: Access HttpContext.Session in Services (ASP.NET Web Forms).