Skip to main content

Handle Database Connection Dynamically

  • 2 minutes to read

Handle the XPObjectSource object’s events to specify a custom data source connection. This allows you to use a single data layer within your application, or to switch from one connection to another dynamically.

  • ResolveSession
    Raised when the XPObjectSource component creates a Session to retrieve data for a report.

  • DismissSession
    Raised when the XPObjectSource component removes the Session it used to supply data to a report.

Use the XPObjectSource object’s Tag property to identify this object when handling these events.

If you handle the ResolveSession event, the XPObjectSource uses the Session you create in the handler. Otherwise, the XPObjectSource uses the Session that it creates based on the connection the ConnectionString or ConnectionStringName property specify.

This following code demonstrates how to create a Session based on a DataLayer instance and pass it to the XPObjectSource:

using DevExpress.Xpo;
using System.Configuration;

    IDataLayer DataLayerInstance = null;

    private void simpleButton_Click(object sender, EventArgs e) {
        XtraReport1 report = new XtraReport1();

        XPObjectSource dataSource = (XPObjectSource)report.DataSource;
        dataSource.ResolveSession += new EventHandler<ResolveSessionEventArgs>(OnResolveSession);
        dataSource.DismissSession += new EventHandler<ResolveSessionEventArgs>(OnDismissSession);

        // Preview the report
        // WinForms-specific code
        ReportPrintTool printTool = new ReportPrintTool(report);
        printTool.ShowPreviewDialog();        
    }

    private void OnResolveSession(object sender, ResolveSessionEventArgs e) {
        //Create a single IDataLayer instance if it does not exist
        if (DataLayerInstance == null) {
            string connectionString = ConfigurationManager.ConnectionStrings["nwind"].ConnectionString;
            DataLayerInstance = XpoDefault.GetDataLayer(connectionString, DevExpress.Xpo.DB.AutoCreateOption.SchemaAlreadyExists);
        }

        //Create new session based on the DataLayer instance
        e.Session = new UnitOfWork(DataLayerInstance);
    }

    private void OnDismissSession(object sender, ResolveSessionEventArgs e) {
        e.Session.Session.Dispose();
    }