locked
SetDataSource fails in Crystal Reports for Visual Studio 2010 RRS feed

  • Question

  • I am trying to get a simple Crystal Report to work in WPF in Visual Studio 2010.  When I try to set the data source (rpt.SetDataSource((DataTable)ds.Tables[0]);) the application crashes with no trappable exception.  The code I am using to set up the dataset is as follows:

    private MainDataSet GetDataSetFromList(List<MainBvaReportRecord> lst) {

    MainDataSet ds = new MainDataSet();

    MainDataSet.BVA_TEST_DATA_VIEWDataTable dt = (MainDataSet.BVA_TEST_DATA_VIEWDataTable)ds.Tables[0]; 

    foreach (MainBvaReportRecord rcd in lst) DataRow row = dt.NewRow();

    row["HOSPITAL_NAME"] = rcd.HospitalName;

    row["DEPARTMENT_NAME"] = rcd.DepartmentName;

    row["DEPARTMENT_ADDRESS"] = rcd.DepartmentAddress;

    row["DEPARTMENT_DIRECTOR"] = rcd.DepartmentDirector;

    row["DEPARTMENT_PHONE_NUMBER"] = rcd.DepartmentPhoneNumber;

    row["FIRST_NAME"] = rcd.FirstName;

    row["MIDDLE_NAME"] = rcd.MiddleName;

    row["LAST_NAME"] = rcd.LastName;

    dt.Rows.Add(row);

     }

    return ds;

    }

    I call this from the following code in the Window_Loaded event:

    private void Window_Loaded(object sender, RoutedEventArgs e) { 

    ViewerCore view = this.crystalReportsViewer.ViewerCore;

    BVACrystalReport rpt = new BVACrystalReport();

    rpt.SetDatabaseLogon("USERNAME", "password", @"Databasepath", "Database");

    try

    {

    List<MainBvaReportRecord> list = new MainBvaReportRecordDataAccess().SelectList();

    MainDataSet ds = this.GetDataSetFromList(list);

    rpt.SetDataSource((DataTable)ds.BVA_TEST_DATA_VIEW);

    }

    catch (Exception ex)

    MessageBox.Show(ex.Message);

    }

    view.ReportSource = rpt;}

    I have tried various combinations in the call to SetDataSource, but all fail in the same manner.  Can anyone help me with this?

     

    Friday, July 2, 2010 12:55 PM

