Multithreading RDLC report not refreshing - c#

Gurus
We are developing a win forms application in .NET 4.0, that generate PDF reports using RDLC control. As the report generation takes lot of time, we decided to implement Parallel for each.. With the following code , it generates the PDF for first record after that, system just hangs.. Do help us...
public void generatereport()
{
button1.Enabled = false;
button4.Enabled = false;
DataTable dtBranch = new DataTable();
dtBranch = getBranchNo(); -- we might get around 300 rows here
try
{
Parallel.ForEach(dtBranch.AsEnumerable(), drow =>
{
// Shows the ReportData along with the branch code
reportdate = drow["reportdate"].ToString();
string branchName = drow["BranchNo"].ToString();
ProcessReport(branchName);
});
reportViewer2.Visible = false;
button1.Enabled = true;
button4.Enabled = true;
lblMsg.Text = "Branch Summary Generated at '" + #fullpath + "'";
}
catch (AggregateException e)
{
//Console.Write(e.Data + e.Message);
//Console.ReadLine();
}
}
private void ProcessReport(string branName)
{
if (reportViewer2.InvokeRequired)
{
ProcessReportCallBack d = new ProcessReportCallBack(ProcessReport);
Invoke(d, new object[] { branName });
}
else
{
log.Debug("branch" + DateTime.Now.ToString());
DataTable dt = new DataTable();
dt = getReportOrderNoBasedonBranchID(branName);//Get all the report order no as per the branch id
this.sp_getReportOrderNoTableAdapter.Fill(this.getRptNo.sp_getReportOrderNo, branName);
this.reportViewer2.LocalReport.SubreportProcessing += new Microsoft.Reporting.WinForms.SubreportProcessingEventHandler(this.reportViewer2_Subreport1);
this.reportViewer2.Clear();
this.reportViewer2.ProcessingMode = ProcessingMode.Local;
this.reportViewer2.LocalReport.ReportPath = #"Master.rdlc";
this.reportViewer2.Refresh();
Savepdf("reportViewer2", branName + "_" + reportdate);
}
}
In save PDF we are generating the PDF report..
byte[] bytes = null;
bytes = reportViewer2.LocalReport.Render(
"PDF", null, out mimeType, out encoding,
out extension,
out streamids, out warnings);
filename = BranchName + '_' + "Summary" + ".pdf";
using (FileStream fs = new FileStream(#fullpath + '\\' + filename, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
fs.Close();
}
bytes = null;
Kindly provide your feedback

you don't need a sample codes to Export to PDF, when the RDLC is already rendered to the ReportViewer try to find this icon from the ToolBars of ReportViewer Control:
EDIT:
Save RDLC reports as PDF programaticaly
public void Save(ReportViewer viewer, string savePath)
{
byte[] Bytes = viewer.LocalReport.Render("PDF", "", null, null, null, null, null);
using (FileStream Stream = new FileStream(savePath, FileMode.Create)) {
Stream.Write(Bytes, 0, Bytes.Length);
}
}

Related

Error code 0x800704CD when generating PDF to zip

I know this question was asked & answered before, but the solutions don't work for me. I have to dynamically create a list of PDFs, and each row has a checkbox. You check the PDFs you want to download, whose ID get passed to a function to create the PDF. I store those PDF's in a list, which gets passed to the Zip function (DotNetZip). Problem is, when first generating a PDF, I get that error somewhere in the middle of creating it, about halfway through, when adding a new page in the PDF. Usually it's the same spot but occasionally it changes where it crashes. Could anyone look at my code and point out where I'm messing up?
protected void Download_PDF_Click(object sender, EventArgs e)
{
Response.Clear();
Response.BufferOutput = false;
HttpContext c = HttpContext.Current;
String archiveName = "Arhiva Inspectii.zip";
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=\"" + archiveName + "\"");
int nr_rows = tbl_inspectii.Rows.Count - 1;
foreach (String id_chbx in ID_Checkbox)
{
CheckBox chbx = tbl_inspectii.FindControl(id_chbx) as CheckBox;
String PDF_id = "";
if(chbx != null)
{
if(chbx.Checked)
{
PDF_id = chbx.ID.Replace("ChBx", string.Empty);
Create_PDF(PDF_id);
}
}
}
string destdir = Server.MapPath("~/Zip/") + archiveName;
using (ZipFile zip = new ZipFile())
{
zip.AddFiles(PDF_list, destdir);
zip.Save(destdir);
}
}
protected byte[] Create_PDF(String id_insp_max)
{
using (MemoryStream ms = new MemoryStream())
{
Document brosura = new Document(PageSize.A4);
brosura.SetMargins(40, 40, 40, 40);
PdfWriter wri = PdfWriter.GetInstance(brosura, ms);//new FileStream(Server.MapPath("Pdf/") + titlu_pdf + ".pdf", FileMode.Create)
HttpContext.Current.Response.AppendHeader("Content-Disposition", "inline; filename=\"" + titlu_pdf + ".pdf\"");
PdfWriter.GetInstance(brosura, HttpContext.Current.Response.OutputStream);
brosura.Open();
//lots of SQL, and brosura.Add();
//at some point, a brosura.Add() has the error halfway through the pdf
brosura.Close();
PDF_list.Add(titlu_pdf);
wri.Close();
return ms.ToArray();
}
}
Try to move the Response block after you closed the Document.
And try to add Response.End();
And why are you return the Array in Create_PDF but does not using it?

