zoukankan      html  css  js  c++  java
  • RDLC生成pdf文件“An unexpected error occurred in Report Processing”错误处理

    这几天遇到一个简单又纠结的异常:

    通过循环报表生成pdf文件的时候,循环时出现了一个错误:“An unexpected error occurred in Report Processing”发生在行:

    “byte[] bytes = reportViewMain.LocalReport.Render(fileFormat, null, out strMimeType, out strEncoding, out strFileNameExtension, out strStreamIds, out warnings);”
    这个问题主要是循环同一个rdlc模板的时候出现的,第一个报表生成pdf文件成功,但是第二个报表生成的时候就报错了,我也尝试通过:“reportViewMain.LocalReport.Dispose();”释放资源,但是没用。

    积极查找信息,并解决中....

    通过参考:http://hi.baidu.com/jiangdbna/item/d8063f612f9da72f68105b13

    因为在循环中有资源没有释放,所以必须通过:

    reportViewMain.Reset();  //将控件重置为其默认值(reportViewMain为ReportViewer控件名)

    即可。

    关键性代码参考如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Reflection;
    using System.IO;
    using TlEt.Ss.Model.SsSys;
    using System.Configuration;
    using Microsoft.Reporting.WebForms;
    
    using System.Text;
    using System.Drawing.Imaging;
    using System.Drawing.Printing;
    using System.Threading;
    
    using TlEt.Ss.Common;
    using TlEt.Ss.UILogic;
    using TlEt.Ss.Model;
    using TlEt.Ss.Model.Reports;
    using TlEt.Ss.BLL;
    using TlEt.Framework.Cache;
    using System.Security;
    using System.Security.Permissions;
    
    namespace TlEt.Ss.Web.Common
    {
        public partial class MultiReportPreview : PageBase, IDisposable
        {
            private IList<TlEt.Ss.Model.Report> subReports;
    
            private int printCurrentPageIndex; //记录打印的页索引
            private IList<Stream> printStreams; //打印的数据流
    
            private string path = UIUtilities.GetConfigValue<string>("ReportPath");
            private string forSpecimen = UIUtilities.GetConfigValue<string>("ForSpecimen");
            bool isExists = false;
    
            string emailAttachmentsPath
            {
                get
                {
                    string attachPath = ConfigurationManager.AppSettings["EmailAttachmentsPath"];
                    attachPath = AppDomain.CurrentDomain.BaseDirectory + attachPath.Replace("/","\");
    
                    if (!Directory.Exists(attachPath))
                    {
                        Directory.CreateDirectory(attachPath);
                    }
    
                    return attachPath;
                }
            }
            string reportPreviewPath
            {
                get
                {
                    string filePath = ConfigurationManager.AppSettings["ReportPreviewPath"];
                    filePath = AppDomain.CurrentDomain.BaseDirectory + filePath.Replace("/", "\");
    
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
    
                    return filePath;
                }
            }
    
            private string splitUrl = "";
            private string[] pdflist;
            protected void Page_Load(object sender, EventArgs e)
            {
                try
                {
                    if (!this.IsPostBack)
                    {
                        SetReportSize();
    
                        string tempReportPath = string.Empty;
                        string url = Request.RawUrl.ToString();
                        string strUrl = url.Substring(url.IndexOf("?") + 1, url.Length - url.IndexOf("?") - 1);
                        string[] strTemp = strUrl.Split('/');
                        if (strTemp.Length > 0)
                        {
                            pdflist = new string[strTemp.Length];
    
                            for (int m = 0; m < strTemp.Length; m++)
                            {
                                splitUrl = strTemp[m].ToString();
                                string[] parameters = splitUrl.Split('&');
    
                                string reportID = parameters[1].Substring(9, parameters[1].Length - 9);//Request.QueryString["ReportID"].ToString();
                                string reportFolder = parameters[0].Substring(13, parameters[0].Length - 13);//Request.QueryString["ReportFolder"].ToString();
    
                                string configFile = Server.MapPath(UIUtilities.ApplicationPath + "/Config/" + reportFolder + "Reports.xml");
                                TlEt.Ss.Model.Report report = ReportUtility.GetReportsByID(configFile, reportID);
    
                                if (report == null)
                                {
                                    Response.Write("Could not find report: " + reportID);
                                    Response.End();
                                    return;
                                }
    
                                if (path.Substring(path.Length - 1) != @"") path = path + @"";
    
                                reportViewMain.Reset();
                                Microsoft.Reporting.WebForms.ReportParameter[] reportParas = GetReportParas(report);
                                reportViewMain.LocalReport.ReportPath = path + report.Path;
                                if (reportParas != null) reportViewMain.LocalReport.SetParameters(reportParas);
                                reportViewMain.LocalReport.DataSources.Clear();
    
                                if (report.DataSources != null)
                                {
                                    for (int i = 0; i < report.DataSources.Count; i++)
                                    {
                                        Dictionary<string, string> methodParas = GetMethodParas(report.DataSources[i], GetUrlParas(splitUrl));
                                        //反射调用
                                        IEnumerable<Object> ds = ReportUtility.GetDataSource(report.DataSources[i], methodParas);
    
                                        if (i == 0 || report.DataSources[i].Name.IndexOf("Header") > 0) SetReportDefaultValue(ref ds);
    
                                        ReportDataSource rds = new ReportDataSource(report.DataSources[i].Name, ds);
                                        reportViewMain.LocalReport.DataSources.Add(rds);
                                    }
                                }
    
                                //reportViewMain.LocalReport.Refresh();
    
                                //是否有子报表
                                if (report.SubReports != null)
                                {
                                    subReports = report.SubReports;
                                    reportViewMain.LocalReport.SubreportProcessing += new Microsoft.Reporting.WebForms.SubreportProcessingEventHandler(LocalReport_SubreportProcessing);
                                }
    
                                //导出报表
                                string action = Request.QueryString["action"];
                                if (!string.IsNullOrEmpty(action))
                                {
                                    string message = string.Empty;
                                    if (action == "sendemail")
                                    {
                                        string attachFormat = Request.QueryString["attachFormat"]; //0:PDF,1:JPG,2:Excel
                                        message = CreatePDF(attachFormat, emailAttachmentsPath.Replace("\\", "\"));
                                    }
    
                                    //生成PDF,用于报表预览
                                    else if (action == "previewpdf")
                                    {
                                        string attachFormat = "0"; //0:PDF
                                        message = CreatePDF(attachFormat, reportPreviewPath.Replace("\\", "\"));
                                        if (!string.IsNullOrEmpty(message))
                                        {
                                            pdflist[m] = message;
                                        }
                                    }
    
                                    //不弹出打印选项,直接打印(已停用)
                                    else if (action == "print")
                                    {
                                        ExportForPrint(reportViewMain.LocalReport);
    
                                        printCurrentPageIndex = 0;
                                        Print(ref message);
                                    }
    
    
                                    this.ScriptManager1.Dispose();
                                    this.reportViewMain.LocalReport.Dispose();
                                    this.reportViewMain.LocalReport.DataSources.Clear();
    
                                }
                            }
                            CombinePDF combinePDF = new CombinePDF();
                            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".pdf";
                            bool isCombineSuccess = combinePDF.mergePDFFiles(pdflist, reportPreviewPath + fileName);
                            Response.Clear();
                            Response.Write(fileName + "|");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("NULL!");
                    LoggerManager.WriteSysLog.Fatal("ReporePreview Error:" + ex.Message);
                }
            }
    
            private void SetReportSize()
            {
                string rWidth = Request.QueryString["rWidth"];
                string rHeight = Request.QueryString["rHeight"];
    
                if (!string.IsNullOrEmpty(rWidth) && !string.IsNullOrEmpty(rHeight))
                {
                    reportViewMain.Width = Unit.Parse(rWidth + "px");
                    reportViewMain.Height = Unit.Parse(rHeight + "px");
                }
            }
    
            private void LocalReport_SubreportProcessing(object sender, Microsoft.Reporting.WebForms.SubreportProcessingEventArgs e)
            {
                TlEt.Ss.Model.Report report = GetReport(subReports, e.ReportPath);
    
                if (report != null && report.DataSources != null)
                {
                    foreach (var datasource in report.DataSources)
                    {
                        Dictionary<string, string> methodParas = GetMethodParas(datasource, GetUrlParas(splitUrl));
                        IEnumerable<Object> ds = ReportUtility.GetDataSource(datasource, methodParas);
                        e.DataSources.Add(new ReportDataSource(datasource.Name, ds));
                    }
                }
            }
    
            private TlEt.Ss.Model.Report GetReport(IList<Model.Report> _subReports, string reportPath)
            {
                isExists = false;
                TlEt.Ss.Model.Report _report = null;
                foreach (TlEt.Ss.Model.Report report in _subReports)
                {
                    if (isExists)
                    {
                        break;
                    }
    
                    if (report.Path != null && report.Path.Contains(reportPath))
                    {
                        isExists = true;
                        return report;
                    }
    
                    if (report.SubReports != null && !isExists)
                    {
                        _report = GetReport(report.SubReports, reportPath);
                    }
                }
                return _report;
            }
    
            private void SetReportDefaultValue(ref IEnumerable<Object> ds)
            {
                string userID = UISessionManager.CurrentUser.UserID;
                string userName = UISessionManager.CurrentUser.UserName;
                string companyName = UISessionManager.CurrentUser.CompanyName;
                string companyNo = UISessionManager.CurrentUser.CompanyNo;
    
                //string userID = "TC1";
                //string userName = "Travel Consultant";
                //string companyName = "Travel Expert Limit";
                //string companyNo = "TEL";
    
                OrgUnit_MasterImpl orgBLL = new OrgUnit_MasterImpl();
                OrgUnit_Master orgUnit = orgBLL.Load(companyNo, userID);
                object companyLogo = orgUnit.CompanyLogo;
                object companyLogo1 = orgUnit.CompanyLogo1;//页脚图片
    
                foreach (object o in ds)
                {
                    bool isInheriteFromBaseModel = o is RPTBaseModel;
    
                    if (isInheriteFromBaseModel)
                    {
                        PropertyInfo pCompanyName = o.GetType().GetProperty("CompanyName");
                        if (pCompanyName != null) pCompanyName.SetValue(o, companyName, null);
    
                        PropertyInfo pCompanyLogo = o.GetType().GetProperty("CompanyLogo");
                        if (pCompanyLogo != null)
                        {
                            pCompanyLogo.SetValue(o, companyLogo, null);
                        }
    
                        PropertyInfo pPrintUser = o.GetType().GetProperty("PrintUser");
                        if (pPrintUser != null) pPrintUser.SetValue(o, userName, null);
    
                        PropertyInfo pPrintDate = o.GetType().GetProperty("PrintDate");
                        if (pPrintDate != null) pPrintDate.SetValue(o, Utility.FormatDate(DateTime.Now), null);
    
                        PropertyInfo pPrintTime = o.GetType().GetProperty("PrintTime");
                        if (pPrintTime != null)
                        {
                            string m = DateTime.Now.ToString("hh:mm");
    
                            if (DateTime.Now.Hour > 11) 
                                m+= " PM";
                            else
                                m += " AM";
    
                            pPrintTime.SetValue(o, m, null);
                        }
    
                        PropertyInfo pIsDisplayFooterImage = o.GetType().GetProperty("IsDisplayFooterImage");
                        if (pIsDisplayFooterImage != null)
                        {
                            object val = pIsDisplayFooterImage.GetValue(o, null);
    
                            if (val != null && (bool)val)
                            {
                                PropertyInfo pFooterImage = o.GetType().GetProperty("FooterImage");
                                if (pFooterImage != null)
                                {
                                    //pFooterImage.SetValue(o, FooterData, null); old
                                    pFooterImage.SetValue(o, companyLogo1, null); //new
                                }
                            }
                        }
    
                        PropertyInfo pIsDisplayVoidImage = o.GetType().GetProperty("IsDisplayVoidImage");
                        if (pIsDisplayVoidImage != null)
                        {
                            object val = pIsDisplayVoidImage.GetValue(o, null);
    
                            if (val != null && (bool)val)
                            {
                                PropertyInfo pVoidImage = o.GetType().GetProperty("VoidImage");
                                if (pVoidImage != null)
                                {
                                    pVoidImage.SetValue(o, VoidData, null);
                                }
                            }
                        }
    
                        if (forSpecimen == "Y")
                        {
                            PropertyInfo pSpecimenImage = o.GetType().GetProperty("SpecimenImage");
                            if (pSpecimenImage != null)
                            {
                                pSpecimenImage.SetValue(o, SpecimenData, null);
                            }
                        }
                    }
    
                    break;
                }
            }
    
            private Dictionary<string, string> GetUrlParas(string CurrUrl)
            {
                Dictionary<string, string> paras = new Dictionary<string, string>();
    
                string[] parameters = CurrUrl.Split('&');
    
                foreach (string str in parameters)
                {
                    string[] s = str.Split('=');
                    paras.Add(s[0], s[1]);
                }
    
                return paras;
    
            }
    
            private Dictionary<string, string> GetMethodParas(DataSource report,Dictionary<string, string> paras)
            {
                if (report.MethodParameters == null)
                {
                    return null;
                }
                else
                {
                    Dictionary<string, string> methodParas = new Dictionary<string, string>();
    
                    foreach (var methodPara in report.MethodParameters)
                    {
                        if (Request.QueryString[methodPara.ParaName] != null)
                        {
                            methodParas.Add(methodPara.ParaName.ToLower(), paras[methodPara.ParaName]);
                        }
                    }
    
                    if (methodParas.Count <= 0)
                        return null;
                    else
                        return methodParas;
                }
            }
    
            private Microsoft.Reporting.WebForms.ReportParameter[] GetReportParas(TlEt.Ss.Model.Report report)
            {
                if (report.ReportParameters == null)
                {
                    return null;
                }
                else
                {
                    int i = 0;
    
                    foreach (var reportPara in report.ReportParameters) if (Request.QueryString[reportPara.ParaName] != null || reportPara.ParaValue!="") i++;
                    Microsoft.Reporting.WebForms.ReportParameter[] reportParas = new Microsoft.Reporting.WebForms.ReportParameter[i];
    
                    i = 0;
                    foreach (var reportPara in report.ReportParameters)
                    {
                        if (Request.QueryString[reportPara.ParaName] != null)
                        {
                            Microsoft.Reporting.WebForms.ReportParameter para = new Microsoft.Reporting.WebForms.ReportParameter(reportPara.ParaName);
                            para.Values.Add(Request.QueryString[reportPara.ParaName].ToString());
                            reportParas[i++] = para;
                        }
                        else
                        {
                            Microsoft.Reporting.WebForms.ReportParameter para = new Microsoft.Reporting.WebForms.ReportParameter(reportPara.ParaName);
                            para.Values.Add(reportPara.ParaValue);
                            reportParas[i++] = para;
                        }
                    }
    
                    if (reportParas.Length <= 0)
                        return null;
                    else
                        return reportParas;
                }
            }
    
            public string CreatePDF(string fileType,string savePath)
            {
                string fileFormat = string.Empty;
                string fileExtension = string.Empty;
                GetFileFormat(fileType, ref fileFormat, ref fileExtension);
    
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExtension;
                string fileFullPath = savePath + fileName;
    
                try
                {
                    if (reportViewMain == null)
                    {
                        return string.Empty;
                    }
    
                    Warning[] warnings;
                    string[] strStreamIds;
                    string strMimeType;
                    string strEncoding;
                    string strFileNameExtension;
    
                    byte[] bytes = reportViewMain.LocalReport.Render(fileFormat, null, out strMimeType, out strEncoding, out strFileNameExtension, out strStreamIds, out warnings);
    
                    using (FileStream fs = new FileStream(fileFullPath, FileMode.Create))
                    {
                        fs.Write(bytes, 0, bytes.Length);
                        fs.Close();
                    }
                }
                catch(Exception ex)
                {
                    Exception inner = ex.InnerException;
                    string messages = "";
                    while (inner != null)
                    {
                        messages += inner.Message + ";";
                        inner = inner.InnerException;
                    }
                    return messages;//string.Empty;
                }
    
                return fileFullPath;
            }
    
            private void GetFileFormat(string attachFormat, ref string fileFormat, ref string fileExtension)
            {
                switch (attachFormat)
                {
                    case "0":
                        fileFormat = "PDF";
                        break;
                    case "1":
                        fileFormat = "Image";
                        break;
                    case "2":
                        fileFormat = "Excel";
                        break;
                    default:
                        fileFormat = "PDF";
                        break;
                }
    
                switch (fileFormat)
                {
                    case "PDF":
                        fileExtension = ".pdf";
                        break;
                    case "Image":
                        fileExtension = ".jpg";
                        break;
                    case "Excel":
                        fileExtension = ".xls";
                        break;
                    default:
                        fileExtension = ".pdf";
                        break;
                }
            }
    
            private byte[] GetImageData(string imageFile)
            {
                try
                {
                    string imagePath = Request.PhysicalApplicationPath + "Styles\Images\" + imageFile;
                    FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
                    BinaryReader br = new BinaryReader(fs);
                    byte[] data = br.ReadBytes((int)br.BaseStream.Length);
    
                    return data;
                }
                catch 
                {
                    return null;
                }
            }
    
            private byte[] SpecimenData
            {
                get
                {
                    if (CacheManager.Current.GetData("SpecimenImageData") == null)
                    {
                        byte[] data = GetImageData("Specimen.png");
    
                        if (data != null) CacheManager.Current.Add("SpecimenImageData", data);
                    }
    
                    return (byte[])CacheManager.Current.GetData("SpecimenImageData");
                }
            }
    
            private byte[] VoidData
            {
                get
                {
                    if (CacheManager.Current.GetData("VoidImageData") == null)
                    {
                        byte[] data = GetImageData("Void.png");
                        CacheManager.Current.Add("VoidImageData", data);
                    }
    
                    return (byte[])CacheManager.Current.GetData("VoidImageData");
                }
            }
    
            //private byte[] FooterData
            //{
            //    get
            //    {
            //        if (CacheManager.Current.GetData("FooterImageData") == null)
            //        {
            //            byte[] data = GetImageData("IATA.png");
            //            CacheManager.Current.Add("FooterImageData", data);
            //        }
    
            //        return (byte[])CacheManager.Current.GetData("FooterImageData");
            //    }
            //}
    
    
            private void ExportForPrint(LocalReport report)
            {
                string deviceInfo =
                  "<DeviceInfo>" +
                  "  <OutputFormat>EMF</OutputFormat>" +
                  "  <PageWidth>8.5in</PageWidth>" +
                  "  <PageHeight>11in</PageHeight>" +
                  "  <MarginTop>0.25in</MarginTop>" +
                  "  <MarginLeft>0.25in</MarginLeft>" +
                  "  <MarginRight>0.25in</MarginRight>" +
                  "  <MarginBottom>0.25in</MarginBottom>" +
                  "</DeviceInfo>";
    
                Warning[] warnings;
                printStreams = new List<Stream>();
                report.Render("Image", deviceInfo, CreateStream, out warnings);
    
                foreach (Stream stream in printStreams)
                {
                    stream.Position = 0;
                }
            }
    
            private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
            {
                Stream stream = new MemoryStream();
                printStreams.Add(stream);
                return stream;
            }
    
            private void Print(ref string message)
            {
                if (printStreams == null || printStreams.Count == 0)
                {
                    message = "This report no data.";
                    return;
                }
    
                PrintDocument printDoc = new PrintDocument();
                //printDoc.PrinterSettings.PrinterName = "";
                printDoc.DocumentName = "TlEt Report";
    
                //printDoc.PrinterSettings.PrintToFile = true;
    
                if (!printDoc.PrinterSettings.IsValid)
                {
                    message = "Error:Cannot find the default printer.";
                    return;
                }
                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
    
                printDoc.Print();
            }
    
            private void PrintPage(object sender, PrintPageEventArgs ev)
            {
                Metafile pageImage = new Metafile(printStreams[printCurrentPageIndex]);
                ev.Graphics.DrawImage(pageImage, ev.PageBounds);
    
                printCurrentPageIndex++;
                ev.HasMorePages = (printCurrentPageIndex < printStreams.Count);
            }
            
            public void Dispose()
            {
                if (printStreams != null)
                {
                    foreach (Stream stream in printStreams)
                    {
                        stream.Close();
                    }
                    printStreams = null;
                }
            }
        }
    }
    View Code
  • 相关阅读:
    富可视M310刷机包 MIUIV5 红米开发版 闪光 美化 稳定
    Windowsclient SSH 远程连接Windowsserver(PowerShell Server)
    数据结构与算法02--链表基础
    rhadoop linear regression 问题
    奇怪的git代理超时问题
    怎样利用Heartbeat与Floating IP在Ubuntu 14.04上创建高可用性设置
    IVS_原理
    NN入门
    算法体系
    CNN原理
  • 原文地址:https://www.cnblogs.com/captainR/p/3302684.html
Copyright © 2011-2022 走看看