2

我的网站有问题。

有一个按钮可以打开 Crystal Reports 文件。大多数情况下,它会正确加载,但有时它不会加载任何内容。

我注意到,如果我在主页加载后立即单击按钮并打开报告,它不会加载(即使您尝试刷新或重新加载报告)。如果您等待至少 3 秒钟并按下按钮,则报告会正确加载(通常在我打开报告时工作,不加载,关闭窗口,再次按下按钮,它会正确加载)。

我知道这听起来像一个愚蠢的问题,但任何用户总是报告文件没有打开,并最终放弃使用我的系统。我需要找出如何修复这个问题,我可以从哪里开始?

报告文件 (cs)

ReportDocument oRpt = new ReportDocument();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["idInvoice"] != null)
            {
                Invoices invoice = new Invoices(int.Parse(Session["idInvoice"].ToString()));
                Client client = new Client(invoice.idClient);

                if (invoice.isRestricted || client.restrictInvoiceAccess)
                {
                    ClientScript.RegisterStartupScript(Page.GetType(), "msg", "window.alert('El acceso a este archivo fue restringido (" + Session["idInvoice"].ToString() + ").');window.close();", true);
                    return;
                }

                loadReport(invoice.idClient, invoice.idInvoice);
            }
        }

        private void loadReport(int pi_idClient, int pi_idInvoice)
        {
            bool isCFD = false;
            string originalString = "", signedString = "", approvedYear = "",
                approvedNumber = "", certificateNum = "", series = "", number = "",
                clientName = "", clientDir = "", clientRFC = "", banckReference = string.Empty, 
                payMethod = string.Empty, FourDigitsAccont = string.Empty, regimentTax = string.Empty, 
                companyPhysicalAddress = string.Empty;

            DataTable dt = null;
            dsCorporatives.CCARD_corporatives_spSelectDataTable corporativesDt = null;
            dsCorporatives.dtResultsDataTable dtResults = null;
            //dsCorporatives.dtFiltersDataTable dtFilters = null;
            dsCorporatives.GAS_invoiceConsumptions_spListByIdClientProductPemexDataTable invoiceDt = null;

            try
            {
                string str = ConfigurationManager.AppSettings["logo_path"].ToString();
                string str2 = ConfigurationManager.AppSettings["rfc_path"].ToString();

                base.Server.MapPath("../images");
                string path = Server.MapPath("../" + ConfigurationManager.AppSettings["pathReports"].ToString());

                Client cliente = new Client(pi_idClient);

                if (!string.IsNullOrEmpty(cliente.bankReference))
                {
                    banckReference = cliente.bankReference;
                }

                dt = Invoices.listTableInvoiceConsuptionsByClient(pi_idClient, pi_idInvoice);

                CCARD_corporatives_spSelectTableAdapter corporativesTA = new CCARD_corporatives_spSelectTableAdapter();
                GAS_invoiceConsumptions_spListByIdClientProductPemexTableAdapter invoiceTA = new GAS_invoiceConsumptions_spListByIdClientProductPemexTableAdapter();
                GAS_invoiceConsumptions_spListByIdClient1TableAdapter resultsTA = new GAS_invoiceConsumptions_spListByIdClient1TableAdapter();

                invoiceDt = new dsCorporatives.GAS_invoiceConsumptions_spListByIdClientProductPemexDataTable();
                invoiceTA.Fill(invoiceDt, pi_idClient, pi_idInvoice);

                DataSet1.GAS_invoiceConsumptions_spListByIdClient1DataTable results = new DataSet1.GAS_invoiceConsumptions_spListByIdClient1DataTable();
                resultsTA.Fill(results, pi_idClient, pi_idInvoice);
                double totalInvoice = double.Parse(results.Compute("Sum(total)", "").ToString());
                //Cambio c1 = new Cambio();
                string sAmountText = NumberToText.doubleToText(double.Parse(results.Compute("Sum(total)", "").ToString())); //c1.EnLetras(double.Parse(results.Compute("Sum(total)", "").ToString())).Trim();

                for (int i = 0; i < results.Count; i++)
                {
                    results[i].amountText = sAmountText.ToUpper();
                }

                for (int i = 0; i < results.Count; i++)
                {
                    results[i].amountText = sAmountText.ToUpper();
                }

                Invoices invoice = new Invoices(pi_idInvoice);

                if (invoice.series != "TIJ" && invoice.series != "MXL" && invoice.number != invoice.idInvoice)
                {
                    isCFD = true;
                    series = invoice.series;
                    number = invoice.number.ToString("000000");
                }

                else
                {
                    isCFD = false;
                }

                if (invoiceDt.Rows.Count == 0)
                {
                    Client client = new Client(pi_idClient);
                    dsCorporatives.GAS_invoiceConsumptions_spListByIdClientProductPemexRow row = invoiceDt.NewGAS_invoiceConsumptions_spListByIdClientProductPemexRow();
                    row.CommissionsAmount = (decimal)0.0;
                    row.CommissionsTaxAmount = (decimal)0.0;
                    row.CommissionsValue = (decimal)0.0;
                    row.contact = string.Empty;
                    row.createdDate = invoice.createdDate.Date;
                    row.dateCreated = invoice.createdDate.Date;
                    row.description = string.Empty;
                    row.folio = string.Empty;
                    row.idCard = -1;
                    row.idClient = pi_idClient;
                    row.idConsumption = -1;
                    row.idInvoice = pi_idInvoice;
                    row.idPemex = string.Empty;
                    row.idStation = -1;
                    row.invoiceCreatedDate = invoice.createdDate;
                    row.operation = string.Empty;
                    row.operationType = string.Empty;
                    row.pemexKey = string.Empty;
                    row.price = (decimal)0.0;
                    row.printedDate = invoice.printedDate;
                    row.printNotes = invoice.printNote;
                    row.quantity = 0;
                    row.rfc = client.RFC;
                    row.stationName = string.Empty;
                    row.stationSaleNumber = 0;
                    row.subtotal = 0;
                    row.tax = 0;
                    row.TaxAmount = 0;
                    row.saleNumber = 0;
                    row.total = 0;
                    invoiceDt.AddGAS_invoiceConsumptions_spListByIdClientProductPemexRow(row);
                }

                corporativesDt = new dsCorporatives.CCARD_corporatives_spSelectDataTable();
                corporativesTA.Fill(corporativesDt, cliente.idCorporative);

                Zone companyBillingZone = new Zone(corporativesDt[0].idBillingZone);
                City companyBillingCity = new City(companyBillingZone.idCity);
                State companyBillingState = new State(companyBillingCity.idState);

                string companyBillingAddress = corporativesDt[0].billingStreet + " "
                                + " #" + corporativesDt[0].billingExtNumber
                                + (corporativesDt[0].billingIntNumber.Trim().Length > 0 ? "-" 
                                + corporativesDt[0].billingIntNumber : "")
                                + Environment.NewLine
                                + corporativesDt[0].billingNeighborhood
                                + Environment.NewLine
                                + companyBillingZone.description
                                + ", " + companyBillingState.description
                                + " C.P. " + corporativesDt[0].billingPostalCode;

                Zone companyPhysicalZone = new Zone(corporativesDt[0].idPhysicalZone);
                City companyPhysicalCity = new City(companyPhysicalZone.idCity);
                State companyPhysicalState = new State(companyPhysicalCity.idState);
                //los datos se deben tomar del xml
                /*string companyPhysicalAddress = corporativesDt[0].physicalStreet + " "
                                + " #" + corporativesDt[0].physicalExtNumber
                                + (corporativesDt[0].physicalIntNumber.Trim().Length > 0 ? "-" + corporativesDt[0].physicalIntNumber : "")
                                + Environment.NewLine
                                + corporativesDt[0].physicalNeighborhood
                                + Environment.NewLine
                                + companyPhysicalZone.description
                                + ", " + companyPhysicalState.description
                                + " C.P. " + corporativesDt[0].physicalPostalCode;*/

                dtResults = new dsCorporatives.dtResultsDataTable();
                dsCorporatives.dtResultsRow dRow = dtResults.NewdtResultsRow();

                double dblSubTotal = Convert.ToDouble(dt.Compute("Sum(subtotal)", "").ToString());
                double dblCommissionAmount = Convert.ToDouble(dt.Compute("Sum(CommissionsAmount)", "").ToString());
                double dblSubTotalWithOutidPemex = 0;
                double.TryParse(dt.Compute("Sum(subtotal)", "idPemex is null").ToString(), out dblSubTotalWithOutidPemex);
                double dblCommissionsTaxAmount = Convert.ToDouble(dt.Compute("sum(CommissionsTaxAmount )", "").ToString());
                double dblTotal = Convert.ToDouble(dt.Compute("sum(total)", "").ToString());
                double dblTaxAmountWithOutidPemex = 0;
                double.TryParse(dt.Compute("Sum(TaxAmount)", "idPemex is null").ToString(), out dblTaxAmountWithOutidPemex);
                double dblTotalWithOutidPemex = 0;
                double.TryParse(dt.Compute("Sum(Total)", "idPemex is null").ToString(), out dblTotalWithOutidPemex);
                double dblTaxAmount = Convert.ToDouble(dt.Compute("sum(TaxAmount)", "").ToString());
                double dblSubTotalOnlyProductsIdPemex = 0;
                double.TryParse(dt.Compute("Sum(subtotal)", "idPemex is not null").ToString(), out dblSubTotalOnlyProductsIdPemex);

                dRow.SubTotalReport = dblSubTotal + dblCommissionAmount;
                dRow.CommissionsAmount = dblCommissionAmount;
                dRow.SubTotalWithoutIdPemex = dblSubTotalWithOutidPemex;
                dRow.totalReport = dblCommissionsTaxAmount + dblCommissionAmount + dblTotal;
                dRow.totalCommissionAmount = dblCommissionAmount;
                dRow.totalCommissionTaxAmount = dblCommissionsTaxAmount;
                dRow.totalCommission = dblCommissionAmount + dblCommissionsTaxAmount;
                dRow.taxAmountwithoutIdPemex = dblTaxAmountWithOutidPemex;
                dRow.totalWithOutIdPemex = dblTotalWithOutidPemex;
                dRow.taxAmountReport = dblTaxAmount + dblCommissionsTaxAmount;
                dRow.SubTotalOnlyProductsIdPemex = dblSubTotalOnlyProductsIdPemex;
                dRow.CorporativeImage = this.GetImageData(string.Concat(new object[] { str, corporativesDt.Rows[0]["idCorporative"], "/", corporativesDt.Rows[0]["logo"] }));
                dRow.FiscalImage = this.GetImageData(string.Concat(new object[] { str2, corporativesDt.Rows[0]["idCorporative"], "/", corporativesDt.Rows[0]["imgRFC"] }));

                dtResults.AdddtResultsRow(dRow);

                if (isCFD)
                {
                    path = path + "crStatementOfAccountCFD.rpt";
                    oRpt.Load(path);
                }

                else
                {
                    path = path + "crStatementOfAccount.rpt";
                    oRpt.Load(path);
                }

                ReportDocument oSubRpt1 = oRpt.OpenSubreport("crSubResults");
                oSubRpt1.SetDataSource((DataTable)results);

                oRpt.Database.Tables["CCARD_corporatives_spSelect"].SetDataSource((DataTable)corporativesDt);
                oRpt.Database.Tables["GAS_invoiceConsumptions_spListByIdClientProductPemex"].SetDataSource((DataTable)invoiceDt);
                oRpt.Database.Tables["dtResults"].SetDataSource((DataTable)dtResults);

                ExportOptions exportOpts = new ExportOptions();
                PdfRtfWordFormatOptions pdfopts = ExportOptions.CreatePdfRtfWordFormatOptions();

                exportOpts.ExportFormatType = ExportFormatType.PortableDocFormat;
                exportOpts.ExportFormatOptions = pdfopts;

                if (isCFD)
                {
                    //ElectronicInvoices.getInvoiceData(cliente.idCorporative, invoice.series, invoice.number, invoiceDt[0].invoiceCreatedDate, out originalString, out signedString, out approvedYear, out approvedNumber, out certificateNum);
                    ElectronicInvoices.getInvoiceData(cliente.idCorporative, invoice.series, invoice.number, invoiceDt[0].invoiceCreatedDate, out originalString, out signedString, out approvedYear, out approvedNumber, out certificateNum, out clientName, out clientDir, out clientRFC, out payMethod, out FourDigitsAccont, out regimentTax, out companyPhysicalAddress);

                    int lineLength = 204;
                    int j = originalString.Length / lineLength;

                    for (int i = 0; i < j; i++)
                    {
                        originalString = originalString.Substring(0, (i + 1) * lineLength + i * 2) + Environment.NewLine + originalString.Substring((i + 1) * lineLength + i * 2);
                    }

                    oRpt.SetParameterValue("series", series);
                    oRpt.SetParameterValue("number", number);

                    oRpt.SetParameterValue("clientName", clientName);
                    oRpt.SetParameterValue("clientDir", clientDir);
                    oRpt.SetParameterValue("clientRfc", clientRFC);

                    oRpt.SetParameterValue("originalString", originalString);
                    oRpt.SetParameterValue("signedString", signedString);

                    oRpt.SetParameterValue("approvedYear", approvedYear);
                    oRpt.SetParameterValue("approvedNumber", approvedNumber);
                    oRpt.SetParameterValue("certificateNumber", certificateNum);

                    oRpt.SetParameterValue("companyBillingAddress", companyBillingAddress);
                    oRpt.SetParameterValue("companyPhysicalAddress", companyPhysicalAddress);
                    //BanckReference
                    oRpt.SetParameterValue("banckReference", banckReference);
                    oRpt.SetParameterValue("payMethod", payMethod);
                    oRpt.SetParameterValue("4DigitsAccount", FourDigitsAccont);
                    oRpt.SetParameterValue("regimentTax", regimentTax);
                }

                else
                {
                    oRpt.SetParameterValue("series", invoice.series);

                    oRpt.SetParameterValue("clientName", cliente.tradeName);
                    oRpt.SetParameterValue("clientDir", cliente.fiscalAddress + " " + new Zone(cliente.idZone).description + ", " + new State(new City(new Zone(cliente.idZone).idCity).idState).description);
                    oRpt.SetParameterValue("clientRfc", cliente.RFC);
                }
                //Response.Clear();

                int iAdditionalRows = 0;

                if (results.Count > 2)
                {
                    iAdditionalRows = (results.Count - 2);
                }

                if (invoiceDt[0].printNotes.Length > 45)
                {
                    if (Math.Ceiling((decimal)(invoiceDt[0].printNotes.Length - 45) / 40) > iAdditionalRows)
                    {
                        iAdditionalRows = (int)Math.Ceiling((decimal)(invoiceDt[0].printNotes.Length - 45) / 40);
                    }
                }

                //Se ncesita mover txtContacto para que se "alinea" al bottom
                oRpt.ReportDefinition.Sections[7].ReportObjects["txtComentarios"].Height += iAdditionalRows * 340;
                oRpt.ReportDefinition.Sections[7].ReportObjects["txtContacto"].Top += iAdditionalRows * 340;
                oRpt.ReportDefinition.Sections[7].ReportObjects["txtContacto1"].Top += iAdditionalRows * 340;

                oRpt.ExportToHttpResponse(exportOpts, Response, false, "Exported");
            }

            finally
            {
                try
                {
                    oRpt.Dispose();
                    oRpt.Close();

                    corporativesDt.Dispose();
                    dtResults.Dispose();
                    //dtFilters.Dispose();
                    dt.Dispose();
                    invoiceDt.Dispose();
                }

                catch
                {

                }
            }
        }

        private byte[] GetImageData(string pi_fileName)
        {
            WebClient client = new WebClient();
            System.Drawing.Image imageToConvert = new Bitmap(client.OpenRead(pi_fileName));
            return ConvertImageToByteArray(imageToConvert);
        }

        private static byte[] ConvertImageToByteArray(System.Drawing.Image imageToConvert)
        {
            ImageConverter converter = new ImageConverter();
            converter.ConvertTo(imageToConvert, typeof(byte[]));
            return (byte[])converter.ConvertTo(imageToConvert, typeof(byte[]));
        }