Trying to export telerik winform grouped grid data to excel?

When i export grid data without grouping it exports perfectly but when i export grid data with grouping it skips rows and if i remove header rows then data is exported perfectly with or without grouping?
I think the problem is in header rows when i remove header rows then it works perfectly.
Please tell me how can i adjust header rows so that grouped data can be exported perfectly
private void btnExport_Click(object sender, EventArgs e)
{
saveFileDialog1.FileName = this.ReportHeaderText.Replace(' ', '-').Replace('/', '-');
saveFileDialog1.OverwritePrompt = true;
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
{
return;
}
if (saveFileDialog1.CheckFileExists)
{
}
if (saveFileDialog1.FileName.Equals(String.Empty))
{
RiceMsgBox.ShowErrorBox("Please enter a file name.");
return;
}
string fileName = this.saveFileDialog1.FileName;
bool openExportFile = false;
RunExportToExcelML(fileName, ref openExportFile);
if (openExportFile)
{
try
{
System.Diagnostics.Process.Start(fileName);
}
catch (Exception ex)
{
RiceMsgBox.ShowErrorBox("The file cannot be opened on your system");
}
}
this.tabControl1.SelectedIndex = 1;
}
private void RunExportToExcelML(string fileName, ref bool openExportFile)
{
Telerik.WinControls.Export.GridViewSpreadExport exporter = new Telerik.WinControls.Export.GridViewSpreadExport(gridReport, 0);
exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;
exporter.CellFormatting += exporter_CellFormatting;
exporter.ExportVisualSettings = true;
exporter.SheetMaxRows = ExcelMaxRows._1048576;
exporter.SheetName = System.Text.RegularExpressions.Regex.Replace(this.ReportHeaderText.Length > 30 ? this.ReportHeaderText.Substring(0,30) : this.ReportHeaderText, #"[^0-9a-zA-Z]+", ",");
exporter.SummariesExportOption = SummariesOption.ExportAll;
Telerik.WinControls.Export.SpreadExportRenderer exportRenderer = new Telerik.WinControls.Export.SpreadExportRenderer();
exportRenderer.WorkbookCreated += renderer_WorkbookCreated;
// exportRenderer.ExcelTableCreated += exporter_ExcelTableCreated;
//exporter.CellFormatting += exporter_ExcelCellFormatting;
//FormatGridColumns(gridReport);
try
{
exporter.RunExport(fileName, exportRenderer);
var dialog = RiceMsgBox.GetQuestionBox("The data in the grid was exported successfully. Do you want to open the file?");
if (dialog == DialogResult.Yes)
{
openExportFile = true;
}
else
{
openExportFile = false;
}
}
catch(Exception ex)
{
RiceMsgBox.ShowErrorBox("Error exporting data.");
}
}
void exporter_CellFormatting(object sender, Telerik.WinControls.Export.CellFormattingEventArgs e)
{
CellBorders borders = new CellBorders();
borders.Top = new CellBorder(CellBorderStyle.Thin, new ThemableColor(System.Windows.Media.Colors.Black));
borders.Bottom = new CellBorder(CellBorderStyle.Thin, new ThemableColor(System.Windows.Media.Colors.Black));
borders.Right = new CellBorder(CellBorderStyle.Thin, new ThemableColor(System.Windows.Media.Colors.Black));
borders.Left = new CellBorder(CellBorderStyle.Thin, new ThemableColor(System.Windows.Media.Colors.Black));
e.CellStyleInfo.Borders = borders;
}
void renderer_WorkbookCreated(object sender, Telerik.WinControls.Export.WorkbookCreatedEventArgs e)
{
PatternFill solidPatternFill = new PatternFill(PatternType.Solid, System.Windows.Media.Colors.Transparent, System.Windows.Media.Colors.Transparent);
CellValueFormat textFormat = new CellValueFormat("#");
string dateRange = "( From Date : " + dtpFromDate.Text + " - To Date : " + dtpToDate.Text + " )";
Worksheet worksheet = e.Workbook.Sheets[0] as Worksheet;
worksheet.Columns[worksheet.UsedCellRange].AutoFitWidth();
CellRange range = new CellRange(0, 0, 1, gridReport.Columns.Count);
CellSelection header = worksheet.Cells[range];
if (header.CanInsertOrRemove(range, ShiftType.Down))
{
header.Insert(InsertShiftType.Down);
}
header.Merge();
header.SetFormat(textFormat);
header.SetHorizontalAlignment(Telerik.Windows.Documents.Spreadsheet.Model.RadHorizontalAlignment.Center);
header.SetVerticalAlignment(Telerik.Windows.Documents.Spreadsheet.Model.RadVerticalAlignment.Center);
header.SetFontFamily(new ThemableFontFamily("Rockwell"));
header.SetFontSize(24);
header.SetFill(solidPatternFill);
header.SetValue(this.ReportHeaderText);
}
The GridViewSpreadExport generates a document that consists of merged cells. Inserting a row on the top and then exporting the document causes wrong merged cells. It is a known issue: link
As a workaround, instead of using the WorkbookCreated event to insert a new row you can export the document and then reopen it and insert a row above the exported grid data.
private void RunExportToExcelML(string fileName, ref bool openExportFile)
{
Telerik.WinControls.Export.GridViewSpreadExport exporter = new Telerik.WinControls.Export.GridViewSpreadExport(gridReport, 0);
exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;
exporter.CellFormatting += exporter_CellFormatting;
exporter.ExportVisualSettings = true;
exporter.SheetMaxRows = ExcelMaxRows._1048576;
exporter.SheetName = System.Text.RegularExpressions.Regex.Replace(this.ReportHeaderText.Length > 30 ? this.ReportHeaderText.Substring(0, 30) : this.ReportHeaderText, #"[^0-9a-zA-Z]+", ",");
exporter.SummariesExportOption = SummariesOption.ExportAll;
Telerik.WinControls.Export.SpreadExportRenderer exportRenderer = new Telerik.WinControls.Export.SpreadExportRenderer();
//exportRenderer.WorkbookCreated += renderer_WorkbookCreated;
try
{
exporter.RunExport(fileName, exportRenderer);
this.InsertHeader(fileName);
// more code...
}
private void InsertHeader(string fileName)
{
XlsxFormatProvider formatProvider = new XlsxFormatProvider();
Workbook workbook = null;
using (Stream stream = new FileStream(fileName, FileMode.Open))
{
workbook = formatProvider.Import(stream);
}
PatternFill solidPatternFill = new PatternFill(PatternType.Solid, System.Windows.Media.Colors.Transparent, System.Windows.Media.Colors.Transparent);
CellValueFormat textFormat = new CellValueFormat("#");
//string dateRange = "( From Date : " + dtpFromDate.Text + " - To Date : " + dtpToDate.Text + " )";
Worksheet worksheet = workbook.Sheets[0] as Worksheet;
worksheet.Columns[worksheet.UsedCellRange].AutoFitWidth();
CellRange range = new CellRange(0, 0, 1, gridReport.Columns.Count);
CellSelection header = worksheet.Cells[range];
if (header.CanInsertOrRemove(range, ShiftType.Down))
{
header.Insert(InsertShiftType.Down);
}
header.Merge();
header.SetFormat(textFormat);
header.SetHorizontalAlignment(Telerik.Windows.Documents.Spreadsheet.Model.RadHorizontalAlignment.Center);
header.SetVerticalAlignment(Telerik.Windows.Documents.Spreadsheet.Model.RadVerticalAlignment.Center);
header.SetFontFamily(new ThemableFontFamily("Rockwell"));
header.SetFontSize(24);
header.SetFill(solidPatternFill);
header.SetValue(this.ReportHeaderText);
using (Stream output = new FileStream(fileName, FileMode.Create))
{
formatProvider.Export(workbook, output);
}
}
For more information about SpreadProcessing visit the following link: https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/overview

How to create PDF Report with data from code in list form, not directly from database with Microsoft Report Viewer

I am using Microsoft.Report.Viewer for generate PDF in my ASP .NET WEB API application. So far when my report get the data directly from database, there is no problem. The problem is, when I try to create a report with subreport within and the subreport data is got from code in a list form, I didn't get the expected result. What I do is create a report with subreport from this tutorial. But when I generate the PDF, what I get is this message .
Here is my code :
My Web API to generate the PDF :
[Route("GeneratePDFForDailyProgram")]
[HttpGet]
[AllowAnonymous]
public async Task<IHttpActionResult> GeneratePDFForDailyProgram(int id) {
string guid = Guid.NewGuid().ToString();
string fileName = string.Concat("Booking_No" + Convert.ToString(id) + "_" + guid.ToUpper() + ".pdf");
string filePath = HttpContext.Current.Server.MapPath("~/Content/Temp/" + fileName);
string name = Request.RequestUri.GetLeftPart(UriPartial.Authority) + System.Configuration.ConfigurationManager.ConnectionStrings[System.Configuration.ConfigurationManager.AppSettings["CUSTOMPORT"]];
string name2 = Request.GetRequestContext().VirtualPathRoot;
List<TourDestination> destination = new List<TourDestination>();
TourTransactionSummaryViewModel summaryViewModel = new TourTransactionSummaryViewModel();
try {
//summaryViewModel = await CalcSummaryViewModel(transaction, summaryViewModel, db);
summaryViewModel.DailyPrograms = DailyProgram(id);
destination = TourDestination(summaryViewModel.DailyPrograms);
List < Movement > movementList = summaryViewModel.DailyPrograms.FirstOrDefault().Movements.ToList();
Reports.ReportGenerator.GeneratePDFForDailyProgram(summaryViewModel.DailyPrograms, destination, filePath);
//await Reports.ReportGenerator.GeneratePDFForMovement(movementList, filePath);
HttpResponseMessage result = null;
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(filePath, FileMode.Open));
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = fileName;
result.Dispose();
string convertedFilePath = filePath.Replace(#"\\", #"\");
} catch (Exception ex) {
return BadRequest(ex.Message);
}
return Ok(name + name2 + "/Content/Temp/" + fileName);
}
As you can see from the code above, I use GeneratePDFForDailyProgram method to generate the PDF.
Here my GeneratePDFForDailyProgram method :
public static bool GeneratePDFForDailyProgram(TourTransactionSummaryViewModel.DailyProgram[] dailyPrograms, List<TourDestination> destination , string filePath) {
try {
string binPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin");
var assembly = Assembly.Load(System.IO.File.ReadAllBytes(binPath + "\\TripPlannerAPI.dll"));
using (Stream stream = assembly.GetManifestResourceStream(DailyProgramReport)) {
var viewer = new ReportViewer();
viewer.LocalReport.EnableExternalImages = true;
viewer.LocalReport.LoadReportDefinition(stream);
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
viewer.LocalReport.SubreportProcessing += new Microsoft.Reporting.WebForms.SubreportProcessingEventHandler(LocalReport_SubreportProcessing);
viewer.LocalReport.DataSources.Add(new ReportDataSource("DailyProgram", dailyPrograms));
byte[] bytes = viewer.LocalReport.Render(
"PDF", null, out mimeType, out encoding, out filenameExtension,
out streamids, out warnings);
using (FileStream fs = new FileStream(filePath, FileMode.Create)) {
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
}
stream.Flush();
}
} catch (Exception ex) {
return false;
}
return true;
}
To run the SubReport, I use the eventhandler code :
private static void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e) {
DateTime movementDate = Convert.ToDateTime(e.Parameters[0].Values[0]);
TourTransactionsController controller = new TourTransactionsController();
var movement = controller.Movements();
List<Movement> movementList = new List<Movement>();
movementList.Add(new Movement {
Destination = "TEST",
MovementDescription = "TEST",
DateTime = Convert.ToDateTime("2017-09-25") //HARDCODE FOR TEST
});
e.DataSources.Clear();
e.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource() {
Name = "DSMovements",
Value = movementList
});
//throw new NotImplementedException();
}
What I did try :
Check the sub report name, and change it from report name to report file url. Still get the same message.
Generate the Sub Report directly, not from the main report. The subreport is successfully generated.
PS : When I debug my code, and put a breakpoint in my event handler LocalReport_SubreportProcessing the breakpoint is not hitting while debugging
My Questions are :
Why my breakpoint on the eventhandler is not hitting while debugging ?
Is it possible that eventhandler which is not hitting while debugging, could be the reason I got the message The subreport 'MovementReport' could not be
found at the specified location MovementReport.
Please verify that the subreport has been
published and that the name is correct. ?
Is there any other way for me to create a main report with data from db, and the subreport with data from code in list form ?
Any help is appreciated.

Trying to download excel file from ssrs and using ClosedXML to modified, getting exception

Trying to download excel file from ssrs and using ClosedXML to modified, getting exception.
Following is my code, getting exception at exlWorkBook = new XLWorkbook(FilePath);
public ActionResult ExportToExcel(string VesselObjectId, string EnquiryID)
{
XLWorkbook exlWorkBook = null;
string FileName = "QuoteCompare_" + VesselObjectId + "_" + String.Format("{0:yyyyMMddHHmmss}", DateTime.Now) + ".xlsx";
string DirPath = Server.MapPath("~/App_Files/Seachef");
string FilePath = Path.Combine(DirPath, FileName);
string strTargetURL = GlobalParameters.SSRSBaseUrl + "/SeaChefReports/rptQuoteCompare&User_ID=" + CurrentUserData.UserId + "&P_ENQUIRY_HD_ID=" + EnquiryID + "&rc:LinkTarget=_blank&rc:Parameters=False&rs:Format=EXCELOPENXML&rs:ClearSession=true";
try
{
ReportViewer objReportViewer = new ReportViewer();
objReportViewer.ProcessingMode = ProcessingMode.Remote;
objReportViewer.ServerReport.ReportServerCredentials = new CustomReportCredentials(ConfigurationManager.AppSettings["ReportServerId"], ConfigurationManager.AppSettings["ReportServerPwd"], "BSM");
objReportViewer.ServerReport.Refresh();
SSRSWebClient client = new SSRSWebClient();
client.DownloadFileBinary(FilePath, strTargetURL);
if (new FileInfo(FilePath).Exists)
{
exlWorkBook = new XLWorkbook(FilePath);
var ws = exlWorkBook.Worksheet("rptQuoteCompare");
List<IXLCell> vendorsectionTotalCells = new List<IXLCell>();
List<IXLCell> vendorCategoryTotalCells = new List<IXLCell>();
ws.SheetView.FreezeRows(5);
ws.SheetView.FreezeColumns(7);
ws.Range(ws.FirstCell(), ws.LastCellUsed()).Style.Protection.Locked = true;
ws.Cell("A1").Value = EnquiryID;
//Doing Some more modifications
exlWorkBook.Style.Protection.Locked = true;
var protection = ws.Protect(BSMUiHelpers.SeachefSessionVariables.SeachefSessionData.ExcelPassword);
protection.SelectLockedCells = true;
protection.SelectUnlockedCells = true;
Stream objStream = new MemoryStream();
exlWorkBook.SaveAs(objStream);
objStream.Position = 0;
BinaryReader rdr = new BinaryReader(objStream);
byte[] fileData = rdr.ReadBytes((int)objStream.Length);
rdr.Close();
objStream.Close();
return File(fileData, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", FileName);
}
else
{
return Json("Export failed!");
}
}
catch (Exception ex)
{
bool rethrow = UserInterfaceExceptionHandler.HandleExcetion(ref ex, CurrentUserData.UserId.ToString(), "");
return Json("Export failed!" + ex.Message);
}
finally
{
if (exlWorkBook != null)
exlWorkBook.Dispose();
if (new FileInfo(FilePath).Exists)
System.IO.File.Delete(FilePath);
}
}
below is the Stack Trace
at ClosedXML.Excel.XLWorkbook.LoadCells(SharedStringItem[] sharedStrings, Stylesheet s, NumberingFormats numberingFormats, Fills fills, Borders borders, Fonts fonts, Dictionary`2 sharedFormulasR1C1, XLWorksheet ws, Dictionary`2 styleList, Cell cell, Int32 rowIndex)
at ClosedXML.Excel.XLWorkbook.LoadRows(Stylesheet s, NumberingFormats numberingFormats, Fills fills, Borders borders, Fonts fonts, XLWorksheet ws, SharedStringItem[] sharedStrings, Dictionary`2 sharedFormulasR1C1, Dictionary`2 styleList, Row row)
at ClosedXML.Excel.XLWorkbook.LoadSpreadsheetDocument(SpreadsheetDocument dSpreadsheet)
at ClosedXML.Excel.XLWorkbook.LoadSheets(String fileName)
at ClosedXML.Excel.XLWorkbook.Load(String file)
at ClosedXML.Excel.XLWorkbook..ctor(String file, XLEventTracking eventTracking)
at ClosedXML.Excel.XLWorkbook..ctor(String file)
at BSM.BSMPALv2.Web.Areas.Seachef.Controllers.QuotationComparisionController.ExportToExcel(String VesselObjectId, String EnquiryID) in d:\XXX\TestSource\XXXXXXX.XXXXXX\XXXXXXX.XXXX\XXXXXXXXXX\Areas\ModuleName\Controllers\QuotationComparisionController.cs:line 293

Optimizing reportviewer to not get outofmemory exception

We have implemented a process using C# and reportviewer to create PDFs by the localreport.render method.
When we have to process a big file, say more than 20000 records, the process fails with outofmemory exception error. I know there may be lot of causes for this error but what I want to know is, if the below code is okay or if you expert can give me a better solution.
I have about 40 case statements each calling different .rdlc files and it is based on the type (I did not include all the case statements due to lack of space).
USP_Select_Batch_Address_To_Sort is a dataset defined in the solution executing a stored procedure accepting three parameters (in this case batch, run and sequence#).
So is this approach feasible? What other solution can you provide?
public static void GenerateIndividualPDFs(string batch, string run, MainDataSet1 DS, MainDataSet1TableAdapters.USP_Select_Batch_Address_To_SortTableAdapter Ta, BindingSource bs, int intStart = 0, int intEnd = 0, string strLetterType = "")
{
reportDataSource.Name = "DataSet1";
reportDataSource.Value = bs;
int count;
SqlDataAdapter adapter;
var batchinfo = new clsBatchInfo();
ReportViewer report = new ReportViewer();
report.LocalReport.DataSources.Add(reportDataSource);
if (!Directory.Exists(mstrFilePath + "\\" + batch + run))
{
DirectoryInfo di = Directory.CreateDirectory(mstrFilePath + "\\" + batch + run);
}
var DA = new clsGetBatchSort();
//this dataAdapter will print the full set
adapter = new SqlDataAdapter(DA.dsBatch_Sort(batch, run));
DataSet ds = new DataSet();
adapter.Fill(ds);
count = ds.Tables[0].Rows.Count;
int i = 0;
int LetterTypeID = 0;
report.ProcessingMode = ProcessingMode.Local;
foreach (DataRow dr in ds.Tables[0].Rows)
{
i++;
report.Clear();
Ta.ClearBeforeFill = true;
try
{
LetterTypeID = Convert.ToInt32(dr[2]);
switch (LetterTypeID)
{
case 1:
{
Ta.Fill(DS.USP_Select_Batch_Address_To_Sort, Convert.ToDecimal(batch), run, Convert.ToInt32(dr["MPresortID"]));
report.LocalReport.ReportEmbeddedResource = "ReportsApplication1.ABC.MAENG.rdlc";
ExportReport(Convert.ToInt32(dr["MPresortID"]), batch, run, report);
continue;
}
case 2:
{
Ta.Fill(DS.USP_Select_Batch_Address_To_Sort, Convert.ToDecimal(batch), run, Convert.ToInt32(dr["MPresortID"]));
report.LocalReport.ReportEmbeddedResource = "ReportsApplication1.ABC.MASPA.rdlc";
ExportReport(Convert.ToInt32(dr["MPresortID"]), batch, run, report);
continue;
}
catch (Exception ex)
{
clsEmail.EmailMessage("Error Batch " + batch + run, "clsGenerateLetters " + ex.Message);
continue;
//MessageBox.Show(ex.Message);
//return "";
}
}
}
private static void ExportReport(int PreSortID, string batch, string run, ReportViewer Report)
{
Report.RefreshReport();
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
string fmt = "00000000";
byte[] bytes = Report.LocalReport.Render(
"PDF", null, out mimeType, out encoding, out filenameExtension,
out streamids, out warnings);
string filename = mstrFilePath + "\\" + batch + run + "\\" + PreSortID.ToString(fmt) + ".PDF";
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
fs.Close();
}
Report.LocalReport.ReleaseSandboxAppDomain();
}

Categories

Resources