public static ICollection GetFiles(bool blankLead, string templateFolder) { DirectoryInfo directoryInfo = new DirectoryInfo(templateFolder); DataTable dataTable = new DataTable(); dataTable.get_Columns().Add(new DataColumn("File", typeof(string))); dataTable.get_Columns().Add(new DataColumn("FullName", typeof(string))); dataTable.get_Columns().Add(new DataColumn("URL", typeof(string))); if (directoryInfo.get_Exists()) { if (blankLead) { DataRow dataRow = dataTable.NewRow(); dataRow.set_Item(0, Constants.Unassigned); dataTable.get_Rows().Add(dataRow); } FileSystemInfo[] files = directoryInfo.GetFiles("*.*"); if (files.Length > 0) { FileSystemInfo[] array = files; for (int i = 0; i < array.Length; i++) { FileSystemInfo fileSystemInfo = array[i]; DataRow dataRow = dataTable.NewRow(); dataRow.set_Item(0, fileSystemInfo.get_Name().ToLower()); dataRow.set_Item(1, fileSystemInfo.get_FullName()); dataRow.set_Item(2, Constants.Config.TemplateFolder + "/" + fileSystemInfo.get_Name()); dataTable.get_Rows().Add(dataRow); } } return new DataView(dataTable); } throw new CarConfigException("Template area does not exist"); }
private void CreateLog(bool useFileLog) { this.m_Logger = new ActionLog(); this.m_Logger.ExceptionLog = new ActionLog(); if (useFileLog) { string str = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), @"Система начислений за услуги ЖКХ\АРМ Печать извещений\Logs"); System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(str); if (!info.get_Exists()) { info.Create(); } this.m_Logger.FileLogName = System.IO.Path.Combine(str, "Log " + System.DateTime.Now.ToString(this.m_Logger.TimeFormatString.Replace(':', '.'), System.Globalization.CultureInfo.InvariantCulture) + ".log"); } this.m_Logger.UseFileLog = useFileLog; }
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(); } }
private void ReportGenerationThread() { Label_0000: if (((this.m_ExportingNoticeCount <= 0) && (this.m_RenderedNoticeQueue.Count == 0)) && this.m_RenderedNoticeQueue.IsClosed) { logger.Info("Поток экспорта завершил выполнение"); } else { if (this.m_RenderedNoticeQueue.Count == 0) { System.Threading.Thread.Sleep(10); } NoticeRenderedNotice notice = null; if (this.m_RenderedNoticeQueue.TryDequeue(out notice)) { System.Threading.Interlocked.Increment(ref this.m_ExportingNoticeCount); NoticeReport noticeReport = new NoticeReport(notice); lock (this.m_ReportGenerationSync) { if ((this.m_GenerationMode == GenerationMode.GenerateReport) && notice.HasResult) { this.m_NoticeReports.Add(noticeReport); } } if (((this.m_Exporter != null) && (this.m_GenerationMode == GenerationMode.GenerateAndExport)) && notice.HasResult) { logger.Info("Экспорт извещений"); try { if (this.m_Exporter.GroupingMode == NoticeGroupingMode.HouseHolder) { string houseHolderName = notice.HouseHolderName; char[] invalidFileChars = m_InvalidFileChars; for (int i = 0; i < invalidFileChars.Length; i = (int) (i + 1)) { char ch = invalidFileChars[i]; houseHolderName = houseHolderName.Replace(ch, ' '); } houseHolderName = houseHolderName.Trim(); if (!this.m_NoticeCache.ContainsKey(houseHolderName)) { this.m_NoticeCache.Add(houseHolderName, new System.Collections.Generic.List<CachedNoticeInfo>()); } System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(System.IO.Path.Combine(this.m_Exporter.DestinationPath, this.m_ExportCacheDirectoryName)); if (!info.get_Exists()) { info.Create(); } System.IO.DirectoryInfo info2 = new System.IO.DirectoryInfo(System.IO.Path.Combine(info.get_FullName(), houseHolderName)); if (!info2.get_Exists()) { info2.Create(); } string cacheFilePath = System.IO.Path.Combine(info2.get_FullName(), notice.AccountNumber); CachedNoticeInfo info3 = new CachedNoticeInfo(cacheFilePath, notice.HouseAddressName, houseHolderName, notice.AddressName, notice.StreetName, notice.HouseSortValue, notice.FlatSortValue); System.IO.File.WriteAllBytes(cacheFilePath, notice.PacketReport); this.m_NoticeCache[houseHolderName].Add(info3); } else { this.m_Exporter.Export(noticeReport); } } catch (System.Exception exception) { System.Threading.Interlocked.Decrement(ref this.m_ExportingNoticeCount); NoticeGenerationException item = new NoticeGenerationException("Ошибка при экспорте извещений", exception); this.m_ThreadExceptions.Enqueue(item); return; } } System.Threading.Interlocked.Decrement(ref this.m_ExportingNoticeCount); } goto Label_0000; } }
private void btExportPdf_Click(object sender, System.EventArgs e) { if (this.workerExportPdf.get_IsBusy()) { this.btExportPdf.set_Text("Отменяется..."); this.btExportPdf.set_Enabled(false); this.workerExportPdf.CancelAsync(); } else { NoticeNoticeTemplate template = (this.bsNoticeTemplates.get_Current() as NoticeNoticeTemplate) ?? NoticeNoticeTemplate.Null; if (this.bsNotices.get_Count() == 0) { Messages.ShowMessage("Для печати ничего не найдено"); } else if (template == NoticeNoticeTemplate.Null) { Messages.ShowMessage("Не выбран шаблон"); } else { template = ObjectWithId.FindById<NoticeNoticeTemplate>(template.Id); if (string.IsNullOrEmpty(Settings.Default.NoticesExportFolder)) { Messages.ShowMessage("Не выбран каталог выгрузки"); } else { int num = System.Convert.ToInt32(this.nudPageCount.Value); int accountsInTemplate = template.AccountsInTemplate; int pageCount = template.PageCount; int num4 = System.Convert.ToInt32(this.nudHousesPerDoc.Value); if ((accountsInTemplate == 0) || (pageCount == 0)) { Messages.ShowMessage("Не задано количество лицевых счетов на количество страниц в шаблоне"); } else { System.IO.DirectoryInfo info; int num5 = (int) ((num * accountsInTemplate) / pageCount); try { System.IO.DirectoryInfo info2 = new System.IO.DirectoryInfo(Settings.Default.NoticesExportFolder); if (!info2.get_Exists()) { info2.Create(); } info = new System.IO.DirectoryInfo(System.IO.Path.Combine(info2.get_FullName(), this.datePeriodShow.DateBegin.ToShortDateString().Replace('.', '-'))); if (!info.get_Exists()) { info.Create(); } } catch (System.Security.SecurityException) { Messages.ShowError("Убедитесь, что текущий пользователь имеет права на запись в указанный каталог."); return; } catch (System.IO.IOException exception) { Messages.ShowError("Ошибка при записи в каталог. " + System.Environment.get_NewLine() + exception.get_Message()); return; } ObjectList<NoticeNotice> noticesToBeFiltered = (ObjectList<NoticeNotice>) this.bsNotices.get_DataSource(); ObjectList<NoticeNotice> list2 = this.rbExportAccountNotices.get_Checked() ? noticesToBeFiltered : this.FilterNotices(noticesToBeFiltered, template); System.Collections.Generic.Dictionary<string, System.Collections.Generic.IList<NoticeNotice>> dictionary = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.IList<NoticeNotice>>(); foreach (NoticeNotice notice in list2) { if (!dictionary.ContainsKey(notice.HouseHolderName)) { dictionary.Add(notice.HouseHolderName, new ObjectList<NoticeNotice>()); } dictionary[notice.HouseHolderName].Add(notice); } NoticeExportPdfParams @params = new NoticeExportPdfParams { NoticeTemplate = template, PeriodDirectory = info, Notices = list2, HouseHolderNotices = dictionary, MaxNoticesPerDocument = num5, MinHouseCount = num4 }; this.set_Cursor(System.Windows.Forms.Cursors.WaitCursor); this.btExportPdf.set_Text("Отменить"); this.btnChooseExportDirectory.set_Enabled(false); this.progressBarExportPdf.set_Visible(true); this.workerExportPdf.RunWorkerAsync(@params); } } } } }
private void workerExportPdf_DoWork(object sender, DoWorkEventArgs e) { char[] chArray2; int num12; int num13; object obj2; char[] invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars(); BackgroundWorker worker = sender as BackgroundWorker; NoticeExportPdfParams @params = e.get_Argument() as NoticeExportPdfParams; ObjectList<NoticeNotice> notices = @params.Notices; int num = 0; if (this.rbExportAccountNotices.get_Checked()) { foreach (NoticeNotice notice in notices) { if (worker.get_CancellationPending()) { e.set_Cancel(true); break; } string str2 = string.IsNullOrEmpty(notice.HouseHolderName) ? ((string) "Неизвестная УК") : notice.HouseHolderName; chArray2 = invalidFileNameChars; num12 = 0; while (num12 < chArray2.Length) { char ch = chArray2[num12]; str2 = str2.Replace(ch, ' '); num12 = (int) (num12 + 1); } str2 = str2.Trim(); System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(System.IO.Path.Combine(@params.PeriodDirectory.get_FullName(), str2)); if (!info.get_Exists()) { info.Create(); } ObjectList<NoticeNotice> list2 = new ObjectList<NoticeNotice>(); list2.Add(notice); try { using (System.Data.DataTable table = NoticeNotice.GetHeader(list2, this.cbHideClosedAccounts.get_Checked(), this.cbNoticeInformation.get_Checked())) { table.set_TableName("header"); using (System.Data.DataSet set = NoticeNotice.GetReport(list2, @params.NoticeTemplate.Sql)) { if ((set.Tables.get_Count() < 2) || (set.Tables.get_Item(0).Rows.get_Count() == 0)) { continue; } bool flag = false; foreach (System.Data.DataRow row in table.Rows) { if (System.Convert.ToInt64(row.get_Item("id")) == notice.Id) { foreach (System.Data.DataRow row2 in set.Tables.get_Item(0).Rows) { if (System.Convert.ToInt64(row2.get_Item("id")) == notice.Id) { flag = true; break; } } } } if (!flag) { continue; } set.Tables.get_Item(0).set_TableName("pays"); set.Tables.get_Item(1).set_TableName("counter"); for (int i = 2; i < set.Tables.get_Count(); i = (int) (i + 1)) { num13 = (int) (i - 1); set.Tables.get_Item(i).set_TableName("data" + ((int) num13).ToString()); } if (@params.NoticeTemplate.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"); } } using (StiReport report = new StiReport()) { report.LoadFromString(@params.NoticeTemplate.Template); report.ReportCacheMode = StiReportCacheMode.Off; report.Compile(); foreach (System.Data.DataTable table2 in set.Tables) { report.RegData(table2.get_TableName(), (System.Data.DataTable) table2); } report.RegData("header", (System.Data.DataTable) table); string accountNumber = notice.AccountNumber; string str5 = System.IO.Path.Combine(info.get_FullName(), accountNumber); if (System.IO.File.Exists(str5 + ".pdf")) { int num5 = 1; num5 = 1; while (System.IO.File.Exists(str5 + "(" + ((int) num5).ToString() + ").pdf")) { num5 = (int) (num5 + 1); } obj2 = str5; str5 = string.Concat((object[]) new object[] { obj2, "(", ((int) num5), ")" }); } report.ReportCacheMode = StiReportCacheMode.Off; report.Compile(); report.Render(false); new StiPdfExportService().ExportPdf(report, str5 + ".pdf"); } } } } catch (System.Exception exception) { string message = string.Format("[{0}] Ошибка при выгрузке в PDF: Адрес: {4}, ЛС {3}{1}{2}{1}", new object[] { System.DateTime.Now.ToShortTimeString(), System.Environment.get_NewLine(), exception.get_Message(), notice.AccountNumber, notice.AddressName }); this.AddMessageToLogFile(info.get_FullName(), message, "errors"); continue; } int num6 = (int) (((num = (int) (num + 1)) * 100) / notices.get_Count()); worker.ReportProgress(num6, (int) num); } } else { BoundaryCollection<long> boundarys = null; System.Collections.Generic.Dictionary<long, int[]> dictionary = null; foreach (System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IList<NoticeNotice>> pair in @params.HouseHolderNotices) { boundarys = new BoundaryCollection<long>(@params.MaxNoticesPerDocument, @params.MinHouseCount); dictionary = new System.Collections.Generic.Dictionary<long, int[]>(); foreach (NoticeNotice notice2 in pair.Value) { num = (int) (num + 1); long num7 = (notice2.AddressLevel == 40) ? notice2.ParentAddrId : notice2.AddrId; if (!dictionary.ContainsKey(num7)) { dictionary.Add(num7, new int[] { 1, notice2.AddressLevel }); } else { dictionary[num7][0] += 1; } } int num8 = (int) ((num * 100) / notices.get_Count()); worker.ReportProgress(num8, (int) num); foreach (System.Collections.Generic.KeyValuePair<long, int[]> pair2 in dictionary) { boundarys.Add(pair2.Key, pair2.Value[0]); } System.Collections.Generic.Dictionary<string, int> dictionary2 = new System.Collections.Generic.Dictionary<string, int>(); foreach (BoundaryCollectionNode<long> node in boundarys.Lists) { if (node.Items.get_Count() > 0) { if (worker.get_CancellationPending()) { e.set_Cancel(true); break; } ObjectList<NoticeNotice> list3 = new ObjectList<NoticeNotice>(); string str7 = null; System.Text.StringBuilder builder = new System.Text.StringBuilder(); foreach (long num9 in node.Items) { foreach (NoticeNotice notice3 in notices) { if (dictionary[num9][1] == 40) { if (notice3.ParentAddrId == num9) { if (str7 == null) { str7 = string.IsNullOrEmpty(notice3.HouseHolderName) ? AIS.SN.Model.Constants.ObjectNotChoosedCaption : notice3.HouseHolderName; if (!dictionary2.ContainsKey(str7)) { dictionary2.Add(str7, 1); } } builder.AppendLine(notice3.AddressName); list3.Add(notice3); } } else if (notice3.AddrId == num9) { if (str7 == null) { str7 = string.IsNullOrEmpty(notice3.HouseHolderName) ? AIS.SN.Model.Constants.ObjectNotChoosedCaption : notice3.HouseHolderName; if (!dictionary2.ContainsKey(str7)) { dictionary2.Add(str7, 1); } } builder.AppendLine(notice3.AddressName); list3.Add(notice3); } } } string str8 = str7; chArray2 = invalidFileNameChars; num12 = 0; while (num12 < chArray2.Length) { char ch2 = chArray2[num12]; str8 = str8.Replace(ch2, ' '); num12 = (int) (num12 + 1); } str8 = str8.Trim(); System.IO.DirectoryInfo info2 = new System.IO.DirectoryInfo(System.IO.Path.Combine(@params.PeriodDirectory.get_FullName(), str8)); if (!info2.get_Exists()) { info2.Create(); } using (System.Data.DataTable table3 = NoticeNotice.GetHeader(list3, this.cbHideClosedAccounts.get_Checked(), this.cbNoticeInformation.get_Checked())) { table3.set_TableName("header"); using (System.Data.DataSet set2 = NoticeNotice.GetReport(list3, @params.NoticeTemplate.Sql)) { if ((set2.Tables.get_Count() >= 2) && (set2.Tables.get_Item(0).Rows.get_Count() != 0)) { set2.Tables.get_Item(0).set_TableName("pays"); set2.Tables.get_Item(1).set_TableName("counter"); for (int j = 2; j < set2.Tables.get_Count(); j = (int) (j + 1)) { num13 = (int) (j - 1); set2.Tables.get_Item(j).set_TableName("data" + ((int) num13).ToString()); } if (@params.NoticeTemplate.IdentityName == "Счет на оплату Ульяновск вариант 3") { if (set2.Tables.get_Count() > 2) { set2.Tables.get_Item(2).set_TableName("organizations"); } if (set2.Tables.get_Count() > 3) { set2.Tables.get_Item(3).set_TableName("rates"); } } using (StiReport report2 = new StiReport()) { System.Collections.Generic.Dictionary<string, int> dictionary3; string str16; report2.LoadFromString(@params.NoticeTemplate.Template); report2.ReportCacheMode = StiReportCacheMode.Off; report2.Compile(); foreach (System.Data.DataTable table4 in set2.Tables) { report2.RegData(table4.get_TableName(), (System.Data.DataTable) table4); } report2.RegData("header", (System.Data.DataTable) table3); report2.Compile(); (dictionary3 = dictionary2).set_Item(str16 = str7, (num13 = dictionary3[str16]) + 1); string str10 = string.Format("{0} {1}", str7, (int) num13); chArray2 = invalidFileNameChars; for (num12 = 0; num12 < chArray2.Length; num12 = (int) (num12 + 1)) { char ch3 = chArray2[num12]; str10 = str10.Replace(ch3, ' '); } string str11 = System.IO.Path.Combine(info2.get_FullName(), str10); if (System.IO.File.Exists(str11 + ".pdf")) { int num11 = 1; num11 = 1; while (System.IO.File.Exists(str11 + "(" + ((int) num11).ToString() + ").pdf")) { num11 = (int) (num11 + 1); } obj2 = str11; str11 = string.Concat((object[]) new object[] { obj2, "(", ((int) num11), ")" }); } try { report2.Render(false); new StiPdfExportService().ExportPdf(report2, str11 + ".pdf"); System.IO.File.WriteAllText(str11 + ".txt", builder.ToString()); } catch (System.IO.IOException exception2) { string str12 = string.Format("[{0}] Ошибка при записи в каталог.{1}{2}{1}", System.DateTime.Now.ToShortTimeString(), System.Environment.get_NewLine(), exception2.get_Message()); string str13 = string.Format("[{0}] {1}{2}{1}", System.DateTime.Now.ToShortTimeString(), System.Environment.get_NewLine(), builder.ToString()); this.AddMessageToLogFile(info2.get_FullName(), str12, "errors"); this.AddMessageToLogFile(info2.get_FullName(), str13, "невыгруженные_адреса"); } catch (System.Exception exception3) { string str14 = string.Format("[{0}] Ошибка при выгрузке в PDF..{1}{2}{1}", System.DateTime.Now.ToShortTimeString(), System.Environment.get_NewLine(), exception3.get_Message()); string str15 = string.Format("[{0}] {1}{2}{1}", System.DateTime.Now.ToShortTimeString(), System.Environment.get_NewLine(), builder.ToString()); this.AddMessageToLogFile(info2.get_FullName(), str14, "errors"); this.AddMessageToLogFile(info2.get_FullName(), str15, "невыгруженные_адреса"); } } } } } } } } } }