ReportUtils.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. //using Ghostscript.NET;
  2. //using Ghostscript.NET.Processor;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Drawing.Printing;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Windows;
  12. using System.Windows.Controls;
  13. using FastReport;
  14. using FastReport.Data;
  15. using FastReport.Export.Pdf;
  16. using FastReport.Utils;
  17. using InABox.Clients;
  18. using InABox.Core;
  19. using InABox.Core.Reports;
  20. using InABox.Scripting;
  21. using InABox.Wpf.Reports.CustomObjects;
  22. using Syncfusion.Pdf;
  23. using Syncfusion.Pdf.Parsing;
  24. using XmlDocument = System.Xml.XmlDocument;
  25. namespace InABox.Wpf.Reports
  26. {
  27. public enum ReportExportType
  28. {
  29. PDF,
  30. HTML,
  31. RTF,
  32. Excel,
  33. Text,
  34. Image
  35. }
  36. public delegate void ReportExportDefinitionClicked();
  37. public class ReportExportDefinition
  38. {
  39. public ReportExportDefinition(string caption, Bitmap image, ReportExportType type, Action<DataModel, byte[]> action)
  40. {
  41. Caption = caption;
  42. Image = image;
  43. Type = type;
  44. Action = action;
  45. }
  46. public ReportExportDefinition(string caption, ContentControl control, ReportExportType type, Action<DataModel, byte[]> action)
  47. {
  48. Caption = caption;
  49. Type = type;
  50. Action = action;
  51. Control = control;
  52. }
  53. public event ReportExportDefinitionClicked OnReportDefinitionClicked;
  54. public string Caption { get; }
  55. public Bitmap Image { get; }
  56. public ContentControl Control { get; }
  57. public ReportExportType Type { get; }
  58. public Action<DataModel, byte[]> Action { get; }
  59. }
  60. [LibraryInitializer]
  61. public static class ReportUtils
  62. {
  63. public static List<ReportExportDefinition> ExportDefinitions { get; } = new();
  64. public static void RegisterClasses()
  65. {
  66. CoreUtils.RegisterClasses(typeof(ReportTemplate).Assembly, typeof(ReportUtils).Assembly);
  67. foreach (string printer in PrinterSettings.InstalledPrinters)
  68. ReportPrinters.Register(printer);
  69. Application.Current.Dispatcher.BeginInvoke(() =>
  70. {
  71. RegisteredObjects.Add(typeof(MultiImageObject), "ReportPage", Wpf.Resources.multi_image, "Multi-Image");
  72. RegisteredObjects.Add(typeof(MultiSignatureObject), "ReportPage",Wpf.Resources.signature, "Multi-Signature");
  73. RegisteredObjects.Add(typeof(HTMLView), "ReportPage",Wpf.Resources.view, "HTML");
  74. });
  75. }
  76. public static void PreviewReport(ReportTemplate template, DataModel data, bool printandclose = false, bool allowdesigner = false)
  77. {
  78. if (template.IsRDL)
  79. {
  80. MessageBox.Show("RDL Reports are no longer supported!");
  81. }
  82. else
  83. {
  84. PreviewWindow window = new(template, data)
  85. {
  86. AllowDesign = allowdesigner,
  87. Title = string.Format("Report Preview - {0}", template.Name),
  88. Height = 800,
  89. Width = 1200,
  90. WindowState = WindowState.Maximized,
  91. };
  92. window.Show();
  93. }
  94. }
  95. public static Report SetupReport(ReportTemplate? template, DataModel data, bool repopulate)
  96. {
  97. var templaterdl = template != null ? string.IsNullOrWhiteSpace(template.RDL) ? "" : template.RDL : "";
  98. var tables = new List<string>();
  99. if (!string.IsNullOrWhiteSpace(templaterdl))
  100. {
  101. var xml = new XmlDocument();
  102. xml.LoadString(templaterdl);
  103. var datasources = xml.GetElementsByTagName("TableDataSource");
  104. for (var i = 0; i < datasources.Count; i++)
  105. {
  106. var datasource = datasources[i];
  107. tables.Add(datasource.Attributes.GetNamedItem("Name").Value);
  108. }
  109. }
  110. else
  111. {
  112. foreach(var table in data.DefaultTables)
  113. {
  114. tables.Add(table.TableName);
  115. }
  116. }
  117. var report = new Report();
  118. report.Log += (sender, args) =>
  119. Logger.Send(args.IsError ? LogType.Error : LogType.Information, "", args.Message);
  120. Config.ReportSettings.ShowProgress = false;
  121. report.LoadFromString(templaterdl);
  122. report.FileName = template?.Name ?? "";
  123. foreach(var tableName in data.TableNames)
  124. {
  125. var modelTable = data.GetDataModelTable(tableName);
  126. var dataSource = report.GetDataSource(tableName);
  127. if (dataSource != null && modelTable.Type is not null)
  128. {
  129. var columnNames = CoreUtils.GetColumnNames(modelTable.Type, x => true);
  130. foreach (var column in dataSource.Columns)
  131. {
  132. if(column is FastReport.Data.Column col && !col.Enabled)
  133. {
  134. //columns.Add(col.Name.Replace('_','.'));
  135. columnNames.Remove(col.Name.Replace('_', '.'));
  136. }
  137. /*if (column is FastReport.Data.Column col && col.DataType != null && col.DataType.IsAssignableTo(typeof(IEnumerable<byte[]>)))
  138. {
  139. col.BindableControl = ColumnBindableControl.Custom;
  140. col.CustomBindableControl = "MultiImageObject";
  141. }*/
  142. }
  143. modelTable.Columns = Columns.None(modelTable.Type).Add(columnNames);
  144. }
  145. }
  146. ScriptDocument? script = null;
  147. bool ScriptOK = false;
  148. if (!string.IsNullOrWhiteSpace(template?.Script))
  149. {
  150. script = new ScriptDocument(template.Script);
  151. if (script.Compile())
  152. {
  153. script.SetValue("Model", data);
  154. ScriptOK = script.Execute("Report", "Init");
  155. }
  156. }
  157. if (repopulate)
  158. data.LoadModel(tables);
  159. if (ScriptOK && script is not null)
  160. {
  161. script.SetValue("RequireTables", tables);
  162. script.Execute("Report", "Populate");
  163. }
  164. var ds = data.AsDataSet();
  165. report.RegisterData(ds);
  166. foreach (var tableName in data.TableNames)
  167. {
  168. var columnNames = data.GetColumns(tableName)?.ColumnNames().ToHashSet();
  169. var dataSource = report.GetDataSource(tableName);
  170. if(dataSource != null)
  171. {
  172. foreach (var column in dataSource.Columns)
  173. {
  174. if (column is FastReport.Data.Column col)
  175. {
  176. if (col.DataType != null && col.DataType.IsAssignableTo(typeof(IEnumerable<byte[]>)))
  177. {
  178. col.BindableControl = ColumnBindableControl.Custom;
  179. col.CustomBindableControl = "MultiImageObject";
  180. }
  181. col.Enabled = columnNames is null || columnNames.Contains(col.Name.Replace('_', '.'));
  182. }
  183. }
  184. }
  185. }
  186. if (string.IsNullOrWhiteSpace(templaterdl))
  187. {
  188. foreach (var table in data.DefaultTables)
  189. {
  190. var dataSource = report.GetDataSource(table.TableName);
  191. dataSource.Enabled = true;
  192. }
  193. foreach (Relation relation in report.Dictionary.Relations)
  194. if (data.DefaultTables.Any(x => x.TableName.Equals(relation.ParentDataSource.Alias)) &&
  195. data.DefaultTables.Any(x => x.TableName.Equals(relation.ChildDataSource.Alias)))
  196. relation.Enabled = true;
  197. }
  198. return report;
  199. }
  200. public static void DesignReport(ReportTemplate template, DataModel data, bool populate = false, Action<ReportTemplate>? saveTemplate = null)
  201. {
  202. var isrdl = template != null && template.IsRDL;
  203. var templaterdl = template != null ? string.IsNullOrWhiteSpace(template.RDL) ? "" : template.RDL : "";
  204. if (isrdl)
  205. MessageBox.Show("RDL Reports are not supported!");
  206. else
  207. {
  208. PreviewWindow window = new(template, data)
  209. {
  210. AllowDesign = true,
  211. Title = string.Format("Report Designer - {0}", template.Name),
  212. Height = 800,
  213. Width = 1200,
  214. WindowState = WindowState.Maximized,
  215. IsPreview = false,
  216. ShouldPopulate = populate,
  217. SaveTemplate = saveTemplate
  218. };
  219. window.Show();
  220. }
  221. }
  222. public static byte[] CompressPDF(byte[] original)
  223. {
  224. //Load the existing PDF document
  225. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(original);
  226. //Create a new compression option.
  227. PdfCompressionOptions options = new PdfCompressionOptions();
  228. //Enable the compress image.
  229. options.CompressImages = true;
  230. //Set the image quality.
  231. options.ImageQuality = 50;
  232. //Assign the compression option to the document.
  233. loadedDocument.CompressionOptions = options;
  234. //Creating the stream object.
  235. using (MemoryStream stream = new MemoryStream())
  236. {
  237. //Save the document into stream.
  238. loadedDocument.Save(stream);
  239. return stream.GetBuffer();
  240. }
  241. }
  242. public static byte[] ReportToPDF(ReportTemplate template, DataModel data, bool repopulate = true)
  243. {
  244. byte[] result = null;
  245. if (template.IsRDL)
  246. MessageBox.Show("RDL Reports are not supported!");
  247. else
  248. using (var report = SetupReport(template, data, repopulate))
  249. {
  250. report.Prepare();
  251. var ms = new MemoryStream();
  252. report.Export(new PDFExport() { JpegCompression = true, JpegQuality = 65, Compressed = true }, ms);
  253. result = ms.GetBuffer();
  254. }
  255. return result;
  256. }
  257. public static Filter<ReportTemplate> GetReportFilter(string sectionName, DataModel model)
  258. {
  259. return new Filter<ReportTemplate>(x => x.DataModel).IsEqualTo(model.Name)
  260. .And(x => x.Section).IsEqualTo(sectionName)
  261. .And(x => x.Visible).IsEqualTo(true);
  262. }
  263. public static IEnumerable<ReportTemplate> LoadReports(string sectionName, DataModel model, Columns<ReportTemplate>? columns = null)
  264. {
  265. return new Client<ReportTemplate>().Query(
  266. GetReportFilter(sectionName, model),
  267. columns,
  268. new SortOrder<ReportTemplate>(x => x.Name))
  269. .ToObjects<ReportTemplate>();
  270. }
  271. private static void PopulateMenu(ItemsControl menu, string sectionName, DataModel model, bool allowdesign, bool populate = false)
  272. {
  273. var reports = LoadReports(sectionName, model);
  274. foreach (var report in reports)
  275. {
  276. var print = new MenuItem
  277. {
  278. Header = report.Name,
  279. Tag = report
  280. };
  281. print.Click += (sender, args) =>
  282. {
  283. PreviewReport(report, model, false, allowdesign);
  284. };
  285. menu.Items.Add(print);
  286. }
  287. if (allowdesign)
  288. {
  289. if (menu.Items.Count > 0 && menu.Items[^1] is not Separator)
  290. {
  291. menu.Items.Add(new Separator());
  292. }
  293. var manage = new MenuItem
  294. {
  295. Header = "Manage Reports"
  296. };
  297. manage.Click += (sender, args) =>
  298. {
  299. var manager = new ReportManager()
  300. {
  301. DataModel = model,
  302. Section = sectionName,
  303. Populate = populate
  304. };
  305. manager.ShowDialog();
  306. };
  307. menu.Items.Add(manage);
  308. }
  309. }
  310. /// <summary>
  311. /// Populate the <paramref name="menu"/> with a list of reports attached to this data model, loaded through <see cref="LoadReports(string, DataModel, Columns{ReportTemplate}?)"/>.
  312. /// </summary>
  313. /// <remarks>
  314. /// This is used for the various places we have context menus for printing reports.
  315. /// </remarks>
  316. /// <param name="allowdesign">Allow designing reports; if <see langword="true"/>, then also adds a "Manage Reports" button.</param>
  317. /// <param name="populate">Determines whether the datamodel should be reloaded when printing a report.<br/>Set to <see langword="false"/> if all the data has already been loaded.</param>
  318. public static void PopulateMenu(MenuItem menu, string sectionName, DataModel model, bool allowdesign, bool populate = false) =>
  319. PopulateMenu(menu as ItemsControl, sectionName, model, allowdesign, populate);
  320. /// <summary>
  321. /// Populate the <paramref name="menu"/> with a list of reports attached to this data model, loaded through <see cref="LoadReports(string, DataModel, Columns{ReportTemplate}?)"/>.
  322. /// </summary>
  323. /// <remarks>
  324. /// This is used for the various places we have context menus for printing reports.
  325. /// </remarks>
  326. /// <param name="allowdesign">Allow designing reports; if <see langword="true"/>, then also adds a "Manage Reports" button.</param>
  327. /// <param name="populate">Determines whether the datamodel should be reloaded when printing a report.<br/>Set to <see langword="false"/> if all the data has already been loaded.</param>
  328. public static void PopulateMenu(ContextMenu menu, string sectionName, DataModel model, bool allowdesign, bool populate = false) =>
  329. PopulateMenu(menu as ItemsControl, sectionName, model, allowdesign, populate);
  330. public static void PrintMenu(FrameworkElement? element, string sectionName, DataModel model, bool allowdesign, bool populate = false)
  331. {
  332. var menu = new ContextMenu();
  333. PopulateMenu(menu, sectionName, model, allowdesign, populate);
  334. if (menu.Items.Count > 0)
  335. {
  336. menu.PlacementTarget = element;
  337. menu.IsOpen = true;
  338. }
  339. }
  340. public static void PrintMenu<TType>(FrameworkElement? element, string sectionName, DataModel<TType> model, bool allowdesign, bool populate = false)
  341. where TType : Entity, IRemotable, IPersistent, new()
  342. {
  343. PrintMenu(element, sectionName, model, allowdesign, populate);
  344. }
  345. #region Old RDL Stuff (Deprecated)
  346. // private static ReportDefinition SetupReportDefinition(String rdl, Dictionary<System.Type, CoreTable> dataenvironment = null)
  347. // {
  348. // ReportDefinition report = null;
  349. // if (String.IsNullOrWhiteSpace(rdl))
  350. // report = CreateReport();
  351. // else
  352. // report = DeserialiseReport(rdl);
  353. //
  354. // if (dataenvironment != null)
  355. // SetupReportData(report, dataenvironment);
  356. // return report;
  357. // }
  358. // public static String SetupReport(String rdl, Dictionary<System.Type, CoreTable> dataenvironment = null)
  359. // {
  360. // var defn = SetupReportDefinition(rdl, dataenvironment);
  361. // return SerialiseReport(defn);
  362. // }
  363. //
  364. // public static MemoryStream SetupReportToStream(String rdl, Dictionary<System.Type, CoreTable> dataenvironment = null)
  365. // {
  366. // var defn = SetupReportDefinition(rdl, dataenvironment);
  367. // return SerialiseReportToStream(defn);
  368. // }
  369. // public static String CleanupReport(String rdl)
  370. // {
  371. // ReportDefinition report = null;
  372. // if (String.IsNullOrWhiteSpace(rdl))
  373. // report = CreateReport();
  374. // else
  375. // report = DeserialiseReport(rdl);
  376. //
  377. // CleanupReportData(report);
  378. //
  379. // return SerialiseReport(report);
  380. //
  381. // }
  382. // private static ReportDefinition CreateReport()
  383. // {
  384. // ReportDefinition rd = new ReportDefinition();
  385. // rd.DataSources = new DataSources();
  386. // rd.DataSets = new DataSets();
  387. //
  388. // rd.ReportSections = new ReportSections();
  389. // rd.ReportSections.Add(
  390. // new ReportSection()
  391. // {
  392. // Width = new Syncfusion.RDL.DOM.Size("7.5in"),
  393. // Body = new Body()
  394. // {
  395. // Style = new Syncfusion.RDL.DOM.Style() { BackgroundColor = "White", Border = new Syncfusion.RDL.DOM.Border() },
  396. // Height = new Syncfusion.RDL.DOM.Size("10in"),
  397. //
  398. // },
  399. // Page = new Syncfusion.RDL.DOM.Page()
  400. // {
  401. // PageHeight = new Syncfusion.RDL.DOM.Size("11in"),
  402. // PageWidth = new Syncfusion.RDL.DOM.Size("8.5in"),
  403. // Style = new Syncfusion.RDL.DOM.Style() { BackgroundColor = "White", Border = new Syncfusion.RDL.DOM.Border() },
  404. // }
  405. // }
  406. // );
  407. // rd.EmbeddedImages = new EmbeddedImages();
  408. //
  409. // rd.RDLType = RDLType.RDL2010;
  410. // rd.CodeModules = new CodeModules();
  411. // rd.CodeModules.Add(new CodeModule() { Value = "System.Drawing, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a" });
  412. // rd.CodeModules.Add(new CodeModule() { Value = "Syncfusion.Pdf.Base, Version = 13.3350.0.7, Culture = neutral, PublicKeyToken = 3d67ed1f87d44c89" });
  413. // rd.CodeModules.Add(new CodeModule() { Value = "Syncfusion.Linq.Base, Version = 13.3350.0.7, Culture = neutral, PublicKeyToken = 3d67ed1f87d44c89" });
  414. //
  415. // rd.Classes = new Classes();
  416. // rd.Classes.Add(new Class() { ClassName = "Syncfusion.Pdf.Barcode.PDFCode39Barcode", InstanceName = "Code39" });
  417. // rd.Classes.Add(new Class() { ClassName = "Syncfusion.Pdf.Barcode.PdfQRBarcode", InstanceName = "QRCode" });
  418. //
  419. // rd.Code = @"
  420. // Public Function Code39BarCode(Text As String) As String
  421. // Dim _msg as String
  422. // try
  423. // Code39.BarHeight = 100
  424. // Code39.Text = Text
  425. // Code39.EnableCheckDigit = True
  426. // Code39.EncodeStartStopSymbols = True
  427. // Code39.ShowCheckDigit = False
  428. // Code39.TextDisplayLocation = 0
  429. // Dim _img As System.Drawing.Image = Code39.ToImage()
  430. // Dim ms As New System.IO.MemoryStream()
  431. // _img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
  432. // Dim _bytes = ms.ToArray()
  433. // Return System.Convert.ToBase64String(_bytes, 0, _bytes.Length)
  434. // Catch ex As Exception
  435. // _msg = ex.toString()
  436. // End Try
  437. // return Nothing
  438. // End Function
  439. //
  440. // Public Function QRBarCode(Text As String) As String
  441. // Dim _msg as String
  442. // try
  443. // QRCode.Text = Text
  444. // QRCode.XDimension = 4
  445. // Dim _img As System.Drawing.Image = QRCode.ToImage()
  446. // Dim ms As New System.IO.MemoryStream()
  447. // _img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
  448. // Dim _bytes = ms.ToArray()
  449. // Return System.Convert.ToBase64String(_bytes, 0, _bytes.Length)
  450. // Catch ex As Exception
  451. // _msg = ex.toString()
  452. // End Try
  453. // return Nothing
  454. // End Function
  455. //
  456. // ";
  457. // return rd;
  458. //
  459. // //MemoryStream memoryStream = new MemoryStream();
  460. // //TextWriter ws2 = new StreamWriter(memoryStream);
  461. // //xs2.Serialize(ws2, rd, serialize);
  462. // //memoryStream.Position = 0;
  463. // ////To save to a file.
  464. // //StringWriter ws3 = new StringWriter
  465. // //TextWriter ws3 = new StreamWriter(_tempfile);
  466. // //xs2.Serialize(ws3, rd, serialize);
  467. // //ws2.Close();
  468. // //ws3.Close();
  469. // //memoryStream.Close();
  470. //
  471. // }
  472. private static string DataTableToXML(Type type, CoreTable table)
  473. {
  474. var doc = new XmlDocument();
  475. var root = doc.CreateElement("", type.Name.ToLower() + "s", "");
  476. doc.AppendChild(root);
  477. //var properties = CoreUtils.PropertyList(type, x => true, true);
  478. if (table != null)
  479. {
  480. if (table.Rows.Any())
  481. {
  482. foreach (var datarow in table.Rows)
  483. {
  484. var row = doc.CreateElement("", type.Name.ToLower(), "");
  485. foreach (var column in table.Columns)
  486. {
  487. var field = doc.CreateElement("", column.ColumnName.Replace('.', '_'), "");
  488. var oVal = datarow[column.ColumnName];
  489. var value = doc.CreateTextNode(oVal != null ? oVal.ToString() : "");
  490. field.AppendChild(value);
  491. row.AppendChild(field);
  492. }
  493. root.AppendChild(row);
  494. }
  495. }
  496. else
  497. {
  498. var row = doc.CreateElement("", type.Name.ToLower(), "");
  499. foreach (var column in table.Columns)
  500. {
  501. var field = doc.CreateElement("", column.ColumnName.Replace('.', '_'), "");
  502. var value = doc.CreateTextNode("");
  503. field.AppendChild(value);
  504. row.AppendChild(field);
  505. }
  506. root.AppendChild(row);
  507. }
  508. }
  509. var xmlString = "";
  510. using (var wr = new StringWriter())
  511. {
  512. doc.Save(wr);
  513. xmlString = wr.ToString();
  514. }
  515. return xmlString.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n", "");
  516. }
  517. public static DataSet CreateReportDataSource(Dictionary<Type, CoreTable> dataenvironment)
  518. {
  519. var ds = new DataSet();
  520. foreach (var key in dataenvironment.Keys)
  521. {
  522. var table = dataenvironment[key];
  523. var dt = new DataTable(key.EntityName().Split('.').Last());
  524. foreach (var column in table.Columns)
  525. dt.Columns.Add(column.ColumnName);
  526. foreach (var row in table.Rows)
  527. dt.Rows.Add(row.Values.ToArray());
  528. ds.Tables.Add(dt);
  529. }
  530. return ds;
  531. }
  532. // private static void SetupReportData(ReportDefinition report, Dictionary<System.Type,CoreTable> dataenvironment)
  533. // {
  534. //
  535. // report.DataSets.Clear();
  536. // report.DataSources.Clear();
  537. // foreach (System.Type type in dataenvironment.Keys)
  538. // {
  539. // String _tempfile = Path.GetTempFileName();
  540. // String xml = DataTableToXML(type, dataenvironment[type]);
  541. // File.WriteAllText(_tempfile, xml);
  542. // // Create DataSource(s)
  543. // DataSource datasource = new DataSource()
  544. // {
  545. // Name = type.Name,
  546. // ConnectionProperties = new ConnectionProperties()
  547. // {
  548. // DataProvider = "XML",
  549. // IntegratedSecurity = true,
  550. // ConnectString = _tempfile
  551. // },
  552. // SecurityType = SecurityType.None,
  553. // };
  554. // report.DataSources.Add(datasource);
  555. //
  556. // Syncfusion.RDL.DOM.DataSet dataset = new Syncfusion.RDL.DOM.DataSet() { Name = type.Name };
  557. // dataset.Fields = new Fields();
  558. //
  559. // CoreTable table = dataenvironment[type];
  560. // foreach (var column in table.Columns)
  561. // {
  562. // dataset.Fields.Add(
  563. // new Field()
  564. // {
  565. // Name = column.ColumnName.Replace('.', '_'),
  566. // DataField = column.ColumnName.Replace('.', '_'),
  567. // TypeName = column.DataType.Name
  568. // }
  569. // );
  570. // }
  571. //
  572. // //var properties = CoreUtils.PropertyList(type, x => true, true);
  573. //
  574. // //// Create DataSet(s)
  575. // //foreach (String key in properties.Keys)
  576. // //{
  577. // // dataset.Fields.Add(
  578. // // new Field()
  579. // // {
  580. // // Name = key.Replace('.', '_'),
  581. // // DataField = key.Replace('.', '_'),
  582. // // TypeName = properties[key].Name
  583. // // }
  584. // // );
  585. // //}
  586. // dataset.Query = new Query()
  587. // {
  588. // DataSourceName = type.Name,
  589. // CommandType = Syncfusion.RDL.DOM.CommandType.Text,
  590. // CommandText = String.Format("{0}s/{0}", type.Name.ToLower())
  591. // };
  592. // report.DataSets.Add(dataset);
  593. // }
  594. // }
  595. //
  596. // private static void CleanupReportData(ReportDefinition report)
  597. // {
  598. // foreach (var ds in report.DataSources)
  599. // {
  600. // String _tempfile = ds.ConnectionProperties.ConnectString;
  601. // if (File.Exists(_tempfile))
  602. // File.Delete(_tempfile);
  603. // ds.ConnectionProperties.ConnectString = "";
  604. // }
  605. // report.DataSources[0].ConnectionProperties.ConnectString = "";
  606. // }
  607. //
  608. // private static ReportDefinition DeserialiseReport(String rdl)
  609. // {
  610. // String data = rdl;
  611. // try
  612. // {
  613. // byte[] debase64 = Convert.FromBase64String(rdl);
  614. // data = Encoding.UTF8.GetString(debase64);
  615. // }
  616. // catch (Exception e)
  617. // {
  618. // Logger.Send(LogType.Error, "", String.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  619. // }
  620. // ReportDefinition report = null;
  621. // XmlSerializer xs = new XmlSerializer(typeof(ReportDefinition), "http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition");
  622. // using (StringReader stringreader = new StringReader(data)) // root.ToString()))
  623. // {
  624. // report = (ReportDefinition)xs.Deserialize(stringreader);
  625. // }
  626. // return report;
  627. // }
  628. //
  629. // [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
  630. // private static String SerialiseReport(ReportDefinition report)
  631. // {
  632. // var stream = SerialiseReportToStream(report);
  633. // return Encoding.UTF8.GetString(stream.ToArray());
  634. //
  635. // }
  636. //
  637. // [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
  638. // private static MemoryStream SerialiseReportToStream(ReportDefinition report)
  639. // {
  640. //
  641. // string nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition";
  642. //
  643. // if (report.RDLType == RDLType.RDL2010)
  644. // nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition";
  645. //
  646. // XmlSerializerNamespaces serialize = new XmlSerializerNamespaces();
  647. // serialize.Add("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
  648. // XmlSerializer xs2 = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), nameSpace);
  649. // MemoryStream memoryStream = new MemoryStream();
  650. // TextWriter ws2 = new StreamWriter(memoryStream);
  651. // xs2.Serialize(ws2, report, serialize);
  652. // memoryStream.Position = 0;
  653. // return memoryStream;
  654. // //return Encoding.UTF8.GetString(memoryStream.ToArray());
  655. //
  656. // }
  657. // private static byte[] GhostScriptIt(byte[] pdf)
  658. // {
  659. // String input = Path.GetTempFileName();
  660. // File.WriteAllBytes(input, pdf);
  661. // byte[] result = new byte[] { };
  662. // GhostscriptVersionInfo gv = new GhostscriptVersionInfo(
  663. // new Version(0, 0, 0),
  664. // "gsdll32.dll",
  665. // "",
  666. // GhostscriptLicense.GPL
  667. // );
  668. // GhostscriptPipedOutput gsPipedOutput = new GhostscriptPipedOutput();
  669. // // pipe handle format: %handle%hexvalue
  670. // string outputPipeHandle = "%handle%" + int.Parse(gsPipedOutput.ClientHandle).ToString("X2");
  671. // using (GhostscriptProcessor processor = new GhostscriptProcessor(gv, true))
  672. // {
  673. // List<string> switches = new List<string>();
  674. // switches.Add("-empty");
  675. // switches.Add("-dQUIET");
  676. // switches.Add("-dSAFER");
  677. // switches.Add("-dBATCH");
  678. // switches.Add("-dNOPAUSE");
  679. // switches.Add("-dNOPROMPT");
  680. // switches.Add("-dCompatibilityLevel=1.4");
  681. // switches.Add("-sDEVICE=pdfwrite");
  682. // switches.Add("-o" + outputPipeHandle);
  683. // switches.Add("-q");
  684. // switches.Add("-f");
  685. // switches.Add(input);
  686. // try
  687. // {
  688. // processor.StartProcessing(switches.ToArray(), null);
  689. // result = gsPipedOutput.Data;
  690. // }
  691. // catch (Exception ex)
  692. // {
  693. // Console.WriteLine(ex.Message);
  694. // }
  695. // finally
  696. // {
  697. // gsPipedOutput.Dispose();
  698. // gsPipedOutput = null;
  699. // }
  700. // }
  701. // File.Delete(input);
  702. // return result;
  703. // }
  704. #endregion
  705. }
  706. }