主页

ASPX

<%@ Page Language="c#" CodeFile="PendingInvoices.aspx.cs" AutoEventWireup="True" Inherits="Arkus.EnerCard.EnerCardWeb.portlets.PendingInvoices" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>
            PendingInvoices
        </title>

        <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1" />
        <meta name="CODE_LANGUAGE" content="C#" />
        <meta name="vs_defaultClientScript" content="JavaScript" />
        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
        <link href="../css/Style.css" type="text/css" rel="stylesheet" />

        <script>
            function viewAll()
            {
                window.parent.location.href = "../reports/PendingInvoicesReport.aspx";
            }

            function onlinePayment()
            {
                window.parent.location.href = "../multipagos/onlinePayment.aspx";
            }

            function AddCredit(url)
            {
                window.parent.location.href = url;
            }

            function openLink (id,CouponInvoice)
            {
                document.getElementById('hdn').value = id;      
                __doPostBack('btnSaveSession','');
                window.open('../ClubCard/reportStatementOfAccount.aspx','Reporte');
            }
        </script>
    </head>

    <body id="bodyWhite">
        <form id="Form1" method="post" runat="server">
            <input type="button" id="btnSaveSession" runat="server" value="saveSession" style="display:none" onserverclick="btnSaveSession_ServerClick" />
            <input type="hidden" id="hdn" runat="server" />

            <table cellspacing="0" cellpadding="0" width="100%" border="0">
                <tr>
                    <td width="100%">
                        <asp:DataGrid ID="dgInvoices" runat="server" AutoGenerateColumns="False" Width="100%"
                            DataKeyField="InvoiceId" PageSize="5" PagerStyle-CssClass="subT" AllowPaging="True"
                            PagerStyle-Visible="False">
                            <AlternatingItemStyle CssClass="txtA" />
                            <ItemStyle CssClass="txtB" />
                            <HeaderStyle CssClass="subT" />

                            <Columns>
                                <asp:TemplateColumn HeaderText="CouponInvoice" visible="false">
                                    <ItemTemplate>
                                        <%# DataBinder.Eval(Container, "DataItem.CouponInvoice") %>
                                    </ItemTemplate>

                                    <ItemStyle HorizontalAlign="Right" />
                                </asp:TemplateColumn>

                                <asp:TemplateColumn HeaderText="Fecha">
                                    <ItemTemplate>
                                        <%# DateTime.Parse(DataBinder.Eval(Container, "DataItem.date").ToString()).ToString("dd/MM/yy") %>
                                    </ItemTemplate>
                                </asp:TemplateColumn>

                                <asp:TemplateColumn ItemStyle-HorizontalAlign="Right" HeaderText="Monto">
                                    <ItemTemplate>
                                        <%# double.Parse(DataBinder.Eval(Container, "DataItem.Charge").ToString()).ToString("C")%>
                                    </ItemTemplate>
                                </asp:TemplateColumn>

                                <asp:TemplateColumn ItemStyle-HorizontalAlign="Right" HeaderText="Saldo">
                                    <ItemTemplate>
                                        <%# (double.Parse(DataBinder.Eval(Container, "DataItem.Payment").ToString())).ToString("C")%>
                                    </ItemTemplate>
                                </asp:TemplateColumn>

                                <asp:TemplateColumn>
                                    <ItemTemplate>
                                        <img id="imgPDF" src="../images/icons/pdf.gif" onclick='javascript:openLink(<%# DataBinder.Eval(Container, "DataItem.InvoiceId")%>,<%# DataBinder.Eval(Container.DataItem, "CouponInvoice") %> )' style="cursor: pointer" alt="" />
                                    </ItemTemplate>

                                    <ItemStyle HorizontalAlign="Right" />
                                </asp:TemplateColumn>
                            </Columns>
                        </asp:DataGrid>
                    </td>
                </tr>

                <tr>
                    <td class="subT" width="100%" />
                </tr>
            </table>
        </form>
    </body>