All replies

  • Hello,

    You are using a DS but then setting the Report log on to the Server directly:

    rpt.SetDatabaseLogon("USERNAME", "password", @"Databasepath", "Database");

    Don't do both, use the rpt.SetDataSource( ds ) method.

    Also, you are using the Beta release, upgrade to Service Pack 1 or above now that it's available.

    http://www.sdn.sap.com/irj/boc/crystalreports-dotnet

    Don


    Don Williams
    • Proposed as answer by SAPDon Tuesday, July 12, 2011 2:46 PM
    Tuesday, July 12, 2011 2:46 PM
  • hello,

     

    i still have difficulty setting datasource to report using rpt.setdatasource(ds)

    i have the latest version.

    Please if anyone can help me with this.

    My function is:

    Public Sub RunReport(ByVal reportFile As String)
          
            Dim rpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument()
            rpt.Load(reportFile)
            Dim crTables As CrystalDecisions.CrystalReports.Engine.Tables

            Dim DS As New DataSet()
            Dim dsa As New DataSet()
            crTables = rpt.Database.Tables
            For Each crTable As CrystalDecisions.CrystalReports.Engine.Table In crTables
                DS = New DataSet

                ''filling my dataset using GetCrystalDataset function

                DS = GetCrystalDataset(crTable.Name)

                  ''need to do some field data changes in dataset

               dsa.Tables.Add(DS.Tables(crTable.Name).Copy)
            Next
          
            rpt.SetDataSource(dsa)''its throws unhandled exception on this line saying Failed to load database information.
                                                 Error in File CrystalReport1 {5412E3E3-5454-41E0-AAF2-A3CA6FC2B47C}.rpt:
                                                     Failed to load database information.(details are mentioed below)

            rpt.Refresh()

            ReportViewer.ViewerCore.ReportSource = rpt

     

    End If

     

     

    Thanks in advance .

     

    P.S

    its runs into series of error

    A first chance exception of type 'CrystalDecisions.CrystalReports.Engine.DataSourceException' occurred in CrystalDecisions.ReportAppServer.DataSetConversion.dll
    Step into: Stepping over non-user code 'MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen'
    Step into: Stepping over non-user code 'MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen'
    Step into: Stepping over non-user code 'MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen'
    Step into: Stepping over non-user code 'System.UnhandledExceptionEventArgs.UnhandledExceptionEventArgs'
    Step into: Stepping over non-user code 'System.Data.ProviderBase.DbConnectionPoolCounters.ExceptionEventHandler'
    Step into: Stepping over non-user code 'System.Transactions.Diagnostics.DiagnosticTrace.UnhandledExceptionHandler'
    System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Unhandled exception</Description><AppDomain>CrystalReportWpfApplication1.vshost.exe</AppDomain><Exception><ExceptionType>CrystalDecisions.CrystalReports.Engine.DataSourceException, CrystalDecisions.Shared, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304</ExceptionType><Message>Failed to load database information.
    Error in File CrystalReport1 {5412E3E3-5454-41E0-AAF2-A3CA6FC2B47C}.rpt:
    Failed to load database information.</Message><StackTrace>   at CrystalDecisions.ReportAppServer.ConvertDotNetToErom.ThrowDotNetException(Exception e)
       at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val, Type type)
       at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSource(DataSet dataSet)
       at CrystalReportWpfApplication1.Window1.RunReport(String reportFile) in C:\Shivangi\CrystalReportWpfApplication1\CrystalReportWpfApplication1\Window1.xaml.vb:line 178
       at CrystalReportWpfApplication1.Window1.Window1_Loaded(Object sender, RoutedEventArgs e) in C:\Shivangi\CrystalReportWpfApplication1\CrystalReportWpfApplication1\Window1.xaml.vb:line 105
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
       at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
       at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
       at MS.Internal.LoadedOrUnloadedOperation.DoWork()
       at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
       at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
       at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
       at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
       at System.Windows.Media.MediaContext.Resize(ICompositionTarget resizedCompositionTarget)
       at System.Windows.Interop.HwndTarget.OnResize()
       at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp;amp; handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp;amp; handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
       at System.Windows.Window.ShowHelper(Object booleanBox)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.DispatcherOperation.InvokeImpl()
       at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.ProcessQueue()
       at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp;amp; handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp;amp; handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&amp;amp; msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at CrystalReportWpfApplication1.Application.Main() in C:\Shivangi\CrystalReportWpfApplication1\CrystalReportWpfApplication1\obj\x86\Debug\Application.g.vb:line 65
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()</StackTrace><ExceptionString>CrystalDecisions.CrystalReports.Engine.DataSourceException: Failed to load database information.
    Error in File CrystalReport1 {5412E3E3-5454-41E0-AAF2-A3CA6FC2B47C}.rpt:
    Failed to load database information. ---&amp;gt; System.Runtime.InteropServices.COMException: Failed to load database information.
    Error in File CrystalReport1 {5412E3E3-5454-41E0-AAF2-A3CA6FC2B47C}.rpt:
    Failed to load database information.
       at CrystalDecisions.ReportAppServer.Controllers.DatabaseControllerClass.ReplaceConnection(Object oldConnection, Object newConnection, Object parameterFields, Object crDBOptionUseDefault)
       at CrystalDecisions.CrystalReports.Engine.Table.SetDataSource(Object val, Type type)
       at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val, Type type)
       --- End of inner exception stack trace ---
       at CrystalDecisions.ReportAppServer.ConvertDotNetToErom.ThrowDotNetException(Exception e)
       at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val, Type type)
       at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSource(DataSet dataSet)
       at CrystalReportWpfApplication1.Window1.RunReport(String reportFile) in C:\Shivangi\CrystalReportWpfApplication1\CrystalReportWpfApplication1\Window1.xaml.vb:line 178
       at CrystalReportWpfApplication1.Window1.Window1_Loaded(Object sender, RoutedEventArgs e) in C:\Shivangi\CrystalReportWpfApplication1\CrystalReportWpfApplication1\Window1.xaml.vb:line 105
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
       at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
       at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
       at MS.Internal.LoadedOrUnloadedOperation.DoWork()
       at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
       at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
       at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
       at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
       at System.Windows.Media.MediaContext.Resize(ICompositionTarget resizedCompositionTarget)
       at System.Windows.Interop.HwndTarget.OnResize()
       at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp;amp; handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp;amp; handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
       at System.Windows.Window.ShowHelper(Object booleanBox)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.DispatcherOperation.InvokeImpl()
       at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.ProcessQueue()
       at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp;amp; handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp;amp; handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&amp;amp; msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at CrystalReportWpfApplication1.Application.Main() in C:\Shivangi\CrystalReportWpfApplication1\CrystalReportWpfApplication1\obj\x86\Debug\Application.g.vb:line 65
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()</ExceptionString><DataItems><Data></Data></DataItems><InnerException><ExceptionType>System.Runtime.InteropServices.COMException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Failed to load database information.
    Error in File CrystalReport1 {5412E3E3-5454-41E0-AAF2-A3CA6FC2B47C}.rpt:
    Failed to load database information.</Message><StackTrace>   at CrystalDecisions.ReportAppServer.Controllers.DatabaseControllerClass.ReplaceConnection(Object oldConnection, Object newConnection, Object parameterFields, Object crDBOptionUseDefault)
       at CrystalDecisions.CrystalReports.Engine.Table.SetDataSource(Object val, Type type)
       at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val, Type type)</StackTrace><ExceptionString>System.Runtime.InteropServices.COMException (0x800002CD): Failed to load database information.
    Error in File CrystalReport1 {5412E3E3-5454-41E0-AAF2-A3CA6FC2B47C}.rpt:
    Failed to load database information.
       at CrystalDecisions.ReportAppServer.Controllers.DatabaseControllerClass.ReplaceConnection(Object oldConnection, Object newConnection, Object parameterFields, Object crDBOptionUseDefault)
       at CrystalDecisions.CrystalReports.Engine.Table.SetDataSource(Object val, Type type)
       at CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val, Type type)</ExceptionString></InnerException></Exception></TraceRecord>

    Wednesday, July 20, 2011 2:30 PM
  • Hello,

    Once again you are using way to much code. You don't .Add the DS, it's already in the report.

    Delete you code:

            For Each crTable As CrystalDecisions.CrystalReports.Engine.Table In crTables
                DS = New DataSet

                ''filling my dataset using GetCrystalDataset function

                DS = GetCrystalDataset(crTable.Name)

                  ''need to do some field data changes in dataset

               dsa.Tables.Add(DS.Tables(crTable.Name).Copy)
            Next

    and replace it with:

    rpt.SetDataSource( DS )

    And DO NOT use more than one table in a data set, this is going to slow the report down considerably. CR will map the fields, if they are removed from the report then it's because the fields do not match what exist in the report.

    Don


    Don Williams
    Wednesday, July 20, 2011 2:47 PM
  • Hello,

     

    Thank you for the immediate reponce , Appreciate it.

    I have 3 tables in my dataset and the loop through that i am using is because there are various reports and various tables , i need to get the table names from the report they are trying to open( they have a dummy database connection with real time names of the table used) and then i create a dataset from the actual database which has the same table names as report , so thats how i know what tables and used and i can fill my dataset with actual data from required database tables.

     So I need loop through to just get the table names, is there other way to get the table names apart from this?

     

    Also i did remove the code you asked me to and just filled the dataset with one table and tried to run it but its still giving me the same error.Even with one table and just rpt.setdatasource throws same error. Any suggestions?

    Can you please help me.

     


    Wednesday, July 20, 2011 3:02 PM

  • Try adding this after your line:

    dsa.Tables.Add(DS.Tables(crTable.Name).Copy)

    ' the next line sets the reports table name to your table name.

    rpt.SetDataSource(dsa, crTable.Name, crTable.Name)

    Don


    Don Williams
    Wednesday, July 20, 2011 3:28 PM
  • Hello ,

     

    It throws an error, it says "Overload resolution fails because no accessible 'SetDatasource' accepts this no of arguments"

    Also you meant it inside the for loop right? just so that we are on the same page.

    Any suggestions please?

     

     

    Wednesday, July 20, 2011 3:45 PM
  • Use Telisense to fill in any missing members.

    So here's what I do, Connect to SQL and fill in 2 tables in a dataset, save it as an XML file and then replace the connection of the report to the XMl. You cna probably remove the XML part. Important part is the table name and aliasing:

     

     

    using System;
    using System.IO;
    using System.Xml;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.Threading;
    using CrystalDecisions.CrystalReports.Engine;
    using CrystalDecisions.Shared;
    using CrystalDecisions.ReportAppServer.ClientDoc;
    using CrystalDecisions.ReportAppServer.Controllers;
    using CrystalDecisions.ReportAppServer.ReportDefModel;
    using CrystalDecisions.ReportAppServer.CommonControls;
    using CrystalDecisions.ReportAppServer.CommLayer;
    using CrystalDecisions.ReportAppServer.CommonObjectModel;
    using CrystalDecisions.ReportAppServer.ObjectFactory;
    using System.Data.OleDb;
    using CrystalDecisions.ReportAppServer.DataSetConversion;
    using CrystalDecisions.ReportAppServer.DataDefModel;
    using CrystalDecisions.ReportSource;
    using CrystalDecisions.Windows.Forms;
    using System.Data.SqlClient;
    using System.Runtime.InteropServices;

    private void SetToXML_Click(object sender, EventArgs e) { CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument(); ISCDReportClientDocument rcd; rcd = rptClientDoc; string connString = "Provider=SQLOLEDB;Data Source=van-w-13-dwilli;Database=xtreme;User ID=sa;Password=pw"; string sqlString = @"SELECT ""Orders"".""Order ID"", ""Orders"".""Order Amount"" FROM ""xtreme"".""dbo"".""Orders"" ""Orders"""; string sqlString2 = @"SELECT ""Orders Detail"".""Order ID"", ""Orders Detail"".""Product ID"", ""Orders Detail"".""Unit Price"", ""Orders Detail"".""Quantity"" FROM ""xtreme"".""dbo"".""Orders Detail"" ""Orders Detail"""; System.Data.OleDb.OleDbConnection oleConn = new System.Data.OleDb.OleDbConnection(connString); System.Data.OleDb.OleDbCommand cmd = oleConn.CreateCommand(); //cmd.Parameters.Add("CustomerID", System.Data.OleDb.OleDbType.Integer); //cmd.Parameters["CustomerID"].Value = 1; cmd.CommandText = sqlString; System.Data.DataSet ds = new System.Data.DataSet(); OleDbDataAdapter oleAdapter = new OleDbDataAdapter(sqlString, oleConn); OleDbDataAdapter oleAdapter2 = new OleDbDataAdapter(sqlString2, oleConn); DataTable dt1 = new DataTable("Orders"); DataTable dt2 = new DataTable("Orders Detail"); oleAdapter.Fill(dt1); oleAdapter2.Fill(dt2); //System.Data.DataSet ds = new System.Data.DataSet(); ds.Tables.Add(dt1); ds.Tables.Add(dt2); ds.WriteXml("c:\\sc.xml", XmlWriteMode.WriteSchema); rpt.SetDataSource(ds); //Create a new Database Table to replace the reports current table. CrystalDecisions.ReportAppServer.DataDefModel.Table boTable = new CrystalDecisions.ReportAppServer.DataDefModel.Table(); //boMainPropertyBag: These hold the attributes of the tables ConnectionInfo object PropertyBag boMainPropertyBag = new PropertyBag(); //boInnerPropertyBag: These hold the attributes for the QE_LogonProperties //In the main property bag (boMainPropertyBag) PropertyBag boInnerPropertyBag = new PropertyBag(); //Set the attributes for the boInnerPropertyBag boInnerPropertyBag.Add("File Path ", @"C:\sc.xml"); boInnerPropertyBag.Add("Internal Connection ID", "{680eee31-a16e-4f48-8efa-8765193dccdd}"); //Set the attributes for the boMainPropertyBag boMainPropertyBag.Add("Database DLL", "crdb_adoplus.dll"); boMainPropertyBag.Add("QE_DatabaseName", ""); boMainPropertyBag.Add("QE_DatabaseType", ""); //Add the QE_LogonProperties we set in the boInnerPropertyBag Object boMainPropertyBag.Add("QE_LogonProperties", boInnerPropertyBag); boMainPropertyBag.Add("QE_ServerDescription", "NewDataSet"); boMainPropertyBag.Add("QE_SQLDB", "False"); boMainPropertyBag.Add("SSO Enabled", "False"); //Create a new ConnectionInfo object CrystalDecisions.ReportAppServer.DataDefModel.ConnectionInfo boConnectionInfo = new CrystalDecisions.ReportAppServer.DataDefModel.ConnectionInfo(); //Pass the database properties to a connection info object boConnectionInfo.Attributes = boMainPropertyBag; //Set the connection kind boConnectionInfo.Kind = CrConnectionInfoKindEnum.crConnectionInfoKindCRQE; //**EDIT** Set the User Name and Password if required. boConnectionInfo.UserName = ""; boConnectionInfo.Password = ""; //Pass the connection information to the table boTable.ConnectionInfo = boConnectionInfo; //Get the Database Tables Collection for your report CrystalDecisions.ReportAppServer.DataDefModel.Tables boTables; boTables = rptClientDoc.DatabaseController.Database.Tables; //For each table in the report: // - Set the Table Name properties. // - Set the table location in the report to use the new modified table boTable.Name = "Orders"; boTable.QualifiedName = "Orders"; boTable.Alias = "Orders"; rptClientDoc.DatabaseController.SetTableLocation(boTables[0], boTable); boTable.Name = "Orders Details"; boTable.QualifiedName = "Orders Details"; boTable.Alias = "Orders_Details"; rptClientDoc.DatabaseController.SetTableLocation(boTables[1], boTable); //Verify the database after adding substituting the new table. //To ensure that the table updates properly when adding Command tables or Stored Procedures. rptClientDoc.VerifyDatabase(); MessageBox.Show("Data Source Set", "RAS", MessageBoxButtons.OK, MessageBoxIcon.Information); }

     

    Thanks

    Don


    Don Williams
    Wednesday, July 20, 2011 5:36 PM
  • hello,

    thanks for the response, but this is way to complex abd different then my scenario,

    what I dont understand is,

    a. you have declared rpt as new reportdocument but not set it to your crystal report and thens you are just setting rpt.setdatasource ( correct me if I am not getting it please)

    also then you use xml doc , my problem id i have to set rpt to my crytal report to get the table names because i dont know what tables are used , then i create a dataset and thens assign to the report .

    Can you please help me and give a sample code similar to what i have send ?

    Thanks

     

     

     

    Thursday, July 21, 2011 1:52 PM
  • Sorry about that. I use a File Open Common Dialog box to open my reports and set it to either ClientDoc or ReportClientDoc for the engine or RAS:

    		private void btnOpenReport_Click(object sender, System.EventArgs e)
    		{
          rptClientDoc = new CrystalDecisions.ReportAppServer.ClientDoc.ReportClientDocument(); // ReportClientDocumentClass();
    
          // this line uses the local PC as the RAS server/services running
          //rptClientDoc.ReportAppServer = "VMDWCR2k8RAS"; //System.Environment.MachineName;
          openFileDialog.Filter = "Crystal Reports (*.rpt)|*.rpt|Crystal Reports Secure (*.rptr)|*.rptr";
          //openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
          openFileDialog.FilterIndex = 1;
    
          //rptClientDoc.MinorVersion();
    
    			if (openFileDialog.ShowDialog() == DialogResult.OK) 
    			{
    				btnOpenReport.Enabled = false;
    				btnSaveRptAs.Enabled = false;
            btnCloserpt.Enabled = false;
    				object rptName = openFileDialog.FileName;
            
            try
            {
              // this one does not use crystalras.exe as a service
              rpt.Load(rptName.ToString(), OpenReportMethod.OpenReportByTempCopy);
              // this one uses RAS
              //rpt.Load(Server.MapPath("" + Request.ApplicationPath) + @"\Reports\ChartComparison.rpt", OpenReportMethod.OpenReportByTempCopy);
              rptClientDoc = rpt.ReportClientDocument;
              btnOpenReport.Enabled = false;
              btnSaveRptAs.Enabled = false;
              ViewReport.Enabled = true;
              btnReportName.Text = rptName.ToString();
              //btnReportName.Text = rptClientDoc.DisplayName.ToString();
            }
            catch (Exception ex)
            {
              MessageBox.Show("ERROR: " + ex.Message);
              btnOpenReport.Enabled = true;
              btnSaveRptAs.Enabled = true;
              ViewReport.Enabled = false;
              return;
            }
            //rpt.Clone();
            rptClientDoc = rpt.ReportClientDocument;
            
            // this one uses the RAS Service
            //rptClientDoc.Open(ref rptName, (int) CdReportClientDocumentOpenOptionsEnum.cdOpenReportRetrieveMinimumReportDocument);
    
            //MessageBox.Show("Report version: " + rptClientDoc.MajorVersion.ToString() + "." + rptClientDoc.MinorVersion.ToString(), "RAS" ,MessageBoxButtons.OK,MessageBoxIcon.Information );
            
    				//MessageBox.Show("Report opened.","RAS",MessageBoxButtons.OK,MessageBoxIcon.Information );
    				btnOpenReport.Enabled = false;
    				btnSaveRptAs.Enabled = true;
            btnCloserpt.Enabled = true;
            //btnSQLString.text = "";
            btnRecordSelectionForm.Text = rpt.RecordSelectionFormula.ToString();
            btnReportVersion.Text = rptClientDoc.MajorVersion.ToString() + "." + rptClientDoc.MinorVersion.ToString();
            
            getPrinterInfoOnOpen(rpt);
          }
    		}


    I did not clean it up for you, it's just my main test app I use to try everything in....

    As for getting the table names you still have to open the report that was built on the data sources. If you did not then no way to get the info. Use RAS to add tables and fields to your report. Lots of other ways around that also, insert a bunch of text objects and simply replace the object with a field object, or update the text etc.

    It's the policy of SAP not to write code for you, if you need help then you can hire SAP Professional Service to help you. All I can do is provide samples that are close to what you need, it's up to you to sort out the details.

    Don


    Don Williams
    Thursday, July 21, 2011 2:41 PM