Wednesday, August 31, 2005

Setting Credentials of your Crystal Reports using your ConnectionString


When using Crystal reports with ASP.NET, you'll need to set the credentials for accessing the database because the .rpt file doesn't keep all of the login information (namely the password). You probably already have this info handy in Your Configuration Settings. This is a handy routine (I put mine in Global.asax.cs) to apply the credentials from your "ConnectionString" of your AppSettings to the CrystalDecisions.CrystalReports.Engine.Tables object.

public static void CrystalReportLogin(CrystalDecisions.CrystalReports.Engine.Tables tables) {
CrystalDecisions.Shared.TableLogOnInfo logOnInfo = new CrystalDecisions.Shared.TableLogOnInfo();
foreach( string s in System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"].Split(';')) {
string[] nv = s.Split('=');
switch(nv[0]) {
case "Password": logOnInfo.ConnectionInfo.Password = nv[1]; break;
case "User ID": logOnInfo.ConnectionInfo.UserID = nv[1]; break;
case "Initial Catalog": logOnInfo.ConnectionInfo.DatabaseName = nv[1]; break;
case "Data Source": logOnInfo.ConnectionInfo.ServerName = nv[1]; break;
}
}
foreach( CrystalDecisions.CrystalReports.Engine.Table table in tables)
table.ApplyLogOnInfo(logOnInfo);
}

With this in place, displaying a Crystal Report is as simple as this:

reportDocument1.Load(@"C:\Projects\Reports\CrystalReport1.rpt");
Global.CrystalReportLogin(reportDocument1.Database.Tables);
CrystalReportViewer1.ReportSource = reportDocument1;



<< Home

This page is powered by Blogger. Isn't yours?