</html>

CS

using System;
using System.Web.UI.WebControls;
using Arkus.EnerCard.Core;
using System.Configuration;

namespace Arkus.EnerCard.EnerCardWeb.portlets
{
    public partial class PendingInvoices : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadDataGrid();
            }
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {    
            this.Load += new EventHandler(this.Page_Load);

        }

        private void LoadDataGrid()
        {
            ClubCard.Core.Client _Client = CurrentClient;
            dgInvoices.DataSource = PendingInvoice.GetList(_Client.id, DateTime.Today.AddYears(-200), DateTime.Today.Date.AddDays(1));
            dgInvoices.DataBind();

            if (ConfigurationSettings.AppSettings["multipagosActive"] == "1" || ConfigurationSettings.AppSettings["multipagosTestIdClient"] == _Client.id.ToString())
            {
                btnPagoLinea.Visible = true;
            }
        }

        protected void btnSaveSession_ServerClick(object sender, EventArgs e)
        {
            Session["idInvoice"] = hdn.Value;
        }
    }
}
4

1 回答 1

0

使用 ASP.Net 中的 Crystal,我在 Page_Init 而不是 Page_Load 事件中加载报表。此外,关闭和处置清理在 Page_Unload 事件中处理。

我注意到 Web 应用程序启动后的第一个报告需要相当长的时间来加载这是 Crystal 运行时。第一次加载后,一切都很好。IIS 在空闲时间后关闭 Web 应用程序后也会发生这种情况。

您唯一能做的就是预热水晶运行时。一种选择是在您的应用程序启动时执行此操作。甚至这意味着从您的 global.asax 在 Application_Start 调用一个虚拟的空白水晶报告。

于 2014-09-12T12:38:07.687 回答