Can't Print Landscape from Crystal Reports Viewer XI

Post Author: conrad
CA Forum: General
Product: Crystal Reports Viewer XI, version 12.0.0.r130_v20070725 and
Crystal Reports XI, version 11.0.0.1282
Patches Applied: none
Operating System(s): XP Pro SP2
Database(s):
Error Messages: noneSteps to Reproduce:
Download and install Crystal Reports Viewer XI
Open a Crystal Report that prints landscape.
Save report with data.
Open that report with Crystal Reports Viewer XI.  Report will display landscape.
Click Print..OK
Viewer will attempt to scale output to fit on portrait paper, with varying degrees of success.
Checking the properties of the report from Viewer (File...Report Properties...) shows a "Page Orientation" of "Landscape" and a message "Page Orientation and size defined by the application (no page information set by report author)."
Any ideas on how to get the report to print landscape?  It prints that way from Crystal Reports XI.

Hello Glenda,
as you refer to the legacy technology I recommend to post this query to the [Legacy Application Development SDKs|SAP Crystal Reports - Legacy SDKs; forum.
This forum is dedicated to topics related to legacy SDKs, including the Report Designer Component (RDC), OCX, VCL, and Crystal Reports Print Engine (CRPE).
It is monitored by qualified technicians and you will get a faster response there.
Also, all Legacy Application Development SDKs queries remain in one place and thus can be easily searched in one place.
Thanks a lot,
Falk

Similar Messages

  • How to print directly to Printer from Crystal Report Viewer ?

    Hi All,
    We are integrating our Java Web Application with Crystal report XI, currently using JRC and export to PDF for user to preview and print to local printer.
    Now there is new requirement :
    Some clients is using thin client terminal (no harddisk, only has OS +Browser in ROM), so I cannot install Acrobat Reader for them to preview&print the report.
    So I am looking at  Crystal Report Viewer, the question is : Can I print from Crystal Report Viewer directly to local printer without first converting it to PDF (because I can't have acrobat reader installed) ??
    Thank you very much,
    Krist
    Indonesia

    Hi,
    It can't be achieved through XI.
    JRCXI R2 SDK offers the ability to print the report server side
    using the PrintOutputController using printReport(PrintReportOptions printReportOptions) method.
    Here is the code(for XIR2):
    import="com.crystaldecisions.reports.sdk.*"
    import="com.crystaldecisions.sdk.occa.report.lib.*"
    import="com.crystaldecisions.sdk.occa.report.document.*"
    try {
    final String REPORT_NAME = "Inventory.rpt";
    ReportClientDocument reportClientDoc = new ReportClientDocument();
    reportClientDoc.open(REPORT_NAME, 0);
    //Create and set print options.
    PrintReportOptions printOptions = new PrintReportOptions();
    //Note: Printer with the 'printer name' below must already be configured.
    printOptions.setPrinterName("
    10.10.45.220
    BOBJ 2C");
    printOptions.setJobTitle("Sample Print Job from JRC.");
    printOptions.setPrinterDuplex(PrinterDuplex.horizontal);
    printOptions.setPaperSource(PaperSource.auto);
    printOptions.setPaperSize(PaperSize.paperLetter);
    printOptions.setNumberOfCopies(1);
    printOptions.setCollated(false);
    PrintReportOptions.PageRange printPageRange = new PrintReportOptions.PageRange(1,1);
    printOptions.addPrinterPageRange(printPageRange);
    //NOTE: If parameters or database login credentials are required, they need to be set before.
    //calling the printReport() method of the PrintOutputController.
    reportClientDoc.getPrintOutputController().printReport(printOptions);
    reportClientDoc.close();
    out.println("Successfully sent report to the printer.");
    catch(ReportSDKException ex) {     
         out.println(ex);
    Please revert in case you have any query.
    Thanks,
    Neeraj

  • Printing from Crystal Reports Viewer

    I have an issue with a customer demanding to print Post Script from Crystal Report Viewer.  When we print using the PS driver we get the form, but the data is blank.  If we use PCL the report prints fine.  Is there any recommendations for using PCL or PS.  Customer says that Crystal reports are Post Script driven and the PS driver should work.  Any help with this would be appreciated.

    Thank you Mariellen for posting the solution.
    Also note that we have only tested the Zebra Printer with the Zebra Print Drivers. I worked with their developers and they said all drivers use the same under laying code so they should all work.
    The other requirement is you must define your paper size in the driver config tool for each size you are going to use, have a separate Printer defined on your PC.
    Thank you
    Don

  • Error With Export/Print from Crystal Report Viewer

    Hello there,
    I've searched through the web and SAP discussion boards with not much luck with this issue.
    After working through this for some days now I've decided to look here for help.
    Environment:
    I have created a web Crystal Report viewer application(Developed with SBOP BI Platform 4.0 SP06 .NET SDK Runtime) that communicates with a managed Cyrstal Server 2011 SP4 (Product 14.0)
    I am able to connect and authenticate with the server, retrieve a token for communication and display reports in the Crystal report Viewer successfully.
    Problem:
    When I attempt to export, I receive the prompt to select format and pages.
    When I click export after selections most times I receive an error with the text
    Unable to cast COM object of type 'System.__ComObject' to interface type 'CrystalDecisions.ReportAppServer.DataDefModel.PropertyBag'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{74EEBC42-6C5D-11D3-9172-00902741EE7C}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
    Other times the page simply refreshes on export.
    When I click to print, no print dialog is displayed the page always refreshes and no error is displayed.
    No Print or Export document is ever created.
    As many print/export issues seems to be related, I'm guessing this two issues are as well.
    Notes:
    I am utilizing the ReportClientDocument model
    I am storing this in session to use as the crystal report viewer report source on postbacks
    I am assigning a subset of export formats to the crystal report viewer
    I am setting particular parameters as well on the report source
    At this point I would appreciate every assistance I may receive on this issue
    Thanks in advance,
    Below is the pertinent code
    Code:
    <aspx>
       <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"
       AutoDataBind="true" EnableDatabaseLogonPrompt="False"
       BestFitPage="False" ReuseParameterValuesOnRefresh="True"
      CssClass="reportFrame" Height="1000px" Width="1100px" EnableDrillDown="False"
      ToolPanelView="None" PrintMode="Pdf"/>
    <Codebehind>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using CrystalDecisions.Enterprise;
    using CrystalDecisions.ReportAppServer.ClientDoc;
    using CrystalDecisions.ReportAppServer.CommonObjectModel;
    using CrystalDecisions.ReportAppServer.Controllers;
    using CrystalDecisions.ReportAppServer.DataDefModel;
    using CrystalDecisions.ReportAppServer.ReportDefModel;
    using CrystalDecisions.Shared;
    namespace ClassicInternalReportPage
        public partial class Reports : System.Web.UI.Page
            protected override void OnInit(EventArgs e)
                base.OnInit(e);
                if (!String.IsNullOrEmpty(Convert.ToString(Session["LogonToken"])) && !IsPostBack)
                    SessionMgr sessionMgr = new SessionMgr();
                    EnterpriseSession enterpriseSession = sessionMgr.LogonWithToken(Session["LogonToken"].ToString());
                    EnterpriseService reportService = enterpriseSession.GetService("RASReportFactory");
                    InfoStore infoStore = new InfoStore(enterpriseSession.GetService("InfoStore"));
                    if (reportService != null)
                        string queryString = String.Format("Select SI_ID, SI_NAME, SI_PARENTID From CI_INFOOBJECTS "
                           + "Where SI_PROGID='CrystalEnterprise.Report' "
                           + "And SI_ID = {0} "
                           + "And SI_INSTANCE = 0", Request.QueryString["rId"]);
                        InfoObjects infoObjects = infoStore.Query(queryString);
                        ReportAppFactory reportFactory = (ReportAppFactory)reportService.Interface;
                        if (infoObjects != null && infoObjects.Count > 0)
                            ISCDReportClientDocument reportSource = reportFactory.OpenDocument(infoObjects[1].ID, 0);
                            Session["ReportClDocument"] = AssignReportParameters(reportSource) ? reportSource : null;
                            CrystalReportViewer1.ReportSource = Session["ReportClDocument"];
                            CrystalReportViewer1.DataBind();
                //Viewer options
                // Don't enable prompting for Live and Custom
                CrystalReportViewer1.EnableParameterPrompt = !(Request.QueryString["t"] == "1" || Request.QueryString["t"] == "4");
                CrystalReportViewer1.HasToggleParameterPanelButton = CrystalReportViewer1.EnableParameterPrompt;
                CrystalReportViewer1.AllowedExportFormats = (int)(ViewerExportFormats.PdfFormat | ViewerExportFormats.ExcelFormat | ViewerExportFormats.XLSXFormat | ViewerExportFormats.CsvFormat);
            protected void Page_Load(object sender, EventArgs e)
                if (IsPostBack && CrystalReportViewer1.ReportSource == null)
                    CrystalReportViewer1.ReportSource = Session["ReportClDocument"];
                    CrystalReportViewer1.DataBind();
            private bool AssignReportParameters(ISCDReportClientDocument reportSource)
                bool success = true;
                if (Request.QueryString["t"] == "1" || Request.QueryString["t"] == "2" || Request.QueryString["t"] == "4" )
                    reportSource.DataDefController.ParameterFieldController.SetCurrentValue("", "STORE", Session["storeParam"]);
                    if (Request.QueryString["t"] == "2")
                        reportSource.DataDefController.ParameterFieldController.SetCurrentValue("", "FromDate", Request.QueryString["fromdate"]);
                        reportSource.DataDefController.ParameterFieldController.SetCurrentValue("", "ToDate", Request.QueryString["todate"]);
                else if (Request.QueryString["t"] == "3")
                    reportSource.DataDefController.ParameterFieldController.SetCurrentValue("", "SKU", Request.QueryString["sku"]);
                else
                    //Unknown report type alert
                    success = false;
                return success;

    Thanks Don for your response,
    I'm new to the SCN spaces and my content has been moved a couple of times already.
    In response to your questions
    The runtime is installed on the web application server, if by that you mean the machine hosting the created .NET SDK application.
    My question was whether it was also required on the Crystal Server 2011 (I.E. the main enterprise server with CMS and Report management and I guess RAS and all that). I figured this would remain untouched and queries would simply be made against it to retrieve/view reports e.t.c
    If install of the SDK on Crystal Server 2011 is indeed required should I expect any interruption to any of the core services after a restart. I.E. I'm hoping that none of the SDK objects would interfere with the existing server objects (in SAP Business Objects)Reason I ask is I note that much of the SDK install directories are similar to the existing Crystal Enterprise Server 2011 (Product 14.0.0)
    Is this temp folder to be manually created/configured or is it created by the application automatically to perform tasks. Or are you referring to the default C:\Windows\Temp directory and so saying that the application would try to use this for print and export tasks?Once I'm sure which I'd give the app pool user permission
    Printing is to be client side but I figured by default (with the Crystal Report Viewer) it would simply pool and print from the user's printer. This is how it works with the previously used URL reporting approach (viewrpt.cwr). Therefore a user can print the document from wherever they are with their own printer.We don't intend on printing from the server machine, but are you suggesting that a printer must be installed on server (which one web or enterprise server) for any client side printing to work.
    App pool is running in 32 bit mode
    Initially didn't get anything useful from fiddler but I'd try and look closer on your suggestion.
    It's also possible that some of my questions are a misunderstanding of APP vs RAS vs WEB, so please feel free to clarify. Currently I see the Web server as simply the created .NET SDK Application and RAS (Crystal Server 2011 e.t.c) as the existing fully established Application server which I simply pool for information.
    Thank you for your patience and advice,

  • Printing from Crystal Report Viewer in Powerbuilder

    I have a Crystal Report Viewer Control placed on a Powerbuilder window. I have my own Print button placed on the window. The code I have in the clicked event of this button is as follows
    g_ole_crx_report.PrintOut(True,1,False)
    This code displays a Print dialog box where I can select the printer.
    I want to implement a functionality which checks whether the printing was successful . If it was successful I want to update a table in the DB else do not update.If I click Cancel on the Print dialog the DB table should not be updated.
    Is it possible to implement such functionality?
    I am using CR XI RDC with Powerbuilder 9.0.
    Thanks,

    Only option I can think of, is to create your own printer dialog and capture the cancel print event there.
    You will not be able to get at the print cancel event of the printer dialog displayed by the CR viewer print button.
    Ludek

  • Can't Print preview draft crystal report.

    Print preview draft crystal report.
    Error message:
    One or more fields could not be found in the result set.
    Use verify database to update the report. Error in file POR20009. Rowset column could not be found.
    It occurs when trying to print (or preview) a DRAFT document with the report being a Crystal report.  No problems when the document is NOT a draft.  This happens on both SAP 8.8 PL16 and PL17.
    Updating the report and saving it again (as suggested by the error message) does not fix the problem.
    The DRAFT or u201CNORMALu201D document type uses the same Crystal report.   Something seems to be different when passing parameters from a Draft report?
    I can preview DRAFTS and NORMAL reports from the Crystal Editoru2019s preview pane.  This is only happening when launching from within SAP.
    Is this a bug?

    Hi Maeve,
    Can you please help by posting what exactly was the solution to this issue?
    Thanks in advance.
    Regards,
    Sanil

  • InfoView not defaulting print settings from Crystal Reports XI

    I have a form/report created from Crystal Reports XI published to InfoView that has the print settings set for the manual tray when printed. When running the report in InfoView, it does not default to the manual tray when printing. I am publishing directly from Crystal Reports. I have the Process/Print Setup 'Set layout to: Report file default' and the Schedule/Format 'Use options saved with report' checkbox checked. I am not finding any other settings to tell InfoView to use the report page layout/printer settings. Anyone know of any other options I should check? Thanks!
    Edited by: Kelley Freelove on Oct 22, 2009 3:09 PM

    That would be the correct forum as this one is for SDK issues only.
    If you are not getting helped on the other BO forum you may want to consider creating a case if you have a valid support contract.
    Jason

  • Cannot Send Email from Crystal Reports Viewer; MAPI:Overflow

    I am trying to send a report via email with crystal reports, but i get the following error message:
    "The following unexpected error occured while trying to send the report to MAPI: Overflow."
    I am using Outlook 2010, Win 7 x64 bit.
    Does anyone have any ideas or thoughts?

    Yes, it is a 3rd party app that opens Crystal Reports Viewer.  Attached are the screen shots I get when try to send the report as an email.
    -Dan

  • Remove Printer Name from Crystal Report

    How can i remove the printer name from the Crystal Report so that the PrinterName property of the CRAXDRT.Report object in the RDC SDK is blank WITHOUT having the "No Printer" Option checkbox checked?
    Here's the scenerio.  When I first create a Report and don't go into Page Setup, PrinterName property is blank.  If I go into Page Setup and explicitly select a printer, PrinterName property equals the name of the printer selected.  If I check the "No Printer" checkbox in Page Setup, PrinterName property is blank.  But if i go back in and uncheck the "No Printer" checkbox in Page Setup, the PrinterName property equals the name of my Windows Default Printer.

    I'm still not sure what is unclear about my first question.  And I'm not sure how any of the info you are requesting is going to make any difference in answering my question.  And I'm not sure how your analogy fits here but ..
    Version of CR = 11.0.0.895
    CR Service Packs applied = None
    Web or Win app? = Win App
    OS? = Windows XP Service Pack 3
    Development language?  = Both Visual Basic 6 and C#.Net 2008
    Method of CR files deployment = email the .RPT file to a client
    Where were the runtime files downloaded from? = Runtimes are installed from Merge Modules donwload from SAP site
    What is the version of the craxdrt.dll on the deployed box? = 11.0.0.893
    So here are the exact steps so you can understand what is going on:
    I have the Crystal Reports Application open side-by-side with my Visual Basic development environment in debug mode so i can step through the code using the RDC SDK.
    1. I open the Crystal Reports Application and create a brand new report - "Test.RPT" and DO NOT go into Page Setup at all and save the report.
    2. In my Visual Basic development environment, i run the code that will generate the report, Here's the exact code
        Dim m_crApp As CRAXDRT.Application
        Dim m_crReport As CRAXDRT.Report
        Set m_crApp = New CRAXDRT.Application
        Set m_crReport = New CRAXDRT.Report
        Set m_crReport = m_crApp.OpenReport("Test.RPT")
    3. When i look at the PrinterName property in the CRAXDRT.Report object, it is blank.
        ie. crReport.PrinterName is equal to ""
    4. I reopen the Crystal Reports Application with report "Test.RPT" and go into Page Setup and check the "No Printer" option.
    5. I go back into my Visual Basic development environment and rerun the code that will generate the report.
    6. When i look at the PrinterName property in the CRAXDRT.Report object, it is still blank.
        ie.  crReport.PrinterName is equal to ""
    7. I reopen the Crystal Reports Application with report "Test.RPT" and go into Page Setup and uncheck the "No Printer" option. I have NOT specified any printer, nor have i clicked the "Printer..." button to setup a printer....i have just unchecked the "No Printer" option
    8. I go back into my Visual Basic development environment and rerun the code that will generate the report.
    9. When i look at the PrinterName property in the CRAXDRT.Report object, it is now set to my WINDOWS DEFAULT PRINTER, yet i had not specified any printer.
        ie.  crReport.PrinterName is equal to "
    MyNetwork\MyPrinter"
    PROBLEMS:
    1. The client needs the report to go to the default windows printer of their machine
    2. If the "No Printer" Option is checked, the Report does not print at all
    3. If the report is set to MY default windows printer and i give it to the client, at times it takes upwards of to a minute for the Print Dialog to disply.  As i've read on other forum posts, it appears Crystal is looking for MY printer on the clients machine and takes a minute before i realizes it can't find it and then sets it to the CLIENTS default windows printer.
    4. The client believes it is unreasonable to wait a minute for the print dialog to appear ...and i agree.
    5. I cannot change the code to use the Select Printer in the RDC SDK - it's a long explanation why but just suffice it to say that i cannot do this.
    All i want to do is either:
    1. Remove the Printer Name in the actual report from the Crystal Reports designer - basically undoing what Crystal did when i went into Page Setup.
    2. Via the RDC SDK, be able to detect the "No Printer" option is selected. Checkign CRAXDRT.PrinterName equal to "" is not an option.

  • Cannot export crystal report in excel format from crystal report viewer

    This problem occurs on only one workstation.
    Open Advanced Reports > Enter workorder # > Click on 'workorder work(uninvoiced)' > Work order opens.
    Click on icon "Export report"
    Save as type: change to .xls
    Error: Crystal Report Windows Forms Viewer. Error in file
    SAP.......rpt:
    Error detected by export DLL:
    Export failed.

    Try adding c:\Program Files\Business Objects\BusinessObjects Enterprise 12.0\win32_x86 to your windows enviroment variable PATH then restart.

  • Get entire record from Crystal report viewer

    Hi,
    I'm using Crystal 2008 .Net components to view reports from within an application.
    I would like to write a custom drill down event so that users can link back from a record on the report they are previewing to somewhere else in the application. In order to do this I need access to the whole record's data for the object that they clicked on.
    It's not really much good if I just have the value, name and table of the field they clicked on, since it is probably not a unique value within that table, and therefore I couldn't drill back to the specific record they selected. Also, if it's not a database field in the first place then I have no way of going anywhere. But if I can get the whole record they are on then I'll already know which primary key field I want, and I could then get the appropriate value from the record.
    Is this possible?
    Richard

    You can get at specific objects using events,  but not a whole record.
    Can't think of any way of doign this at all...
    Ludek

  • How to display the print dialogbox in crystal reports viewer for visualstudio 2013 in wpf?

    Hi,
    In my wpf application when i click on print button i want to display the print dialog box for current report.
    Here i have written like as follows.
    1.MyCrystalReportsViewer.ViewerCore.ReportSource = reportDocument;
    2. MyCrystalReportsViewer.ViewerCore.PrintReport();
    The above two statements  is executed and displayed the report in CrystalReportViewer, but it doesn't show any print dialogbox.
    MyCrystalReportsViewer is name of the CrystalReportsVIewer control.
    Can any one help me to solve this one using code.

    Hi Sandeep,
    Did you download CR for VS SP 13 from this link?
    http://scn.sap.com/docs/DOC-7824
    First link is to integrate CR into VS.
    If you did then I suggest you do a Repair on both VS and CR for VS.
    Also, VS must be Pro or higher, CR will not work in VS 2013 Express.
    Do you have printers installed? Do not use Windows XPS printer, it has problems.
    Don

  • Dissociate default printer driver from the report viewer

    Hello,
    I have a problem in reports visualization. I set the report paper size via the code:
    _printOptions.PaperSize = CrPaperSizeEnum.crPaperSizePaperCsheet;
    The problem is when i visualize it it's truncated to the printer default paper size. How could i resolve this. I tried the DissociatePrinter option and it didn't help.
    I'm working with .NET RAS SDK and C#.
    Edited by: Rahma Sayari on Feb 20, 2012 9:35 AM
    Edited by: Rahma Sayari on Feb 20, 2012 9:44 AM

    What version of CR?
    What version of .NET?
    WEB or Win app?
    See KB 1386475 and 1490938 (use the search box in the top right corner)
    Also note that the paper size enum may be (most likely will be) different for each printer driver. Thus retrieving the paper size enum and setting that to printOptions.PaperSize may be something worth trying.
    Searching for 'printoutputcontroler' may also get you additional resources.
    Ludek
    Follow us on Twitter http://twitter.com/SAPCRNetSup
    Got Enhancement ideas? Try the [SAP Idea Place|https://ideas.sap.com/community/products_and_solutions/crystalreports]

  • Crystal Report Viewer Session Time out error ( FWM 01002)

    Hi,
    We are using java 1.4 and Teradata base with BO XI 3.0
    I am getting the following error when click on icons (Export, Print, Paging) within Crystal Report Viewer.
    com.crystaldecisions.sdk.occa.report.lib.ReportSDKException: Unable to
    reconnect to the CMS [servername]. The session has been logged off or has expired. (FWM 01002) [RASLIB9038]---- Error code:-2147215357
    Error code name:internal at
    com.crystaldecisions.sdk.occa.report.lib.ReportSDKException.throwReportSDKException(Unknown Source) at
    com.crystaldecisions.sdk.occa.managedreports.ps.internal.f.a(Unknown Source) at com.crystaldecisions.sdk.occa.managedreports.ps.internal.f.getLastPageNumber(Unknown Source) at com.businessobjects.report.web.b.a.do(Unknown Source) at
    com.businessobjects.report.web.event.q.a(Unknown Source) at com.businessobjects.report.web.event.q.a(Unknown Source) at com.businessobjects.report.web.event.k.a(Unknown Source) at com.businessobjects.report.web.event.bt.broadcast(Unknown Source) at com.businessobjects.report.web.event.ak.a(Unknown Source) at com.businessobjects.report.web.a.q.if(Unknown Source) at com.businessobjects.report.web.e.a(Unknown Source) at com.businessobjects.report.web.e.a(Unknown Source) at com.businessobjects.report.web.e.if(Unknown Source) at
    com.crystaldecisions.report.web.viewer.CrystalReportViewerUpdater.a(Unknown Source) at com.crystaldecisions.report.web.ServerControl.processHttpRequest(Unknown Source) at com.crystaldecisions.report.web.viewer.CrystalReportViewerServlet.if(Unknown Source) at com.crystaldecisions.report.web.viewer.CrystalReportViewerServlet.doPost(Unknown Source) at javax.servlet.http.HttpServlet.service(HttpServlet.java:709) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173) at
    org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178) at
    If I let the report sit for 30 minutes or so, the icons will work. The u201Csession
    timeout error messageu201D is kind of misleading. I have updated the JDBC drivers to version 13.0 for Teradata (terajdbc4.jar and tdgssconfig.jar) and did not see improvement.
    Can anyone please help?
    Thanks!
    Edited by: Yingchiu Ou on May 12, 2010 12:42 AM

    I see the viewer, but not the attendant EnterpriseSession nor what the ReportSource is connected to.
    Since the error message explicitly states issues with EnterpriseSession lifetime, it'll be good to give the above info.
    Sincerely,
    Ted Ueda

  • Export from Crystal Reports 2008 viewer fails if run on separate thread

    I have a windows desktop application written in Visual Basic using Visual Studio 2008.  I have installed and am trying Crystal Reports 2008 to run a report.  Everything seems to work well except that when I preview a report (using the viewer control) and click the export button found in the upper left corner of that control, I get the following message:
    Error 5: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made.  Ensure that your Main function has STAThreadAttribute marked on it.  This exception is only raised if a debugger is attached to the process.
    I am a little confused on what to do exactly.  Is the problem because I am running in the Visual Studio 2008 IDE?  It says this exception is only raise if a debugger is attached to the process.  No, I tried running it outside the IDE.  The exception wasn't generated but the application hung when the button was clicked.
    It says the current thread must be set to single thread apartment (STA) mode.  If the report is run on its own thread, is the "current" thread the thread the report is running on or is the main application's UI thread?  I don't think I want to set my main application to single thread apartment mode because it is a multi-threaded application (although I really don't know for sure because I am new to multi-threaded programming). 
    My objective is to allow reports to run asynchronously so that the user can do other things while it is being generated.  Here is the code I use to do this:
        ' Previews the report using a new thread (asynchronously)
        Public Sub PreviewReportAsynch(ByVal sourceDatabase As clsMainApplicationDatabase)
            Dim backgroundProcess As System.ComponentModel.BackgroundWorker
            ' Start a new thread to run this report.
            backgroundProcess = New System.ComponentModel.BackgroundWorker
            Using (backgroundProcess)
                ' Wire the function we want to run to the 'do work' event.
                AddHandler backgroundProcess.DoWork, AddressOf PreviewReportAsynch_Start
                ' Kick off the report asynchronously and return control to the calling process
                backgroundProcess.RunWorkerAsync(sourceDatabase)
            End Using
        End Sub
        Private Sub PreviewReportAsynch_Start(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
            ' The source database needed to call preview report was passed as the only argument
            Call PreviewReport(CType(e.Argument, clsMainApplicationDatabase))
        End Sub
        ' Previews the report.  From the preview window, the user can print it.
        Public Function PreviewReport(ByVal sourceDatabase As clsMainApplicationDatabase) As FunctionEndedResult
            Dim errorBoxTitle As String
            Dim frmPreview As frmReportPreview
            ' Setup error handling
            errorBoxTitle = "Preview " & Name & " Report"
            PreviewReport = FunctionEndedResult.FAILURE
            On Error GoTo PreviewError
            ' Set up the crxReport object
            If InitializeReportProcess(sourceDatabase) <> FunctionEndedResult.SUCCESS Then
                GoTo PreviewExit
            End If
            ' Use the preview form to preview the report
            frmPreview = New frmReportPreview
            frmPreview.Report = crxReport
            frmPreview.ShowDialog()
            ' Save any settings that should persist from one run to the next
            Call SavePersistentSettings()
            ' If we got this far everything is OK.
            PreviewReport = FunctionEndedResult.SUCCESS
    PreviewExit:
            ' Do any cleanup work
            Call CleanupReportProcess(sourceDatabase)
            Exit Function
    PreviewError:
            ' Report error then exit gracefully
            ErrorBox(errorBoxTitle)
            Resume PreviewExit
        End Function
    The variable crxReport is of type ReportDocument and the windows form called 'frmPreview' has only 1 control, the crystal reports viewer. 
    The print button on the viewer works fine.  Just the export button is failing.  Any ideas?

    Hi Trevor.
    Thank you for the reply.  The report document is create on the main UI thread of my application.  The preview form is created and destroyed on the separate thread.  For reasons I won't get into, restructuring the code to move all the initialization stuff inside the preview form is not an option (OK, if you a really curious, I don't always preview a report, sometimes I print and/or export it directly which means the preview form isn't used).
    What I learned through some other research is that there are some things (like COM calls and evidently some OLE automation stuff) that cannot be run on a thread that uses the MTA threading model.   The export button probably uses some of this technology, thus the message stating that an STA threading model is required.  I restructured the code as follows to accomodate this requirement.  Here is a sample:
    ' Previews the report using a new thread (asynchronously)
        Public Sub PreviewReportAsynch(ByVal sourceDatabase As clsMainApplicationDatabase)
            Dim staThread As System.Threading.Thread
            ' Start the preview report function on a new thread
            staThread = New System.Threading.Thread(AddressOf PreviewReportAsynchStep1)
            staThread.SetApartmentState(System.Threading.ApartmentState.MTA)
            staThread.Start(sourceDatabase)
        End Sub
        Private Sub PreviewReportAsynchStep1(ByVal sourceDatabase As Object)
            Dim staThread As System.Threading.Thread
            ' Initialize report preview.  This includes staging any data and configuring the
            ' crystal report document object for use by the crystal report viewer control.
            If InitializeReportProcess(DirectCast(sourceDatabase, clsMainApplicationDatabase)) = FunctionEndedResult.SUCCESS Then
                ' Show the report to the user.  This must be done on an STA thread so we will
                ' start another of that type.  See description of PreviewReportAsynchStep2()
                staThread = New System.Threading.Thread(AddressOf PreviewReportAsynchStep2)
                staThread.SetApartmentState(System.Threading.ApartmentState.STA)
                staThread.Start(mcrxReport)
                ' Wait for step 2 to finish.  This blocks the current thread, but this thread
                ' isn't the main UI thread and this thread has no UI anymore (the progress
                ' form was closed) so it won't matter that is it blocked.
                staThread.Join()
                ' Save any settings that should persist from one successful run to the next
                Call SavePersistentSettings()
            End If
            ' Release the crystal report
            Call CleanupReportProcess(DirectCast(sourceDatabase, clsMainApplicationDatabase))
        End Sub
        ' The preview form must be launched on a thread that use the single-threaded apartment (STA) model.
        ' Threads use the multi-threaded apartment (MTA) model by default.  This is necessary to make the
        ' export and print buttons on the preview form work.  They do not work when running on a
        ' thread using MTA.
        Public Sub PreviewReportAsynchStep2(ByVal crxInitializedReport As Object)
            Dim frmPreview As frmReportPreview
            ' Use the preview form to preview the report.  The preview form contains the crystal reports viewer control.
            frmPreview = New frmReportPreview
            frmPreview.Report = DirectCast(crxInitializedReport, ReportDocument)
            frmPreview.ShowDialog()
        End Sub
    Thanks for your help!
    Andy

Maybe you are looking for

  • ICal Bug: Disappearing Meetings

    I am posting in the hope that someone else can validate and help me solve a problem I have been having sporadically with iCal. I have done other searches and see that people have complete vanishing calendars but this seems to be a more subtle form of

  • FirmBanking Scenario~

    I try FirmBanking Scenario.... Scenario step : RFC -> xi(BPM) -> File -> Socket -> Bank RFC.response <- xi(BPM) <- File Socket <- Bank Realtime scenario... So, I want Scenario that BPM in wait step. But, Wait Step is 1 minitue. How to Second Paramete

  • Attachment missing in back end for purchase order

    Hi all, We are using SRM 5.0 SP10 extended classic scenario. I have created a shopping cart with attachment. A local purchase order has been successfully created and i can find the attachment in it. When i check in the backend the purchase order does

  • Very Disgruntled

    Hi, Could someone please tell me the correct way to format a media card, earlier this month I posted a new topic relating to the fact I was having trouble formatting a 16Gb sandisk micro card for my new 8310, I was not able to format it due to the di

  • Opening Mainstage in 32 Bit

    I'm trying to rewire Reason 4 to Mainstage 3. Reason is a 32 bit application but I can't find the box in Mainstage to open it in 32 bit so Reason is not automatically entering slave mode. Help!