public ActionResult GetPaymentTemplatePdf(Guid id) { var payRepo = new OBKPaymentRepository(); string name = "Счет на оплату.pdf"; StiReport report = new StiReport(); try { report.Load(Server.MapPath("~/Reports/Mrts/OBK/1c/ObkInvoicePayment.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables["ContractId"].ValueObject = id; //итого var totalPriceWithCount = payRepo.GetTotalPriceCount(id); report.Dictionary.Variables["TotalPriceWithCount"].ValueObject = totalPriceWithCount; //в том числе НДС var totalPriceNDS = payRepo.GetTotalPriceNDS(totalPriceWithCount); report.Dictionary.Variables["TotalPriceNDS"].ValueObject = totalPriceNDS; //прописью var priceText = RuDateAndMoneyConverter.CurrencyToTxtTenge(Convert.ToDouble(totalPriceWithCount), false); report.Dictionary.Variables["TotalPriceWithCountName"].ValueObject = priceText; //report.Dictionary.Variables["ChiefAccountant"].ValueObject = payRepo.GetEmpoloyee(Guid.Parse("E1EE3658-0C35-41EB-99FD-FDDC4D07CEC4")); //report.Dictionary.Variables["Executor"].ValueObject = payRepo.GetEmpoloyee(Guid.Parse("55377FAC-A5F0-4093-BBB6-18BD28E53BE1")); report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace); } var stream = new MemoryStream(); var contractId = payRepo.GetContractIdGuid(id); var directionToPayment = payRepo.GetDirectionToPayments(contractId); var signPayment = payRepo.GetDirectionSignData(directionToPayment.Id); if (signPayment.ChiefAccountantSign != null && signPayment.ExecutorSign != null) { try { report.ExportDocument(StiExportFormat.Word2007, stream); stream.Position = 0; Aspose.Words.Document doc = new Aspose.Words.Document(stream); doc.InserQrCodesToEnd("ChiefAccountantSign", signPayment.ChiefAccountantSign); var pdfFile = new MemoryStream(); doc.Save(pdfFile, SaveFormat.Pdf); pdfFile.Position = 0; stream.Close(); return(new FileStreamResult(pdfFile, "application/pdf")); } catch (Exception e) { Console.WriteLine(e); } } report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; return(new FileStreamResult(stream, "application/pdf")); }
/// <summary> /// формирование печатной формы /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult ExportFilePdf(Guid id) { var db = new ncelsEntities(); var assessmentDeclaration = db.OBK_AssessmentDeclaration.FirstOrDefault(dd => dd.Id == id); var fileName = assessmentDeclaration.OBK_Ref_Type.Code == "1" ? "SafetyAssessmentDeclaration.mrt" : "SafetyAssessmentDeclaration.mrt"; string name = "Заявление на проведение оценки безопасности и качества лс.pdf"; StiReport report = new StiReport(); try { report.Load(Server.MapPath("~/Reports/Mrts/" + fileName)); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables["AssessmentDeclarationId"].ValueObject = id; report.Dictionary.Variables["ExecutorSign"].ValueObject = null; report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace); } Stream stream = new MemoryStream(); var assessmentDeclarationHistory = assessmentDeclaration.OBK_AssessmentDeclarationHistory.Where(dh => dh.XmlSign != null) .OrderByDescending(dh => dh.DateCreate).FirstOrDefault(); if (assessmentDeclarationHistory != null) { try { report.ExportDocument(StiExportFormat.Word2007, stream); stream.Position = 0; Aspose.Words.Document doc = new Aspose.Words.Document(stream); doc.InserQrCodesToEnd("ExecutorSign", assessmentDeclarationHistory.XmlSign); var pdfFile = new MemoryStream(); doc.Save(pdfFile, Aspose.Words.SaveFormat.Pdf); pdfFile.Position = 0; stream.Close(); return(new FileStreamResult(pdfFile, "application/pdf")); } catch (Exception e) { Console.WriteLine(e); } } report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; return(new FileStreamResult(stream, "application/pdf")); }
private void btnPdfExport_Click(object sender, EventArgs e) { Report.Load(Application.StartupPath + OutPout_Name()); Report.RegBusinessObject(OutPout_Data(), dgSearch.DataSource); Report.Render(false); _save = new SaveFileDialog(); _save.Filter = "PDF File (.pdf)|*.pdf"; if (_save.ShowDialog() == DialogResult.OK) { Report.ExportDocument(StiExportFormat.Pdf, _save.FileName); } }
private void buttonExport_Click(object sender, EventArgs e) { var report = new StiReport(); report.Load(@"Reports\TwoSimpleLists.mrt"); report.Render(); var stream = new MemoryStream(); switch (comboBoxFormat.Text) { case "PDF": report.ExportDocument(StiExportFormat.Pdf, stream); saveFileDialog.DefaultExt = ".pdf"; break; case "Word": report.ExportDocument(StiExportFormat.Word2007, stream); saveFileDialog.DefaultExt = ".docx"; break; case "Excel": report.ExportDocument(StiExportFormat.Excel2007, stream); saveFileDialog.DefaultExt = ".xlsx"; break; case "Text": report.ExportDocument(StiExportFormat.Text, stream); saveFileDialog.DefaultExt = ".txt"; break; case "Image": report.ExportDocument(StiExportFormat.ImagePng, stream); saveFileDialog.DefaultExt = ".png"; break; } saveFileDialog.FileName = report.ReportName; if (saveFileDialog.ShowDialog() == DialogResult.OK) { // Save to Local Storage using (var fileStream = File.Create(saveFileDialog.FileName)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } } MessageBox.Show("The export action is complete.", "Export Report"); }
public virtual byte[] GenerateReport() { try { var stream = new MemoryStream(); ReportFile.ExportDocument(StiExportFormat.Pdf, stream, new StiPdfExportSettings { AllowEditable = StiPdfAllowEditable.No, EmbeddedFonts = true, StandardPdfFonts = true, UseUnicode = true, // PdfACompliance = true, ExportRtfTextAsImage = true, ImageResolution = 400, ImageQuality = 1000, UserAccessPrivileges = StiUserAccessPrivileges.PrintDocument }); return(stream.ToArray()); } catch (Exception ex) { Logger.ErrorException(ex.Message, ex); throw ex; } }
public ActionResult GetOutputDocument(string id, string name) { var gId = new Guid(id); var pp = db.PP_Protocols.FirstOrDefault(x => x.Id == gId); if (pp != null) { var file = FileHelper.GetProtocolAttachFile(db, gId); if (file != null && file.Exists) { using (FileStream streamFile = file.OpenRead()){ var bytes = GetByte(streamFile); return(File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Name)); } } } StiReport report = new StiReport(); report.Load(Server.MapPath("../Reports/PriceProject/Protocol.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables["protocolId"].ValueObject = new Guid(id); report.Render(false); var stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Word2007, stream); stream.Position = 0; return(File(stream, "application/word", string.Format("Протокол {0}.docx", name))); }
public FileStreamResult ExportFilePdf(Guid id) { string name = "Документ.pdf"; StiReport report = new StiReport(); try { report.Load(Server.MapPath("~/Reports/Pharmacological/OutcomeDoc.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } // имя и должность эксперта var currentEmployee = UserHelper.GetCurrentEmployee(); var employeeName = currentEmployee.FullName; var employeePosition = currentEmployee.Position.Name; report.Dictionary.Variables["EmployeeName"].ValueObject = employeeName; report.Dictionary.Variables["EmployeePosition"].ValueObject = employeePosition; report.Dictionary.Variables["ExpertisePharmacologicalFinalDocId"].ValueObject = id; report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex:" + ex.Message + " \r\nstack:" + ex.StackTrace); } var stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; return(File(stream, "application/pdf", name)); }
//public JsonResult CheckAndUploadHistoryFile(string code = null, string path = null, bool saveMetadata = false, string originFileId = null,string fileTypeCode) //{ // var currentEmployeeGuid = UserHelper.GetCurrentEmployee().Id; // using (var db = new ncelsEntities()) // { // db.FileLinks.FirstOrDefault(x=>x.) // } //} public FileStreamResult ExportFile(Guid id) { string name = "Документ.pdf"; StiReport report = new StiReport(); report.Load(Server.MapPath("~/Reports/DrugDeclaration/OutcomeDocCopy.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } // имя и должность эксперта var currentEmployee = UserHelper.GetCurrentEmployee(); var employeeName = currentEmployee.FullName; var employeePosition = currentEmployee.Position.Name; report.Dictionary.Variables["EmployeeName"].ValueObject = employeeName; report.Dictionary.Variables["EmployeePosition"].ValueObject = employeePosition; report.Dictionary.Variables["DrugPrimaryFinalDocumentId"].ValueObject = id; report.Render(false); var stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; return(File(stream, "application/pdf", name)); }
public ActionResult ActExportFilePdf(Guid id) { string name = "Акт выполненных работ.pdf"; StiReport report = new StiReport(); try { report.Load(Server.MapPath("~/Reports/Mrts/OBK/1c/ObkCertificateOfCompletion.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables["AssessmentDeclarationId"].ValueObject = id; report.Dictionary.Variables["ContractId"].ValueObject = expRepo.GetAssessmentDeclaration(id).ContractId; report.Dictionary.Variables["ValueAddedTax"].ValueObject = expRepo.GetValueAddedTax(); var totalCount = expRepo.GetContractPrice(expRepo.GetAssessmentDeclaration(id).ContractId); report.Dictionary.Variables["TotalCount"].ValueObject = totalCount; var priceText = RuDateAndMoneyConverter.CurrencyToTxtTenge(Convert.ToDouble(totalCount), false); report.Dictionary.Variables["TotalCountText"].ValueObject = priceText; report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace); } var stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; return(File(stream, "application/pdf", name)); }
private static string ConvertToImage(string name) { StiReport report = new StiReport(); report.Load(name); if (report.Dictionary.Variables.Contains("EmployeeId")) { report.Dictionary.Variables["EmployeeId"].Value = _currentEmployeeId; } foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = _connectionString; } Thread.CurrentThread.CurrentCulture = CultureInfo.DefaultThreadCurrentCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.DefaultThreadCurrentUICulture; report.Render(false); MemoryStream stream = new MemoryStream(); report.ExportDocument(StiExportFormat.ImagePng, stream); stream.Position = 0; var str = Convert.ToBase64String(stream.GetBuffer()); return(str); }
public ActionResult ExpDocumentExportFilePdf(string productSeriesId, Guid id) { var db = new ncelsEntities(); string name = "Заключение о безопасности и качества.pdf"; StiReport report = new StiReport(); try { report.Load(Server.MapPath("~/Reports/Mrts/OBKExpDocument.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables["StageExpDocumentId"].ValueObject = Convert.ToInt32(productSeriesId); report.Dictionary.Variables["AssessmentDeclarationId"].ValueObject = id; report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace); } var stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; return(File(stream, "application/pdf", name)); }
private static Stream ExportWithoutShow(StiReport stiReport, StiExportFormat exportFormat, bool useReturnStream) { stiReport.Render(false); if (stiReport.AutoLocalizeReportOnRun) { LocalizeReport(stiReport, Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName); } // ReSharper disable AccessToStaticMemberViaDerivedType var exportingFileName = Path.ChangeExtension(GetReportFileName(stiReport), WebReportManager.GetFileExtension(exportFormat)); // ReSharper restore AccessToStaticMemberViaDerivedType var stream = new MemoryStream(); stiReport.ExportDocument(exportFormat, stream); stream.Position = 0; if (!useReturnStream) { PageHelper.DownloadFile(stream, exportingFileName, HttpContext.Current.Response); } else { return(stream); } return(null); }
public FileStreamResult ShowPdfLetter(string ides) { List <Guid> list = new List <Guid>(); if (ides != null && !ides.Equals("")) { var arr = ides.Split(','); foreach (var temp in arr) { list.Add(Guid.Parse(temp)); } } var letterList = repository.LetterList(list); StiReport report = new StiReport(); report.Load(Server.MapPath("../Reports/Mrts/OBK/OBKDefectiveProducts.mrt")); report.RegBusinessObject("ZBKList", letterList.ToList()); report.RegBusinessObject("Organ", new { name = "РГП на ПХВ «Национальный центр экспертизы лекарственных средств, изделий медицинского назначения и медицинской техники» МЗ РК" }); report.Compile(); report.Render(false); var stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; return(new FileStreamResult(stream, "application/pdf")); }
public ActionResult PrintMotivationRefuse(Guid declarationId, bool view) { StiReport report = new StiReport(); try { report.Load(Server.MapPath("~/Reports/Mrts/OBK/ObkOPMotivRefus.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables[0].ValueObject = declarationId; report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace); } var stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; string name = "Мотивированный отказ" + DateTime.Now.ToString() + ".pdf"; if (view) { return(new FileStreamResult(stream, "application/pdf")); } else { return(File(stream, "application/pdf", name)); } }
public ActionResult ExpDocumentMotivRefusExportFilePdf(Guid id) { string name = "Уведомление о мотивированном отказе.pdf"; StiReport report = new StiReport(); try { report.Load(Server.MapPath("~/Reports/Mrts/OBK/ObkExpDocumentMotivRefus.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables["AssessmentDeclarationId"].ValueObject = id; report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace); } var stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; return(File(stream, "application/pdf", name)); }
private void buttonExportClick(object sender, EventArgs e) { var report = new StiReport(); report.ReportCacheMode = StiReportCacheMode.On; report.RenderedPages.CanUseCacheMode = true; report.RenderedPages.CacheMode = true; report.RenderedPages.Clear(); report.ReportUnit = StiReportUnitType.HundredthsOfInch; var tempReport = new StiReport(); for (int index = 0; index < 30; index++) { using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ExportManyFilesToOneBigPDF.MasterDetailSubdetail.mdc")) { tempReport.LoadDocument(stream); } foreach (StiPage page in tempReport.RenderedPages) { page.Report = tempReport; page.Guid = Guid.NewGuid().ToString().Replace("-", ""); report.RenderedPages.Add(page); } } report.ExportDocument(StiExportFormat.Pdf, "d:\\1.pdf"); }
public FileStreamResult ExportFile() { StiReport report = new StiReport(); report.Load(Server.MapPath("../Reports/InDocList.mrt")); var currentEmployee = UserHelper.GetCurrentEmployee(); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } if (report.Dictionary.Variables.Contains("OrganizationId")) { report.Dictionary.Variables["OrganizationId"].ValueObject = currentEmployee.OrganizationId; } report.Dictionary.Variables["CreatedUserId"].ValueObject = currentEmployee.Position.Name.ToLower() == "руководитель"?(Guid?)null: currentEmployee.Id; report.Render(false); var stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Excel, stream); stream.Position = 0; return(File(stream, "application/excel", "входящие.xls")); }
/// <summary> /// 打印公共方法 /// </summary> /// <param name="reportName"></param> /// <param name="dv">数据视图</param> /// <returns></returns> public void DoPrint(string reportName, DataView dv) { string reportPath = startPath + @"\Reports\" + reportName + ".mrt"; ////报表文件是否存在 if (!System.IO.File.Exists(reportPath)) { TXMessageBoxExtensions.Info("报表文件丢失!"); return; } this.stiReport = new StiReport(); this.stiReport.Load(reportPath); this.stiReport.RegData(reportName, dv); this.stiReport.Compile(); this.stiReport.Render(); string pdfPath = string.Empty; string rootPath = startPath + @"\Reports\printPdf_temp\"; MyCommon.DeleteAndCreateEmptyDirectory(rootPath, true); pdfPath = rootPath + reportName + ".pdf"; stiReport.ExportDocument(StiExportFormat.Pdf, pdfPath); frmReports = new frmReport(pdfPath); frmReports.ShowDialog(); }
private static string ConvertToHtml(string name, params string[] param) { StiReport report = new StiReport(); report.Load(name); int i = 0; if (report.Dictionary.Variables.Contains("EmployeeId")) { report.Dictionary.Variables["EmployeeId"].Value = _currentEmployeeId; } foreach (var item in param.Where(x => !string.IsNullOrEmpty(x) && x != "undefined")) { report.Dictionary.Variables[i++].Value = item; } foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = _connectionString; } Thread.CurrentThread.CurrentCulture = CultureInfo.DefaultThreadCurrentCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.DefaultThreadCurrentUICulture; report.Render(false); MemoryStream stream = new MemoryStream(); report.ExportDocument(StiExportFormat.HtmlTable, stream); stream.Position = 0; var sr = new StreamReader(stream); var str = sr.ReadToEnd().Replace("Stimulsoft Reports - Demo Version", string.Empty); return(str); }
private void button7_Click(object sender, System.EventArgs e) { StiReport report1 = GetReport("SimpleList.mrt"); StiReport report2 = GetReport("SimpleGroup.mrt"); StiReport report3 = GetReport("Master-Detail.mrt"); StiReport report = new StiReport(); report.Render(false); report.RenderedPages.Clear(); foreach (StiPage page in report1.RenderedPages) { report.RenderedPages.Add(page); } foreach (StiPage page in report2.RenderedPages) { report.RenderedPages.Add(page); } foreach (StiPage page in report3.RenderedPages) { report.RenderedPages.Add(page); } report.ExportDocument(StiExportFormat.Pdf, "d:\\file.pdf"); }
static void Main(string[] args) { Console.WriteLine("Hello!"); // How to Activate //Stimulsoft.Base.StiLicense.Key = "6vJhGtLLLz2GNviWmUTrhSqnO..."; //Stimulsoft.Base.StiLicense.LoadFromFile("license.key"); //Stimulsoft.Base.StiLicense.LoadFromStream(stream); Console.Write("Loading report and data... "); var report = new StiReport(); report.Load($"{ReportsDirectory}/TwoSimpleLists.mrt"); Console.WriteLine("OK"); Console.Write("Rendering and exporting a report... "); var exportFilePath = $"{ReportsDirectory}/TwoSimpleLists_{DateTime.Now.ToString("yyyy-dd-MM_HH-mm-ss")}.pdf"; report.Render(false); report.ExportDocument(StiExportFormat.Pdf, exportFilePath); Console.WriteLine("OK"); Console.WriteLine("Exported to:"); Console.WriteLine(Path.GetFullPath(exportFilePath)); Console.ReadKey(); }
public FileStreamResult ExportProtocol(Guid id) { StiReport report = new StiReport(); var model = new DrugAnaliticRepository().GetExpExpertiseStageDosage(id); var applicant = new EmployeesRepository().GetById(model.EXP_ExpertiseStage.EXP_DrugDeclaration.OwnerId); report.Load(Server.MapPath("../Reports/DrugDeclaration/AnaliseProtocol.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } if (report.Dictionary.Variables.Contains("DosageStageId")) { report.Dictionary.Variables["DosageStageId"].ValueObject = id; } if (report.Dictionary.Variables.Contains("ApplicationName")) { report.Dictionary.Variables["ApplicationName"].ValueObject = applicant.DisplayName; } report.Render(false); var stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; var reportname = "Протокол_" + DateTime.Now.ToString("yyyy-mm-dd hh.mm.ss") + ".pdf"; return(File(stream, "application/pdf", reportname)); }
public ActionResult GetContractTemplatePdf(Guid id) { var db = new ncelsEntities(); string name = "Договор_на_проведение_оценки_безопасности_и_качества.pdf"; StiReport report = new StiReport(); try { report.Load(obkRepo.GetContractTemplatePath(id));//(Server.MapPath("~/Reports/Mrts/OBK/ObkContractDec.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables["ContractId"].ValueObject = id; var price = new OBKContractRepository().GetPriceCount(id); report.Dictionary.Variables["PriceCount"].ValueObject = price; var priceText = RuDateAndMoneyConverter.ToTextTenge(Convert.ToDouble(price), false); report.Dictionary.Variables["PriceCountName"].ValueObject = priceText; report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace); } Stream stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Word2007, stream); stream.Position = 0; Aspose.Words.Document doc = new Aspose.Words.Document(stream); try { var signData = db.OBK_ContractSignedDatas.Where(x => x.ContractId == id).FirstOrDefault(); if (signData != null && signData.ApplicantSign != null && signData.CeoSign != null) { doc.InserQrCodesToEnd("ApplicantSign", signData.ApplicantSign); doc.InserQrCodesToEnd("CeoSign", signData.CeoSign); } } catch (Exception ex) { } var file = new MemoryStream(); doc.Save(file, Aspose.Words.SaveFormat.Pdf); file.Position = 0; //return new FileStreamResult(stream, "application/pdf"); return(File(file, "application/pdf", name)); }
public ActionResult GetAdditionalContractTemplatePdf(Guid id, bool?isStream, string contractAdditionTypeCode) { var db = new ncelsEntities(); StiReport report = new StiReport(); try { report.Load(obkRepo.GetContractAdditionalTemplatePath(id, contractAdditionTypeCode.Trim()));//(Server.MapPath("~/Reports/Mrts/OBK/ObkContractDec.mrt")); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } report.Dictionary.Variables["addContractNumber"].ValueObject = id; report.Render(false); } catch (Exception ex) { LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace); } Stream stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Word2007, stream); stream.Position = 0; Aspose.Words.Document doc = new Aspose.Words.Document(stream); try { var signData = db.OBK_ContractSignedDatas.Where(x => x.ContractId == id).FirstOrDefault(); if (signData != null && signData.ApplicantSign != null && signData.CeoSign != null) { doc.InserQrCodesToEnd("ApplicantSign", signData.ApplicantSign); doc.InserQrCodesToEnd("CeoSign", signData.CeoSign); } } catch (Exception ex) { } var file = new MemoryStream(); doc.Save(file, Aspose.Words.SaveFormat.Pdf); file.Position = 0; if (isStream != null && isStream.Value) { return(new FileStreamResult(file, "application/pdf")); } else { return(File(file, "application/pdf", "")); } }
public ActionResult DepartamentDetails(string name, DateTime?dateStart, DateTime?dateEnd, string departmentId, string lsPriceComparisonItem1, string lsPriceComparisonItem2) { StiReport report = new StiReport(); report.Load(Server.MapPath("../Reports/List/" + name)); foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>()) { data.ConnectionString = UserHelper.GetCnString(); } if (!dateStart.HasValue) { dateStart = DateTime.Now.AddMonths(-1); } if (!dateEnd.HasValue) { dateEnd = DateTime.Now; } if (report.Dictionary.Variables.Contains("DateStart")) { report.Dictionary.Variables["DateStart"].ValueObject = dateStart; } if (report.Dictionary.Variables.Contains("DateEnd")) { report.Dictionary.Variables["DateEnd"].ValueObject = dateEnd; } if (report.Dictionary.Variables.Contains("DepartmentId") && !string.IsNullOrEmpty(departmentId)) { report.Dictionary.Variables["DepartmentId"].Value = departmentId; //UserHelper.GetDepartment().Id.ToString(); } if (report.Dictionary.Variables.Contains("UserId")) { report.Dictionary.Variables["UserId"].Value = UserHelper.GetCurrentEmployee().Id.ToString(); } if (report.Dictionary.Variables.Contains("OrganizationId")) { report.Dictionary.Variables["OrganizationId"].ValueObject = UserHelper.GetCurrentEmployee().OrganizationId; } if (report.Dictionary.Variables.Contains("PriceProjectId1") && !string.IsNullOrEmpty(lsPriceComparisonItem1)) { report.Dictionary.Variables["PriceProjectId1"].ValueObject = Guid.Parse(lsPriceComparisonItem1); } if (report.Dictionary.Variables.Contains("PriceProjectId2") && !string.IsNullOrEmpty(lsPriceComparisonItem2)) { report.Dictionary.Variables["PriceProjectId2"].ValueObject = Guid.Parse(lsPriceComparisonItem2); } report.Render(false); var stream = new MemoryStream(); report.ExportDocument(StiExportFormat.HtmlDiv, stream); stream.Position = 0; using (var reader = new StreamReader(stream, Encoding.UTF8)) { return(Content(reader.ReadToEnd())); } }
private void button1_Click(object sender, System.EventArgs e) { StiReport report = new StiReport(); report.RegData(dataSet1); report.Load("..\\..\\Reports\\" + (string)lbReports.SelectedItem + ".mrt"); report.Render(false); string file = (string)lbReports.SelectedItem + "."; if (rbPdf.Checked) { file += "pdf"; report.ExportDocument(StiExportFormat.Pdf, file); System.Diagnostics.Process.Start(file); } else if (rbHtml.Checked) { file += "html"; report.ExportDocument(StiExportFormat.HtmlTable, file); System.Diagnostics.Process.Start(file); } else if (rbXls.Checked) { file += "xls"; report.ExportDocument(StiExportFormat.Excel, file); System.Diagnostics.Process.Start(file); } else if (rbTxt.Checked) { file += "txt"; report.ExportDocument(StiExportFormat.Text, file); System.Diagnostics.Process.Start(file); } else if (rbRtf.Checked) { file += "rtf"; report.ExportDocument(StiExportFormat.RtfTable, file); System.Diagnostics.Process.Start(file); } }
private void buttonExport_Click(object sender, RoutedEventArgs e) { StiReport report = new StiReport(); report.RegData(dataSet1); report.Load("..\\" + ((ListBoxItem)lbReports.SelectedItem).Content as string + ".mrt"); report.RenderWithWpf(false); string file = ((ListBoxItem)lbReports.SelectedItem).Content as string + "."; if (rbPdf.IsChecked.GetValueOrDefault()) { file += "pdf"; report.ExportDocument(StiExportFormat.Pdf, file); System.Diagnostics.Process.Start(file); } else if (rbHtml.IsChecked.GetValueOrDefault()) { file += "html"; report.ExportDocument(StiExportFormat.HtmlTable, file); System.Diagnostics.Process.Start(file); } else if (rbXls.IsChecked.GetValueOrDefault()) { file += "xls"; report.ExportDocument(StiExportFormat.Excel, file); System.Diagnostics.Process.Start(file); } else if (rbTxt.IsChecked.GetValueOrDefault()) { file += "txt"; report.ExportDocument(StiExportFormat.Text, file); System.Diagnostics.Process.Start(file); } else if (rbRtf.IsChecked.GetValueOrDefault()) { file += "rtf"; report.ExportDocument(StiExportFormat.RtfTable, file); System.Diagnostics.Process.Start(file); } }
public static MemoryStream GetReportPdf(Guid id, ncelsEntities db) { StiReport report = GetReport(id, db); report.Render(false); var stream = new MemoryStream(); report.ExportDocument(StiExportFormat.Pdf, stream); stream.Position = 0; return(stream); }
/// <summary> /// SaveAs /// </summary> /// <param name="type">None = 0, Pdf = 1, Xps = 2, HtmlTable = 3, HtmlSpan = 4, Rtf = 5, RtfTable = 5, RtfFrame = 6, RtfWinWord = 7, RtfTabbedText = 8, RtfMode1 = 6, RtfMode2 = 7, RtfMode3 = 8, Text = 9, Excel = 10, ExcelXml = 11, Excel2007 = 12, Word2007 = 13, Xml = 14, Csv = 15, ImageGif = 16, ImageBmp = 17, ImagePng = 18, ImageTiff = 19, ImageJpeg = 20, ImageEmf = 21, Mht = 22, Dbf = 23, Html = 24</param> /// <param name="fileName">The file for a rendered report export.</param> /// <param name="openDocument">If is true that open exported document.</param> public void SaveAs(int type, string fileName, bool openDocument) { StiExportFormat exportFormat = (StiExportFormat)type; report.ExportDocument(exportFormat, fileName); if (openDocument) { System.Diagnostics.Process.Start(fileName); } }
private void GetReportStimulsoft(string xmltext) { try { global::Stimulsoft.Base.StiLicense.Key = "6vJhGtLLLz2GNviWmUTrhSqnOItdDwjBylQzQcAOiHn6T1QyRLNg9ob5/AoMlKpfD06YlnbaK+apLpkPGy58/hwEVP" + "JFLu2ahVXhoRuQ6rqqr2dmiE1sVk+HoFVWz15idNVym7+T9lWeQUbd8FI/gJCJVd9zEPTA3yfhJpZx1s2ZXumj8n0P" + "FAahfNUT8qlOCjmeZ2admzNVdRlTcH/uN3Ms51HIix2g7C0cuupRUJOYBM36vuEOSXp1B07rV6NwU0iACQHiUQ/Y4c" + "Gx2SVSiZdVGKY4hVgfWDeHCTr5MaqXWo6p6EOSVB0bM3Y421Tv2qitJ3Utj/zcYDVbW5nSwhahuygT3ZCY5iftNvzw" + "gwIEjS2LnGME3QghFEWnC04Vld/zxSQyxGcMyK7/03VkqfHlBN8jIVHEjFT0YQUhPAbiC2pfFKa6MIgJqvXTJDNQgn" + "6y8c9RwfwPdC6PJjL/9c0kEpaG198A2R0mVZNzjvXHpG/mEUIeWN2zmWJMJNm5fgySzlV9BLUwKlM1jpv4rQcf5MR/" + "/ZONmx6qqmjYcSASNmW/ICM72fwSsJE7F7chh1Q0VMkOe6sriXsdhkqC3lV5yTifwCK3JYM9i08XF1HXDMeNF6/tss" + "wdMaaCVQDGJJp3stA8KlSyAeLFvRo5uMFl/5vvCuK3lV275SRgStTvS4uAu2yWIkUMnxMey6mZ"; String sPath = Path.GetDirectoryName(this.GetType().Assembly.Location); sPath = sPath + @"/Report/OVReportMasivo.mrt"; XmlDocument xml = new XmlDocument(); xml.LoadXml(xmltext); StiReport rep = StiReport.CreateNewReport(); MemoryStream stream = new MemoryStream(); rep.Load(sPath); rep.Dictionary.Databases.Clear(); var ds = ConvertXMLToDataSet(xml.InnerXml); rep.Dictionary.DataSources.Clear(); //refrescar reporte con campo nuevo rep.RegData(ds); rep.Dictionary.Synchronize(); //refrescar reporte con campo nuevo rep.Render(); DateTime now = DateTime.Now; string pdfName = now.ToString("yyyyMMddTHHmmssZ") + "OVReportMasivo.pdf"; //rep.ExportDocument(StiExportFormat.Pdf, stream); //intento de abrirlo pdf en memoria, pero no funciono rep.ExportDocument(StiExportFormat.Pdf, "C:\\Windows\\Temp\\" + pdfName); sPath = Path.GetDirectoryName(this.GetType().Assembly.Location); //string filename = "OVReportMasivo.pdf"; System.Diagnostics.Process.Start("C:\\Windows\\Temp\\" + pdfName); } catch (Exception e) { Application.SBO_Application.StatusBar.SetText(e.Message + " ** Trace: " + e.StackTrace, SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Error); log.AddLog(e.Message + " ** Trace: "); } finally { } }
public static void ExportInfo(byte exportType, StiReport report) { using (MemoryStream ms = new MemoryStream()) { string fileName = "rep"; switch (exportType) { case 0:// "pdf" report.ExportDocument(StiExportFormat.Pdf, HttpContext.Current.Server.MapPath(string.Format("~/App_Data/Report/Tmp/{0}.Pdf", fileName))); report.ExportDocument(StiExportFormat.Pdf, ms); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.pdf", fileName)); HttpContext.Current.Response.ContentType = "application/pdf"; break; case 1:// "jpeg" report.ExportDocument(StiExportFormat.ImageJpeg, HttpContext.Current.Server.MapPath(string.Format("~/App_Data/Report/Tmp/{0}.jpeg", fileName))); report.ExportDocument(StiExportFormat.ImageJpeg, ms); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.jpeg", fileName)); HttpContext.Current.Response.ContentType = "application/ImageJpeg"; break; case 2: // "html": report.ExportDocument(StiExportFormat.Html, HttpContext.Current.Server.MapPath(string.Format("~/App_Data/Report/Tmp/{0}.html", fileName))); report.ExportDocument(StiExportFormat.Html, ms); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.html", fileName)); HttpContext.Current.Response.ContentType = "application/html"; break; case 3: // "xls": report.ExportDocument(StiExportFormat.Excel, HttpContext.Current.Server.MapPath(string.Format("~/App_Data/Report/Tmp/{0}.xls", fileName))); report.ExportDocument(StiExportFormat.Excel, ms); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", fileName)); HttpContext.Current.Response.ContentType = "application/xls"; break; } HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.End(); } }
private void ShowReport(bool isPrint, RepReport report) { System.IO.MemoryStream stream = null; System.Data.DataSet ds; string str; string str2; RepReportTemplate template; System.IO.FileInfo info; string str3; DbFileFormat format; if (report.PackedResult != null) { stream = new System.IO.MemoryStream(report.PackedResult); } GZipStream stream2 = null; if (stream != null) { stream2 = new GZipStream(stream, CompressionMode.Decompress); } if (report.IsSimpleTable || report.IsTxt) { if (isPrint) { System.Windows.Forms.MessageBox.Show("Невозможно распечатать данный тип отчета:" + System.Environment.get_NewLine() + report.ReportTemplateName); return; } ds = null; if (report.PlannedDate != AIS.SN.Model.Constants.NullDate) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); ds = (System.Data.DataSet) formatter.Deserialize(stream2); } else { ds = report.ds; } if (stream2 != null) { stream2.Close(); } if (((ds.Tables.get_Count() < 2) || (ds.Tables.get_Item(0).Rows.get_Count() == 0)) || (ds.Tables.get_Item(1).Rows.get_Count() == 0)) { System.Windows.Forms.MessageBox.Show("Отчет пуст:" + System.Environment.get_NewLine() + report.ReportTemplateName); return; } str = ds.Tables.get_Item(0).Rows.get_Item(0).get_Item("filename").ToString(); try { str2 = str.Substring(0, str.LastIndexOf(@"\")); str = str.Substring((int) (str.LastIndexOf(@"\") + 1)); } catch (System.Exception) { str2 = @"C:\"; str = "file.dbf"; } if (System.IO.Directory.Exists(str2)) { this.sfdDBF.set_InitialDirectory(str2); } this.sfdDBF.set_FileName(str); this.sfdDBF.set_DefaultExt(report.IsTxt ? ((string) "txt") : ((string) "dbf")); template = RepReportTemplate.FindById(report.ReportTemplateId); if (this.sfdDBF.ShowDialog(this) != System.Windows.Forms.DialogResult.OK) { return; } str = this.sfdDBF.get_FileName(); if (System.IO.File.Exists(str) && !template.IsAppending) { System.IO.File.Delete(str); } info = new System.IO.FileInfo(str); System.Guid guid = System.Guid.NewGuid(); ds.Tables.get_Item(1).set_TableName('A' + guid.ToString().Substring(0, 7).ToUpper()); str2 = info.get_DirectoryName() + ((info.get_DirectoryName() == "") ? ((string) "") : ((string) @"\")); if (!report.IsSimpleTable) { goto Label_04FF; } str3 = str; if (template.IsAppending && info.get_Exists()) { info.MoveTo(str2 + ds.Tables.get_Item(1).get_TableName() + ".DBF"); } format = DbFileFormat.dBase3; string str5 = ds.Tables.get_Item(0).Rows.get_Item(0).get_Item("fileformat").ToString(); if (str5 != null) { if (str5 == "dBase3") { format = DbFileFormat.dBase3; } else if (str5 == "dBase4") { format = DbFileFormat.dBase4; } else if (str5 == "dBase5") { format = DbFileFormat.dBase5; } } } else { System.IO.MemoryStream stream3 = new System.IO.MemoryStream(); byte[] buffer = new byte[0x400]; while (true) { int num = stream2.Read(buffer, 0, 0x400); if (num == 0) { break; } stream3.SetLength((long) (stream3.get_Length() + num)); stream3.Write(buffer, 0, num); } StiReport report2 = new StiReport(); stream3.set_Position((long) 0L); report2.LoadDocument((System.IO.Stream) stream3); if (report.IsExcel) { this.sfdExcel.set_FileName("Document " + ((long) report.Id).ToString()); this.sfdExcel.set_Filter("Excel Worksheets|*.xls"); this.sfdExcel.set_DefaultExt(".xls"); if (this.sfdExcel.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { StiExcelExportSettings settings = new StiExcelExportSettings { ExportPageBreaks = false, UseOnePageHeaderAndFooter = true }; report2.ExportDocument(StiExportFormat.Excel, this.sfdExcel.get_FileName(), settings); } return; } if (isPrint) { report2.Print(false); return; } report2.Show(false); return; } string tableColumns = null; if (ds.Tables.get_Item(0).Columns.Contains("columnlist")) { tableColumns = ds.Tables.get_Item(0).Rows.get_Item(0).get_Item("columnlist").ToString(); } DBF.WriteToFile((System.Data.DataTable) ds.Tables.get_Item(1), info.get_DirectoryName(), ds.Tables.get_Item(1).get_TableName(), format, false, template.IsAppending, tableColumns); if (info.get_Name().ToUpper().LastIndexOf(".DBF") >= 0) { str = str2 + info.get_Name(); } else { str = str2 + info.get_Name() + ".DBF"; } info = new System.IO.FileInfo(str2 + ds.Tables.get_Item(1).get_TableName() + ".DBF"); if (template.IsAppending) { info.MoveTo(str3); } else { info.MoveTo(str); } Label_04FF: if (report.IsTxt && (ds.Tables.get_Count() > 1)) { try { if (Settings.Default.ReportsExtractTxtEncoding == "ANSI-I (Windows)") { using (System.IO.FileStream stream4 = System.IO.File.Open(str, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream4, System.Text.Encoding.Default)) { foreach (System.Data.DataRow row in ds.Tables.get_Item(1).Rows) { writer.WriteLine(row.get_Item(0)); } writer.Close(); stream4.Close(); } return; } } using (System.IO.FileStream stream5 = System.IO.File.Open(str, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) { using (System.IO.StreamWriter writer2 = new System.IO.StreamWriter(stream5, System.Text.Encoding.GetEncoding(0x362))) { foreach (System.Data.DataRow row2 in ds.Tables.get_Item(1).Rows) { writer2.WriteLine(row2.get_Item(0)); } writer2.Close(); stream5.Close(); } } } catch (System.Exception) { System.IO.File.Delete(str); throw; } } }
protected void Generate(GenerationMode generationMode, AsyncOperation asyncOp) { System.DateTime time2; System.TimeSpan span2; this.IsBusy = true; int num = 0; logger.Info("Запущена операция формирования извещений"); System.Exception ex = null; System.DateTime now = System.DateTime.Now; if (generationMode != GenerationMode.GenerateOnly) { ObjectList<NoticeNoticeTemplate> list = new ObjectList<NoticeNoticeTemplate> { this.Template }; this.Templates = list; } this.InitNoticeRenderer(); this.m_RenderedNoticeQueue.IsClosed = false; this.m_SaveRenderedNoticeQueue.IsClosed = false; this.m_RenderingNoticeQueue.IsClosed = false; this.m_ThreadExceptions.IsClosed = false; this.m_GeneratedReport = null; this.m_RenderingNoticeQueue.Clear(); this.m_RenderedNoticeQueue.Clear(); this.m_SaveRenderedNoticeQueue.Clear(); this.m_ThreadExceptions.Clear(); this.m_ProcessedNoticeCount = this.AccountListStatistics.RenderedCount; this.m_RenderThreads = null; this.m_ReportGenerationThreads = null; logger.Info("Запуск потоков"); try { this.m_RenderThreads = new System.Threading.Thread[Constants.NoticeRenderThreads]; for (int i = 0; i < this.m_RenderThreads.Length; i = (int) (i + 1)) { this.m_RenderThreads[i] = new System.Threading.Thread(new System.Threading.ThreadStart(this.RenderThread)); this.m_RenderThreads[i].Start(); logger.Info("Запуск потока рендера " + (i + 1)); } if (generationMode != GenerationMode.GenerateOnly) { this.m_ReportGenerationThreads = new System.Threading.Thread[Constants.NoticeReportGenerationThreads]; for (int j = 0; j < this.m_ReportGenerationThreads.Length; j = (int) (j + 1)) { this.m_ReportGenerationThreads[j] = new System.Threading.Thread(new System.Threading.ThreadStart(this.ReportGenerationThread)); this.m_ReportGenerationThreads[j].Start(); logger.Info("Запуск потока экспорта " + (j + 1)); } } } catch (System.OutOfMemoryException exception2) { ex = new NoticeGenerationException("Недостаточно памяти для создания потоков.", exception2); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } catch (System.ApplicationException exception3) { ex = new NoticeGenerationException("Ошибка при выполнении запроса в базу данных для получения константы", exception3); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } catch (System.Data.SqlClient.SqlException exception4) { ex = new NoticeGenerationException("Ошибка при выполнении запроса в базу данных для получения константы", exception4); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } catch (System.Exception exception5) { ex = new NoticeGenerationException("Ошибка при создании потоков", exception5); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } if (Constants.MaxAccountsInGeneratingBlock > 0) { time2 = System.DateTime.Now; logger.Info("AccountCount: " + ((long) this.AccountListStatistics.AccountCount)); for (int k = 0; k < System.Math.Ceiling((decimal) (this.AccountListStatistics.AccountCount / System.Convert.ToDecimal(Constants.MaxAccountsInGeneratingBlock))); k = (int) (k + 1)) { if ((this.m_ThreadExceptions.Count > 0) || this.m_IsCancelled) { ex = null; this.m_ThreadExceptions.TryDequeue(out ex); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } foreach (NoticeNoticeTemplate template in this.Templates) { bool flag; int indexPart = (int) (k + 1); logger.Info("Получение блока извещений для пачки " + ((int) indexPart)); System.Data.DataTable table = null; do { flag = false; } while (flag && (num <= 5)); this.ReportPercentage(asyncOp); ObjectList<NoticeNotice> list2 = new ObjectList<NoticeNotice>(); logger.Info("Разбор полученного блока. Кол-во: " + ((int) table.Rows.get_Count())); foreach (System.Data.DataRow row in table.Rows) { if (!row.IsNull("renderedNoticeId") && (generationMode != GenerationMode.GenerateOnly)) { long id = (long) ((long) row.get_Item("renderedNoticeId")); NoticeRenderedNotice item = null; num = 0; do { flag = false; try { item = NoticeRenderedNotice.GetById(id); this.m_RenderedNoticeQueue.Enqueue(item); } catch (System.ApplicationException exception9) { if (exception9.InnerException is System.Data.SqlClient.SqlException) { num = (int) (num + 1); flag = true; logger.Warn("Потеря соединения. Переподключение."); } else { ex = new NoticeGenerationException("Ошибка при получении сформированного извещения из базы данных", exception9); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } } catch (System.Exception exception11) { ex = new NoticeGenerationException("Ошибка при получении сформированного извещения из базы данных", exception11); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } } while (flag && (num <= 5)); } else if (!row.IsNull("noticeId") && row.IsNull("renderedNoticeId")) { NoticeNotice notice2 = new NoticeNotice(); try { long num7 = (long) ((long) row.get_Item("noticeId")); notice2.Id = num7; notice2.Period = (System.DateTime) row.get_Item("period"); notice2.AccountId = (long) ((long) row.get_Item("accountId")); notice2.HouseHolderId = row.IsNull("houseHolderId") ? NoticeNotice.Null.Id : ((long) ((long) row.get_Item("houseHolderId"))); notice2.Barcode = row.IsNull("barcode") ? string.Empty : ((string) ((string) row.get_Item("barcode"))); } catch (System.Exception exception12) { ex = new NoticeGenerationException("Ошибка заполнении объекта извещения данными из БД", exception12); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } list2.Add(notice2); } } table.Clear(); table.Dispose(); this.ReportPercentage(asyncOp); if (list2.get_Count() > 0) { logger.Info("Получение данных для блока извещений из " + ((int) list2.get_Count())); System.Data.DataTable table2 = null; num = 0; do { flag = false; try { table2 = NoticeNotice.GetHeader(this.AreaId, this.Adapter.Filter.Period.Value, indexPart, template.Id); } catch (System.ApplicationException exception13) { if (exception13.InnerException is System.Data.SqlClient.SqlException) { num = (int) (num + 1); flag = true; logger.Warn("Потеря соединения. Переподключение."); } else { ex = new NoticeGenerationException("Ошибка при получении заголовков для блока извещений", exception13); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } } catch (System.Exception exception15) { ex = new NoticeGenerationException("Ошибка при получении заголовков для блока извещений", exception15); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } } while (flag && (num <= 5)); table2.set_TableName("header"); this.ReportPercentage(asyncOp); if ((this.m_ThreadExceptions.Count > 0) || this.m_IsCancelled) { ex = null; this.m_ThreadExceptions.TryDequeue(out ex); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } System.Data.DataSet set = null; num = 0; do { flag = false; try { set = NoticeNotice.GetReport(this.AreaId, this.Adapter.Filter.Period.Value, indexPart, template.Sql, template.Id); if ((this.AdditionDataTable != null) && (set != null)) { set.Tables.Add(this.AdditionDataTable); } } catch (System.ApplicationException exception16) { if (exception16.InnerException is System.Data.SqlClient.SqlException) { num = (int) (num + 1); flag = true; logger.Warn("Потеря соединения. Переподключение."); } else { ex = new NoticeGenerationException("Ошибка при получении данных для блока извещений", exception16); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } } catch (System.Exception exception18) { ex = new NoticeGenerationException("Ошибка при получении данных для блока извещений", exception18); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } } while (flag && (num <= 5)); set.Tables.get_Item(0).set_TableName("pays"); set.Tables.get_Item(1).set_TableName("counter"); for (int m = 2; m < set.Tables.get_Count(); m = (int) (m + 1)) { int num15 = (int) (m - 1); set.Tables.get_Item(m).set_TableName("data" + ((int) num15).ToString()); } if (template.IdentityName == "Счет на оплату Ульяновск вариант 3") { if (set.Tables.get_Count() > 2) { set.Tables.get_Item(2).set_TableName("organizations"); } if (set.Tables.get_Count() > 3) { set.Tables.get_Item(3).set_TableName("rates"); } } logger.Info("Отправка группы извещений {0} на рендер", indexPart); this.m_RenderingNoticeQueue.IsWaiting = true; foreach (NoticeNotice notice3 in list2) { System.Data.DataTable headerTable = table2.Clone(); foreach (System.Data.DataRow row2 in table2.Rows) { bool flag2 = false; foreach (System.Data.DataRow row3 in set.Tables.get_Item(0).Rows) { if (((long) row3.get_Item("id")) == notice3.Id) { flag2 = true; break; } } if (!flag2) { break; } if (((long) row2.get_Item("id")) == notice3.Id) { headerTable.ImportRow(row2); break; } } RenderingNotice notice4 = new RenderingNotice(notice3, headerTable, set.Copy(), template.Template, template.Id); this.m_RenderingNoticeQueue.Enqueue(notice4); logger.Info("Отправлено на рендер " + ((long) notice3.Id)); this.ReportPercentage(asyncOp); } table2.Clear(); table2.Dispose(); set.Clear(); set.Dispose(); this.m_RenderingNoticeQueue.IsWaiting = false; this.m_RetreivedNoticeBlocksCount = (int) (this.m_RetreivedNoticeBlocksCount + 1); } this.ReportPercentage(asyncOp); if (this.m_RetreivedNoticeBlocksCount >= Constants.MaxRenderingBlocks) { logger.Info("Достигнуто максимальное количество одновременно обрабатываемых блоков"); while (true) { if (((this.m_SaveRenderedNoticeQueue.Count == 0) && (this.m_RenderingNoticeQueue.Count == 0)) && (this.m_RenderingNoticeCount == 0)) { logger.Info("Очереди обработаны."); this.m_RetreivedNoticeBlocksCount = 0; continue; } this.SaveRenderedNotices(asyncOp, now); this.ReportPercentage(asyncOp); if ((this.m_ThreadExceptions.Count > 0) || this.m_IsCancelled) { ex = null; this.m_ThreadExceptions.TryDequeue(out ex); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } System.Threading.Thread.Sleep(10); } } this.SaveRenderedNotices(asyncOp, now); this.ReportPercentage(asyncOp); span2 = (System.TimeSpan) (System.DateTime.Now - time2); if (span2.get_TotalMinutes() >= 3.0) { time2 = System.DateTime.Now; logger.Info("Сборка мусора"); System.GC.Collect(); } if ((this.m_ThreadExceptions.Count > 0) || this.m_IsCancelled) { ex = null; this.m_ThreadExceptions.TryDequeue(out ex); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } } } this.m_RenderingNoticeQueue.IsClosed = true; logger.Info("Ожидание и обработка очереди оставшихся отрендеренных извещений"); while (!this.m_SaveRenderedNoticeQueue.IsClosed || (this.m_SaveRenderedNoticeQueue.Count != 0)) { if (this.m_SaveRenderedNoticeQueue.Count == 0) { System.Threading.Thread.Sleep(10); } span2 = (System.TimeSpan) (System.DateTime.Now - time2); if (span2.get_TotalMinutes() >= 3.0) { time2 = System.DateTime.Now; logger.Info("Сборка мусора"); System.GC.Collect(); } this.ReportPercentage(asyncOp); if ((this.m_ThreadExceptions.Count > 0) || this.m_IsCancelled) { ex = null; this.m_ThreadExceptions.TryDequeue(out ex); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } this.SaveRenderedNotices(asyncOp, now); } } else { ex = new NoticeGenerationException("Неверное значение константы MaxAccountsInGeneratingBlock"); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } this.m_RenderedNoticeQueue.IsClosed = true; logger.Info("Ожидание завершения запущенных потоков рендеринга и экспорта"); while ((this.m_RenderingNoticeQueue.Count > 0) || (this.m_RenderingNoticeCount > 0)) { System.Threading.Thread.Sleep(10); if ((this.m_ThreadExceptions.Count > 0) || this.m_IsCancelled) { ex = null; this.m_ThreadExceptions.TryDequeue(out ex); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } this.ReportPercentage(asyncOp); } while ((this.m_RenderedNoticeQueue.Count > 0) || (this.m_ExportingNoticeCount > 0)) { System.Threading.Thread.Sleep(10); if ((this.m_ThreadExceptions.Count > 0) || this.m_IsCancelled) { ex = null; this.m_ThreadExceptions.TryDequeue(out ex); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } this.ReportPercentage(asyncOp); } span2 = (System.TimeSpan) (System.DateTime.Now - time2); if (span2.get_TotalMinutes() >= 3.0) { time2 = System.DateTime.Now; logger.Info("Сборка мусора"); System.GC.Collect(); } NoticeReport report = null; if (generationMode == GenerationMode.GenerateReport) { logger.Info("Объединение извещений в один отчёт для показа"); System.Collections.Generic.List<NoticeRenderedNotice> renderedNotices = new System.Collections.Generic.List<NoticeRenderedNotice>(); foreach (NoticeReport report2 in this.m_NoticeReports) { renderedNotices.AddRange(report2.RenderedNotices); report2.Dispose(); } report = new NoticeReport(renderedNotices); this.m_GeneratedReport = report; } if ((this.m_ThreadExceptions.Count > 0) || this.m_IsCancelled) { ex = null; this.m_ThreadExceptions.TryDequeue(out ex); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); } else { if ((this.m_NoticeCache.get_Count() > 0) && (this.m_Exporter != null)) { logger.Info("Экспорт по домам управляющих компаний"); int num9 = (int) ((this.m_Exporter.MaxPageCount * this.m_Template.AccountsInTemplate) / this.m_Template.PageCount); CachedNoticeInfoComparer comparer = new CachedNoticeInfoComparer(); try { foreach (string str in this.m_NoticeCache.Keys) { this.m_NoticeCache[str].Sort(comparer); logger.Info("Экспорт домов УК " + str); for (int n = 0; n < this.m_NoticeCache[str].get_Count(); n = (int) (n + num9)) { System.Text.StringBuilder builder = new System.Text.StringBuilder(); int num11 = this.m_NoticeCache[str].get_Count(); if (num11 != 0) { int maxPageCount = this.m_Exporter.MaxPageCount; int num13 = (int) (num11 - (n + maxPageCount)); num13 = (num13 < 1) ? ((int) 0) : num13; using (StiReport report3 = new StiReport()) { report3.IsRendered = true; report3.NeedsCompiling = false; report3.RenderedPages.Clear(); System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(System.IO.Path.Combine(this.m_Exporter.DestinationPath, str)); if (!info.get_Exists()) { info.Create(); } string file = System.IO.Path.Combine(info.get_FullName(), string.Format("{0}_{1}.pdf", str, n / num9)); for (int num14 = n; num14 < (num11 - num13); num14 = (int) (num14 + 1)) { System.IO.FileInfo info2 = new System.IO.FileInfo(this.m_NoticeCache[str].get_Item(num14).CacheFilePath); if (info2.get_Exists()) { byte[] bytes = System.IO.File.ReadAllBytes(info2.get_FullName()); StiReport report4 = new StiReport(); report4.LoadPackedDocument(bytes); report4.ReportUnit = report3.ReportUnit; foreach (StiPage page in report4.RenderedPages) { page.Report = report3; page.Guid = System.Guid.NewGuid().ToString().Replace("-", ""); report3.RenderedPages.Add(page); } if (this.m_Exporter.DualPageExportMode && ((report4.RenderedPages.get_Count() % 2) != 0)) { StiPage page2 = new StiPage(report3) { IsRendered = true, Orientation = report4.RenderedPages[0].Orientation, Guid = System.Guid.NewGuid().ToString().Replace("-", "") }; report3.RenderedPages.Add(page2); } builder.AppendLine(this.m_NoticeCache[str].get_Item(num14).FullAddress); } } report3.ExportDocument(StiExportFormat.Pdf, file); System.IO.File.WriteAllText(file + ".txt", builder.ToString()); } } } } logger.Info("Очистка дискового кэша"); System.IO.Directory.Delete(System.IO.Path.Combine(this.m_Exporter.DestinationPath, this.m_ExportCacheDirectoryName), true); } catch (System.Exception exception19) { ex = new NoticeGenerationException("Ошибка при экспорте извещений, сгруппированных по УК", exception19); this.AbortOperation(asyncOp, ex, (System.TimeSpan) (System.DateTime.Now - now)); return; } } System.TimeSpan timeSpent = (System.TimeSpan) (System.DateTime.Now - now); logger.Info("Операция успешно завершена. Время выполнения " + timeSpent.ToString()); logger.Info("Всего отрендерено: " + ((int) this.m_TotalRendered)); if (asyncOp != null) { GenerationCompletedEventArgs args = new GenerationCompletedEventArgs(timeSpent, null, false, asyncOp.get_UserSuppliedState()) { GeneratedReport = report }; asyncOp.PostOperationCompleted(this.onCompletedDelegate, args); } this.Reset(); } }
public void ReportCreated(StiReport rpt, AccountServicesJournalReportForm form, string xml) { string str; using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { rpt.ExportDocument(StiExportFormat.Pdf, (System.IO.Stream) stream); str = System.Convert.ToBase64String(stream.ToArray()); } ExchangeRequest objectWithId = (ExchangeRequest) base.ObjectWithId; try { this.MakeResponse(objectWithId, "Получение справки об оплате для единого окна", string.Empty, str, xml); } catch (System.Exception exception) { AIS.SN.UI.Messages.ShowException(this, exception); } }