Update Database Connections
- 2 minutes to read
You can create a report that obtains data from a sample database, for development purposes, and switches the database connection to the production database, for end-users. To retrieve production data, specify a database connection at runtime and implement a method to update database connections when users open a report.
Implement the IConnectionProviderFactory service:
using DevExpress.DataAccess.Web; using DevExpress.DataAccess.Wizard.Services; // ... public class MyConnectionProviderFactory : IConnectionProviderFactory { public IConnectionProviderService Create() { return new MyConnectionProviderService(); } }
The service returns an instance of the IConnectionProviderService that supplies connections.
Implement the IConnectionProviderService class:
using DevExpress.DataAccess.ConnectionParameters; using DevExpress.DataAccess.Sql; using DevExpress.DataAccess.Wizard.Services; using System.Collections.Generic; // ... public class MyConnectionProviderService : IConnectionProviderService { public SqlDataConnection LoadConnection(string connectionName) { switch (connectionName) { case ("NWindConnectionString"): return new SqlDataConnection("NWindConnectionString", new MsSqlConnectionParameters() { AuthorizationType = MsSqlAuthorizationType.Windows, DatabaseName = "Northwind", ServerName = "localhost" }); default: throw new KeyNotFoundException($"Connection string '{connectionName}' not found."); } } }
When the Document Viewer or Report Designer Preview loads a report, it calls the IConnectionProviderService.LoadConnection method and allows you to return a connection with the specified name stored in a report.
You can use various DataConnectionParametersBase descendants to establish a connection to different DBMS and data files in different formats, such as:
- MS SQL Server - MsSqlConnectionParameters
- Oracle - OracleConnectionParameters
- XML file - XmlFileConnectionParameters.
To specify a custom connection string, use the CustomStringConnectionParameters instance.
Register the MyConnectionProviderFactory service at application startup before the ASPxWebDocumentViewer.StaticInitialize method: