Link to home
Start Free TrialLog in
Avatar of ABM Support
ABM Support

asked on

View a Crystal Report via an ASP Web Page

Good Afternoon

I want to view an existing Crystal report from within an ASP web page. I also need to pass a parameter to that Crystal Report.

The .rpt has been included within the application.

I have added both a view and source to my ASP page as below:

<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" Height="1000px" Width="1000px" ReportSourceID="CrystalReportSource1" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server" ></CR:CrystalReportSource>

My code behind is as follows:

Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports CrystalDecisions.Web

Dim CR As New ReportDocument
CR.Load("~/" & ReportID)

Dim crParameterDiscreteValue As ParameterDiscreteValue
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
Dim crParameterFieldLocation As ParameterFieldDefinition
Dim crParameterValues As ParameterValues

crParameterFieldDefinitions = CR.DataDefinition.ParameterFields

crParameterFieldLocation = crParameterFieldDefinitions.Item("SalonID")
crParameterValues = crParameterFieldLocation.CurrentValues
crParameterDiscreteValue = New CrystalDecisions.Shared.ParameterDiscreteValue
crParameterDiscreteValue.Value = 1
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldLocation.ApplyCurrentValues(crParameterValues)

CrystalReportViewer1.ReportSource = CR

The code behind falls over on the highlighted line, the stack trace is a sbelow:

[COMException (0x80041811): Unsupported Operation. A document processed by the JRC engine cannot be opened in the C++ stack.]
CrystalDecisions.ReportAppServer.ClientDoc.ReportClientDocumentClass.Open(Object& DocumentPath, Int32 Options) +0
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.Open(Object& DocumentPath, Int32 Options) +138
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.EnsureDocumentIsOpened() +546

[CrystalReportsException: Load report failed.]
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.EnsureDocumentIsOpened() +647
CrystalDecisions.CrystalReports.Engine.ReportDocument.Load(String filename, OpenReportMethod openMethod, Int16 parentJob) +1800
CrystalDecisions.CrystalReports.Engine.ReportDocument.Load(String filename) +180
Snip_IT.ViewReport.Page_Load(Object sender, EventArgs e) in C:\Snip-IT\Snip-IT\ViewReport.aspx.vb:113
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

Any assistance or pointing in the right direction would be appreciated!

Many thanks

Steve
Avatar of Mike McCracken
Mike McCracken

What does ReportId equal?

There is no highlighted line.  I assume this fails on this line
  CrystalReportViewer1.ReportSource = CR


mlmcc
Avatar of ABM Support

ASKER

Apologies for the long delay and for responding!

You are quite right as to where the application fails!

ReportID is the name of the CrystalReport, ie OrderList.rpt
Are you sure the file exists at the path "~/" & ReportID? Have you tried checking that?
Indeed, its definitely there, see attached
Capture.JPG
But is it accessible on that URL?

Perhaps you need to use server.mappath.

CR.Load(Server.MapPath("~/" & ReportID))
I've changed the code to use Server.MapPath as suggested and the application now doesn't fall over, however the report is not displaying, so we're getting closer!

The report is expecting a parameter so I suspect that might actually be the issue. I'll have a play with that and get back to you.
Right, an update! Below is the code I'm using, this is now generating a 'The report filename was empty' and I have no idea why!

Try
            Dim ReportID As String = Request.QueryString("ReportID")

            Dim CR As New ReportDocument

            CR.Load(Server.MapPath("~/" & ReportID))

            Dim crParameterDiscreteValue As ParameterDiscreteValue
            Dim crParameterFieldDefinitions As ParameterFieldDefinitions
            Dim crParameterFieldLocation As ParameterFieldDefinition
            Dim crParameterValues As ParameterValues

            crParameterFieldDefinitions = CR.DataDefinition.ParameterFields

            crParameterFieldLocation = crParameterFieldDefinitions.Item("SalonID")
            crParameterValues = crParameterFieldLocation.CurrentValues
            crParameterDiscreteValue = New CrystalDecisions.Shared.ParameterDiscreteValue
            crParameterDiscreteValue.Value = DropDownList1.SelectedValue
            crParameterValues.Add(crParameterDiscreteValue)
            crParameterFieldLocation.ApplyCurrentValues(crParameterValues)

            Dim myLogin As CrystalDecisions.Shared.TableLogOnInfo

            Dim myTable As Table

            For Each myTable In CR.Database.Tables
                myLogin = myTable.LogOnInfo
                myLogin.ConnectionInfo.ServerName = "Snip-IT"
                myLogin.ConnectionInfo.DatabaseName = ""
                myLogin.ConnectionInfo.UserID = "sa"
                myLogin.ConnectionInfo.Password = "TVR-Cerbera"
                myTable.ApplyLogOnInfo(myLogin)
                myTable.Location = myTable.Location
            Next

            CrystalReportViewer1.ReportSource = CR
        Catch ex As Exception
            MsgBox("Error" & vbCrLf & ex.Message)
        End Try
Have you stepped through the code and verified that variable values such as reportid are as expected?
ReportID is exactly as it should be
I've also just stepped through the myTable loop and confirmed it is finding the tables within the report and that is all correct also, which suggests that it is the CrystalReportViewer1.ReportSource = CR line that is causing the error but again, no idea why!
If you comment that line out do you get an error?
You won't get a report but it would help pinpoint where the error is.

mlmcc
I do indeed still get that error...the plot thickens!
I've now gone back and commented every line out except the CR.Load and it is that that generates the error!
What do you enter for the report id?

mlmcc
ReportID is c:\Snip-IT\Snip-IT\StockList.rpt

The file has full permissions and does exist in that path
Lets start again! I have recoded as below and it still does not display and there are no errors. I have validated that the dataset contains the right number of records.

This needs to run from a selectedindex change on a dropdownlist as the dropdownlist provides the key to the record selection.

Thanks for all the ideas so far.

Private Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged

        DropDownList1.Enabled = False
        CrystalReportViewer1.Visible = True

        Try
            Dim ReportID As String = Request.QueryString("ReportID")

            Dim CRpt As New ReportDocument
            Dim Path As String = Server.MapPath("~/" & ReportID)

            Dim CTableLogInfo As TableLogOnInfo
            Dim ConnInfo As CrystalDecisions.Shared.ConnectionInfo = New ConnectionInfo()

            ConnInfo.Type = ConnectionInfoType.CRQE
            ConnInfo.ServerName = ServerName
            ConnInfo.DatabaseName = DatabaseName
            ConnInfo.UserID = UserName
            ConnInfo.Password = Password
            ConnInfo.AllowCustomConnection = False
            ConnInfo.IntegratedSecurity = False

            CRpt.Load(Path)

            For Each CTable As Table In CRpt.Database.Tables
                CTable.LogOnInfo.ConnectionInfo = ConnInfo
                CTableLogInfo = CTable.LogOnInfo
                CTableLogInfo.ReportName = CRpt.Name
                CTableLogInfo.TableName = CTable.Name
                CTable.ApplyLogOnInfo(CTableLogInfo)
            Next

            Dim dsStock As DataSet = GetData("select * from stock where SalonID = " & DropDownList1.SelectedValue)

            CRpt.SetDataSource(dsStock)
            CrystalReportViewer1.ReportSource = CRpt
            CrystalReportViewer1.DataBind()
            CrystalReportViewer1.RefreshReport()
        Catch ex As Exception
            MsgBox("Error" & vbCrLf & ex.Message & " " & ex.HResult)
        End Try
       
    End Sub

    Private Function GetData(query As String) As DataSet
        Dim conString As String = ConfigurationManager.ConnectionStrings("SnipITConnectionString").ConnectionString
        Dim cmd As New SqlCommand(query)
        Using con As New SqlConnection(conString)
            Using sda As New SqlDataAdapter()
                cmd.Connection = con

                sda.SelectCommand = cmd
                Using dsCustomers As New DataSet()
                    sda.Fill(dsCustomers, "DataTable1")
                    Return dsCustomers
                End Using
            End Using
        End Using
    End Function
End Class
Why are you connecting to a server as well as setting a dataset as the datasource? It needs to be one of these.
Here is a link to code that works to pass the data to the report from the application

http://www.emoreau.com/Entries/Articles/2006/09/Feeding-Crystal-Reports-from-your-application.aspx

mlmcc
Mimcc

I have replicated from the link you provided and the report is still not displaying! I'm starting to think that it may be due to where I have the code positioned (Dropdownlist_selectedIndexChanged) and maybe the form_load is causing issues!

Any thoughts

Steve
I am not a .Net programmer so I can't comment on the code.

Can you post the code you are now using?

mlmcc
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports CrystalDecisions.Web
Imports System.Data.SqlClient

Public Class ViewReport
    Inherits System.Web.UI.Page
    Public UserName As String = "xx"
    Public ServerName As String = "xxxxxxx"
    Public DatabaseName As String = "Snip-IT"
    Public Password As String = "xxxxxxxxxx"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim labMenu As Label = Master.FindControl("labMenu")
        Dim butMenu1 As Button = Master.FindControl("butMenu1")
        Dim butMenu2 As Button = Master.FindControl("butMenu2")
        Dim butMenu3 As Button = Master.FindControl("butMenu3")
        Dim butMenu4 As Button = Master.FindControl("butMenu4")
        Dim butMenu5 As Button = Master.FindControl("butMenu5")
        Dim butMenu6 As Button = Master.FindControl("butMenu6")
        Dim butMenu7 As Button = Master.FindControl("butMenu7")
        Dim butMaster1 As Button = Master.FindControl("butMaster1")
        Dim butMaster2 As Button = Master.FindControl("butMaster2")
        Dim butMaster3 As Button = Master.FindControl("butMaster3")
        Dim butMaster4 As Button = Master.FindControl("butMaster4")
        Dim butMaster5 As Button = Master.FindControl("butMaster5")
        Dim butMaster6 As Button = Master.FindControl("butMaster6")
        Dim butMaster7 As Button = Master.FindControl("butMaster7")
        Dim butMaster8 As Button = Master.FindControl("butMaster8")
        Dim butMaster9 As Button = Master.FindControl("butMaster9")
        Dim butMaster10 As Button = Master.FindControl("butMaster10")

        labMenu.Text = Trim(Mid(Session("Report"), 3, 99))

        butMenu1.Text = Session("butMenu1")
        butMenu2.Text = Session("butMenu2")
        butMenu3.Text = Session("butMenu3")
        butMenu4.Text = Session("butMenu4")
        butMenu5.Text = Session("butMenu5")
        butMenu6.Text = Session("butMenu6")
        butMenu7.Text = Session("butMenu7")

        Select Case Session("MenuClicked")
            Case "Salon"
                butMenu1.BackColor = Drawing.Color.LightSteelBlue
            Case "Stylist"
                butMenu2.BackColor = Drawing.Color.LightSteelBlue
            Case "Customer"
                butMenu3.BackColor = Drawing.Color.LightSteelBlue
            Case "Parameter"
                butMenu4.BackColor = Drawing.Color.LightSteelBlue
            Case "Reports"
                butMenu6.BackColor = Drawing.Color.LightSteelBlue
        End Select

        butMenu1.Enabled = False
        butMenu2.Enabled = False
        butMenu3.Enabled = False
        butMenu4.Enabled = False
        butMenu5.Enabled = False
        butMenu6.Enabled = False
        butMenu7.Enabled = False

        Me.Master.FindControl("labMenu").Visible = True
        Me.Master.FindControl("butMenu1").Visible = True
        Me.Master.FindControl("butMenu2").Visible = True
        Me.Master.FindControl("butMenu3").Visible = True
        Me.Master.FindControl("butMenu4").Visible = True
        Me.Master.FindControl("butMenu5").Visible = True
        Me.Master.FindControl("butMenu6").Visible = True
        Me.Master.FindControl("butMenu7").Visible = True

        butMaster1.Text = Session("butMaster1")
        butMaster2.Text = Session("butMaster2")
        butMaster3.Text = Session("butMaster3")
        butMaster4.Text = Session("butMaster4")
        butMaster5.Text = Session("butMaster5")
        butMaster6.Text = Session("butMaster6")
        butMaster7.Text = Session("butMaster7")
        butMaster8.Text = Session("butMaster8")
        butMaster9.Text = Session("butMaster9")
        butMaster10.Text = Session("butMaster10")

        Dim ReportNumber As Integer
        Dim ReportSelected As String = Trim(Mid(Session("Report").ToString, 1, 2))
        ReportNumber = ReportSelected
        Session("ReportNumber") = ReportNumber

        Select Case ReportSelected
            Case 1
                butMaster1.BackColor = Drawing.Color.LightSteelBlue
            Case 2
                butMaster2.BackColor = Drawing.Color.LightSteelBlue
            Case 3
                butMaster3.BackColor = Drawing.Color.LightSteelBlue
            Case 4
                butMaster4.BackColor = Drawing.Color.LightSteelBlue
            Case 5
                butMaster5.BackColor = Drawing.Color.LightSteelBlue
            Case 6
                butMaster6.BackColor = Drawing.Color.LightSteelBlue
            Case 7
                butMaster7.BackColor = Drawing.Color.LightSteelBlue
            Case 8
                butMaster8.BackColor = Drawing.Color.LightSteelBlue
            Case 9
                butMaster9.BackColor = Drawing.Color.LightSteelBlue
            Case 10
                butMaster10.BackColor = Drawing.Color.LightSteelBlue
        End Select

        butMaster1.Enabled = False
        butMaster2.Enabled = False
        butMaster3.Enabled = False
        butMaster4.Enabled = False
        butMaster5.Enabled = False
        butMaster6.Enabled = False
        butMaster7.Enabled = False
        butMaster8.Enabled = False
        butMaster9.Enabled = False
        butMaster10.Enabled = False

        Me.Master.FindControl("butMaster1").Visible = True
        Me.Master.FindControl("butMaster2").Visible = True
        Me.Master.FindControl("butMaster3").Visible = True
        Me.Master.FindControl("butMaster4").Visible = True
        Me.Master.FindControl("butMaster5").Visible = True
        Me.Master.FindControl("butMaster6").Visible = True
        Me.Master.FindControl("butMaster7").Visible = True
        Me.Master.FindControl("butMaster8").Visible = True
        Me.Master.FindControl("butMaster9").Visible = True
        Me.Master.FindControl("butMaster10").Visible = True

        If Not (IsPostBack) Then
            Populate_DropdownList1()
        End If

    End Sub

    Private Sub butCancel_Click(sender As Object, e As EventArgs) Handles butCancel.Click
        Response.Redirect("~/default.aspx", False)
    End Sub

    Public Sub Populate_DropdownList1()

        Select Case Session("ReportNumber")
            Case 1

                Label1.Text = "Trading Name"

                Dim constr As String = ConfigurationManager.ConnectionStrings("SnipITConnectionString").ConnectionString
                Dim cmd As New SqlCommand("Select * from [Salon]", New SqlConnection(constr))
                cmd.Connection.Open()

                Dim ddlValues As SqlDataReader
                ddlValues = cmd.ExecuteReader

                DropDownList1.DataSource = ddlValues
                DropDownList1.DataValueField = "SalonID"
                DropDownList1.DataTextField = "TradingName"
                DropDownList1.DataBind()

                DropDownList1.Items.Insert(0, New ListItem("Select ...", String.Empty))

                cmd.Connection.Close()
                cmd.Connection.Dispose()
        End Select
        
    End Sub
    Private Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged

        DropDownList1.Enabled = False
        CrystalReportViewer1.Visible = True

        Try
            Dim ReportID As String = Request.QueryString("ReportID")

            Dim CRpt As New ReportDocument
            Dim Path As String = Server.MapPath("~/" & ReportID)

            CRpt.Load(Path)

            Dim dsStock As DataSet = GetData("select * from stock where SalonID = " & DropDownList1.SelectedValue)

            Dim recordCount As Integer = 0
            For Each table As DataTable In dsStock.Tables
                recordCount += table.Rows.Count
            Next
            
            CRpt.SetDataSource(dsStock)

            CRpt.SetParameterValue("SalonID", DropDownList1.SelectedValue)
            CrystalReportViewer1.ReportSource = CRpt
            CrystalReportViewer1.DataBind()
            CrystalReportViewer1.RefreshReport()
        Catch ex As Exception
            MsgBox("Error" & vbCrLf & ex.Message & " " & ex.HResult)
        End Try
        
    End Sub

    Private Function GetData(query As String) As DataSet
        Dim conString As String = ConfigurationManager.ConnectionStrings("SnipITConnectionString").ConnectionString
        Dim cmd As New SqlCommand(query)
        Using con As New SqlConnection(conString)
            Using sda As New SqlDataAdapter()
                cmd.Connection = con

                sda.SelectCommand = cmd
                Using dsCustomers As New DataSet()
                    sda.Fill(dsCustomers, "DataTable1")
                    Return dsCustomers
                End Using
            End Using
        End Using
    End Function
End Class

Open in new window

Are you getting a error? Have you tried setting the viewer to be visible all the time?
CodeCruiser

I set the control to always be visible and commented line 174 out and the only visible change is that the dropdownlist is now not disabled, as set in line 173!

With the control visibility set to true or false, there are no errors displayed!

cheers

Steve
Do you see viewer toolbar or any other part of it?
Nope, absolutely nothing to suggest a Crystal Report is running!
WHen you run the application, what do you see?
DO you get the dropdown list?

What actions do you take that should cause a report to run?

Your code seems to be just the class definition and not the code that the application is running when you choose a report.

mlmcc
Mimcc

When I run the application, I get the dropdownlist and I make my selection and the dropdownlist is then disabled which suggests that it is going through the SelectIndexChanged.

The value from the dropdown is used to create the dataset and pass the parameter to the report.

Cheers

Steve
Does it work if you move the code, that populates the dataset and passes to report, to the page load using a hard coded report name?
It makes no difference! I just tried a further test, inserting messages at lines 177 and 196 and it appears to be going through the process fine, just not loading the viewer / report!
Can you show us your current markup?
I hope this is what you mean! Also, just out of interest, I have to create a scheduled job that runs these reports, creates PDF output and Emails....I have this working so I think it's definitely something to do with the fact that it's web pages / Page_Load / Post-Back

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="ViewReport.aspx.vb" Inherits="Snip_IT.ViewReport"  MasterPageFile="~/Snip-IT.Master" %>

<%@ Register Assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %>

<asp:Content ID="pageContent" ContentPlaceHolderID="contentPageContent" Runat="Server">
   
    <div style="height: 500px">
        <br><br />
        <asp:Label ID="Label1" runat="server" Text="" Font-Size="Medium" Width="180px"></asp:Label>
        <asp:DropDownList ID="DropDownList1" runat="server" cssClass="textcurves" Font-Size="Medium" AutoPostBack="True">
        </asp:DropDownList>
        <br />
        <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" Height="1000px" Width="1000px" Visible="False" ViewStateMode="Inherit" />
       
    </div>
        <asp:Button ID="butCancel" runat="server" Text="Cancel" cssClass="button" Font-Size="Medium" />
        <br><br />
 </asp:Content>
SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
CodeCruiser

Changing the Visible = True appears to stop the SelectedIndexChanged from running so I put it back to false and just reduced the height and width by half, but still with no effect!

confused.com
But have you tried setting the visible = true and then loading a hardcoded report on page load instead of through dropdownlist?
I have now and that still doesn't display a report or an error! The code from the page_load  is as below:

Try
             Dim CRpt As New ReportDocument
             Dim Path As String = Dim Path As String = "c:\Snip-IT\Snip-IT\Reports\StockList.rpt"

            CRpt.Load(Path)

            Dim dsStock As DataSet = GetData("select * from stock where SalonID = 1")

            Dim recordCount As Integer = 0
            For Each table As DataTable In dsStock.Tables
                recordCount += table.Rows.Count
            Next

            CRpt.SetDataSource(dsStock)
            CRpt.SetDatabaseLogon("xx", "xxxxxxxxx")
            CRpt.SetParameterValue("SalonID", 1)
            CrystalReportViewer1.ReportSource = CRpt
            CrystalReportViewer1.DataBind()
            CrystalReportViewer1.RefreshReport()

        Catch ex As Exception
            MsgBox("Error" & vbCrLf & ex.Message & " " & ex.HResult)
        End Try
You seem to be mixing methods.  You bind a data source to the report then refresh the report which deletes the data you bound

Also if you bind a data source to the report it shouldn't have to use the database so there is no need for a parameter or logon information.

Look at the method in this sample
http://www.emoreau.com/Entries/Articles/2006/09/Feeding-Crystal-Reports-from-your-application.aspx

mlmcc
Hi Mimcc

You posted that link previously and I have also tried following those instructions without success.

I know the report runs as I have created and tested within Crystal Reports itself. I have also created a batch process that runs this report without a viewer, refreshes it and Emails the subsequent PDF, which is what makes this all the more confusing for me!

Steve
What code are you using the email the report.  The viewing code should be very similar just assigning to the viewer rather than exporting

mlmcc
Hi, that code is exactly as you suggest it should be!

I just tried something different, not sure why I did, but I did get a different response! I test my application through Chrome, so I tried IE and this generated the following error:

Unhandled exception at line 157, column 4 in http://localhost:49482/default.aspx

0x800a1391 - JavaScript runtime error: 'bobj' is undefined

I also note that I have 34 compilation warnings, all based around embedded interop assembly and Crystal! The first warning is as below:

Warning      1      A reference was created to embedded interop assembly 'CRVsPackageLib' because of an indirect reference to that assembly from assembly 'CrystalDecisions.VSDesigner'. Consider changing the 'Embed Interop Types' property on either assembly.      Snip-IT

What do you think?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Mimcc and CodeCruiser

I have finally resolved the issue!!

The initial problem was not showing as the error being generated was not displayed within Chrome but only IE (which I found by chance).

I removed all references to CrystalDescisions from my code, removed the Crystal Report itself and then validated my installation as correct (mimcc, I have version v.13.0.12.1494

I then followed the instructions as per the following link http://scn.sap.com/thread/3476094 and hey presto, the viewer opened and tried to display. there are credential issues to the database etc but I'm sure they are now easily resolved!

Thank you both for your on-going attempts to assist.