DynamicDocumentGrid.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Data;
  10. using System.Windows.Media;
  11. using InABox.Clients;
  12. using InABox.Core;
  13. using InABox.WPF;
  14. using Microsoft.Win32;
  15. using Microsoft.Xaml.Behaviors.Core;
  16. using Image = System.Windows.Controls.Image;
  17. using InABox.Wpf;
  18. namespace InABox.DynamicGrid
  19. {
  20. public class DocumentConverter : AbstractConverter<object, object>
  21. {
  22. public override object Convert(object value)
  23. {
  24. return value;
  25. }
  26. }
  27. public class TimeStampToBrushConverter : AbstractConverter<DateTime, System.Windows.Media.Brush?>
  28. {
  29. public System.Windows.Media.Brush? Empty { get; init; }
  30. public System.Windows.Media.Brush? Set { get; init; }
  31. public override System.Windows.Media.Brush? Convert(DateTime value)
  32. {
  33. return value.IsEmpty()
  34. ? Empty
  35. : Set;
  36. }
  37. }
  38. public class DynamicDocumentGrid<TDocument, TEntity, TEntityLink> : DynamicManyToManyGrid<TDocument, TEntity>
  39. where TEntity : Entity, IPersistent, IRemotable, new()
  40. where TDocument : Entity, IEntityDocument<TEntityLink>, IPersistent, IRemotable, new() // Entity, IPersistent, IRemotable, IManyToMany<TEntity, Document>, new()
  41. where TEntityLink : EntityLink<TEntity>, new()
  42. {
  43. // private DynamicActionColumn supercedecolumn;
  44. //
  45. // public bool ShowSupercededColumn
  46. // {
  47. // get
  48. // {
  49. // return supercedecolumn.Position != DynamicActionColumnPosition.Hidden;
  50. // }
  51. // set
  52. // {
  53. // supercedecolumn.Position = value ? DynamicActionColumnPosition.End : DynamicActionColumnPosition.Hidden;
  54. // }
  55. // }
  56. public bool ShowSupercededColumn { get; set; }
  57. private bool _simpleTemplate;
  58. public bool SimpleTemplate
  59. {
  60. get => _simpleTemplate;
  61. set
  62. {
  63. _simpleTemplate = value;
  64. RowHeight = value
  65. ? 150
  66. : 100;
  67. }
  68. }
  69. private DynamicTemplateColumn _template;
  70. public DynamicDocumentGrid()
  71. {
  72. MultiSelect = false;
  73. HiddenColumns.Add(x => x.DocumentLink.ID);
  74. HiddenColumns.Add(x => x.Superceded);
  75. HiddenColumns.Add(x => x.DocumentLink.FileName);
  76. HiddenColumns.Add(x => x.Thumbnail);
  77. HiddenColumns.Add(x => x.Notes);
  78. //ActionColumns.Add(new DynamicImageColumn(DocumentImage, ViewDocument) { Position = DynamicActionColumnPosition.Start });
  79. //ActionColumns.Add(new DynamicImageColumn(DiskImage, SaveDocument) { Position = DynamicActionColumnPosition.Start });
  80. _template = new DynamicTemplateColumn(DocumentTemplate)
  81. {
  82. Position = DynamicActionColumnPosition.Start,
  83. Width = 0,
  84. HeaderText = "Attached Documents"
  85. };
  86. ActionColumns.Add(_template);
  87. //supercedecolumn = new DynamicImageColumn(SupercededImage, SupercedeDocument);
  88. //ActionColumns.Add(supercedecolumn);
  89. RowHeight = 100;
  90. }
  91. protected override void DoDoubleClick(object sender, DynamicGridCellClickEventArgs args)
  92. {
  93. var doc = SelectedRows.FirstOrDefault()?.ToObject<TDocument>();
  94. if (doc != null)
  95. {
  96. var editor = new DocumentEditor(new IEntityDocument[] { doc });
  97. //editor.PrintAllowed = Security.IsAllowed<CanPrintFactoryFloorDrawings>();
  98. editor.SaveAllowed = false;
  99. editor.ShowDialog();
  100. }
  101. }
  102. private FrameworkElement DocumentTemplate(CoreRow row)
  103. {
  104. return SimpleTemplate
  105. ? CreateSimpleTemplate()
  106. : CreateDetailedTemplate();
  107. }
  108. private FrameworkElement CreateDetailedTemplate()
  109. {
  110. Grid grid = new Grid()
  111. {
  112. Height = 100,
  113. ContextMenu = CreateContextMenu(),
  114. RowDefinitions =
  115. {
  116. new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) },
  117. new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) },
  118. },
  119. ColumnDefinitions =
  120. {
  121. new ColumnDefinition() { Width = new GridLength(100) },
  122. new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) },
  123. new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) },
  124. }
  125. };
  126. // grid.SetBinding(
  127. // Grid.BackgroundProperty,
  128. // new Binding("Superceded")
  129. // {
  130. // Converter = new TimeStampToBrushConverter()
  131. // {
  132. // Empty = new SolidColorBrush(Colors.LightYellow),
  133. // Set = new SolidColorBrush(Colors.Silver)
  134. // }
  135. // }
  136. // );
  137. Image thumbnail = new Image()
  138. {
  139. Stretch = Stretch.Uniform,
  140. Margin = new Thickness(5, 2, 5, 2),
  141. };
  142. var ttImage = new Image();
  143. ttImage.SetBinding(Image.SourceProperty,
  144. new Binding("Thumbnail") { Converter = new BytesToBitmapImageConverter() });
  145. thumbnail.ToolTip = new ToolTip()
  146. {
  147. Content = ttImage
  148. };
  149. thumbnail.SetBinding(Image.SourceProperty,
  150. new Binding("Thumbnail") { Converter = new BytesToBitmapImageConverter() });
  151. thumbnail.SetValue(Grid.RowProperty, 0);
  152. thumbnail.SetValue(Grid.RowSpanProperty, 2);
  153. thumbnail.SetValue(Grid.ColumnProperty, 0);
  154. grid.Children.Add(thumbnail);
  155. var dock = new DockPanel();
  156. dock.SetValue(Grid.RowProperty, 0);
  157. dock.SetValue(Grid.ColumnProperty, 1);
  158. grid.Children.Add(dock);
  159. var superceded = new Label()
  160. {
  161. FontWeight = FontWeights.Bold,
  162. Content = "*** SUPERCEDED ***",
  163. Margin = new Thickness(0, 0, 5, 0)
  164. };
  165. superceded.SetBinding(Label.VisibilityProperty,
  166. new Binding("Superceded") { Converter = new DateTimeToVisibilityConverter() });
  167. superceded.SetValue(DockPanel.DockProperty, Dock.Left);
  168. dock.Children.Add(superceded);
  169. var filename = new Label()
  170. {
  171. FontWeight = FontWeights.Bold
  172. };
  173. filename.SetBinding(Label.ContentProperty, new Binding("DocumentLink_FileName"));
  174. filename.SetValue(DockPanel.DockProperty, Dock.Left);
  175. dock.Children.Add(filename);
  176. var buttons = new StackPanel()
  177. {
  178. Orientation = Orientation.Horizontal
  179. };
  180. buttons.SetValue(Grid.RowProperty, 0);
  181. buttons.SetValue(Grid.ColumnProperty, 2);
  182. grid.Children.Add(buttons);
  183. var view = new Button()
  184. {
  185. Content = new Image() { Source = Wpf.Resources.multi_image.AsBitmapImage() },
  186. BorderBrush = new SolidColorBrush(Colors.Transparent),
  187. Background = new SolidColorBrush(Colors.Transparent),
  188. Height = 32,
  189. Width = 32,
  190. ToolTip = "View Documents",
  191. Command = new ActionCommand(ViewDocuments)
  192. };
  193. buttons.Children.Add(view);
  194. var copy = new Button()
  195. {
  196. Content = new Image() { Source = Wpf.Resources.copy.AsBitmapImage() },
  197. BorderBrush = new SolidColorBrush(Colors.Transparent),
  198. Background = new SolidColorBrush(Colors.Transparent),
  199. Height = 32,
  200. Width = 32,
  201. ToolTip = "Copy to Clipboard",
  202. Command = new ActionCommand(CopyDocuments)
  203. };
  204. buttons.Children.Add(copy);
  205. var save = new Button()
  206. {
  207. Content = new Image() { Source = Wpf.Resources.download.AsBitmapImage() },
  208. BorderBrush = new SolidColorBrush(Colors.Transparent),
  209. Background = new SolidColorBrush(Colors.Transparent),
  210. Height = 32,
  211. Width = 32,
  212. ToolTip = "Save Documents",
  213. Command = new ActionCommand(SaveDocuments)
  214. };
  215. buttons.Children.Add(save);
  216. var print = new Button()
  217. {
  218. Content = new Image() { Source = Wpf.Resources.print.AsBitmapImage(), Margin = new Thickness(2) },
  219. BorderBrush = new SolidColorBrush(Colors.Transparent),
  220. Background = new SolidColorBrush(Colors.Transparent),
  221. Height = 32,
  222. Width = 32,
  223. ToolTip = "Print Documents",
  224. Command = new ActionCommand(PrintDocuments)
  225. };
  226. buttons.Children.Add(print);
  227. var notes = new Label()
  228. {
  229. };
  230. notes.SetBinding(Label.ContentProperty, new Binding("Notes"));
  231. notes.SetValue(Grid.RowProperty, 1);
  232. notes.SetValue(Grid.ColumnProperty, 1);
  233. notes.SetValue(Grid.ColumnSpanProperty, 2);
  234. grid.Children.Add(notes);
  235. return grid;
  236. }
  237. private ContextMenu CreateContextMenu()
  238. {
  239. var menu = new ContextMenu();
  240. menu.Items.Add(new MenuItem()
  241. {
  242. Header = "View Documents",
  243. Command = new ActionCommand(ViewDocuments)
  244. });
  245. menu.Items.Add(new MenuItem()
  246. {
  247. Header = "Copy To Clipboard",
  248. Command = new ActionCommand(CopyDocuments)
  249. });
  250. menu.Items.Add(new MenuItem()
  251. {
  252. Header = "Save Documents",
  253. Command = new ActionCommand(SaveDocuments)
  254. });
  255. return menu;
  256. }
  257. private FrameworkElement CreateSimpleTemplate()
  258. {
  259. Grid grid = new Grid()
  260. {
  261. Height = 150,
  262. ContextMenu = CreateContextMenu(),
  263. RowDefinitions =
  264. {
  265. new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) },
  266. new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) },
  267. },
  268. ColumnDefinitions =
  269. {
  270. new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) },
  271. }
  272. };
  273. Image thumbnail = new Image()
  274. {
  275. Stretch = Stretch.Uniform,
  276. Margin = new Thickness(5),
  277. };
  278. thumbnail.SetBinding(Image.SourceProperty, new Binding("Thumbnail") { Converter = new BytesToBitmapImageConverter() });
  279. thumbnail.SetValue(Grid.RowProperty,0);
  280. grid.Children.Add(thumbnail);
  281. var filename = new Label()
  282. {
  283. HorizontalContentAlignment = HorizontalAlignment.Center,
  284. FontSize = 10
  285. };
  286. filename.SetBinding(Label.ContentProperty, new Binding("DocumentLink_FileName"));
  287. filename.SetValue(Grid.RowProperty,1);
  288. grid.Children.Add(filename);
  289. return grid;
  290. }
  291. private void GetDocuments(Action<Dictionary<string,byte[]>> action)
  292. {
  293. var ids = SelectedRows.Select(r => r.Get<IEntityDocument, Guid>(c => c.DocumentLink.ID)).ToArray();
  294. var files = Client.Query(
  295. new Filter<Document>(x => x.ID).InList(ids),
  296. Columns.None<Document>().Add(x => x.FileName).Add(x => x.Data)
  297. ).ToDictionary<Document, String, byte[]>(x => x.FileName, x => x.Data);
  298. action?.Invoke(files);
  299. }
  300. private static string SanitiseFileName(string filename)
  301. {
  302. var basefilename = Path.GetFileNameWithoutExtension(filename);
  303. var extension = Path.GetExtension(filename);
  304. return Path.ChangeExtension(string.Join("_", basefilename.Split(Path.GetInvalidFileNameChars())), extension);
  305. }
  306. private void ViewDocuments()
  307. {
  308. GetDocuments((files) =>
  309. {
  310. foreach (var file in files)
  311. {
  312. Task.Run(() =>
  313. {
  314. var tempfile = Path.Combine(System.IO.Path.GetTempPath(), SanitiseFileName(file.Key));
  315. try
  316. {
  317. File.WriteAllBytes(tempfile, file.Value);
  318. }
  319. catch
  320. {
  321. // Outlook likes to keep files open apparently, which breaks this code.
  322. }
  323. var info = new System.Diagnostics.ProcessStartInfo(tempfile);
  324. info.UseShellExecute = true;
  325. info.Verb = "Open";
  326. Process.Start(info);
  327. });
  328. }
  329. });
  330. }
  331. private void CopyDocuments()
  332. {
  333. if (SelectedRows?.Any() != true)
  334. return;
  335. GetDocuments((files) =>
  336. {
  337. System.Collections.Specialized.StringCollection FileCollection = new System.Collections.Specialized.StringCollection();
  338. foreach(var file in files)
  339. {
  340. var tempfile = Path.Combine(System.IO.Path.GetTempPath(), SanitiseFileName(file.Key));
  341. File.WriteAllBytes(tempfile, file.Value);
  342. FileCollection.Add(tempfile);
  343. }
  344. Clipboard.SetFileDropList(FileCollection);
  345. });
  346. }
  347. private void SaveDocuments()
  348. {
  349. if (SelectedRows?.Any() != true)
  350. return;
  351. using(var fbd = new System.Windows.Forms.FolderBrowserDialog())
  352. {
  353. var result = fbd.ShowDialog();
  354. if (result == System.Windows.Forms.DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
  355. {
  356. var path = fbd.SelectedPath;
  357. GetDocuments(files =>
  358. {
  359. foreach (var file in files)
  360. File.WriteAllBytes(Path.Combine(path, SanitiseFileName(file.Key)), file.Value);
  361. });
  362. }
  363. }
  364. }
  365. private void PrintDocuments()
  366. {
  367. if (SelectedRows?.Any() != true)
  368. return;
  369. GetDocuments(files =>
  370. {
  371. Task.Run(() =>
  372. {
  373. foreach (var file in files)
  374. {
  375. var tempfile = Path.Combine(System.IO.Path.GetTempPath(), SanitiseFileName(file.Key));
  376. File.WriteAllBytes(tempfile, file.Value);
  377. var info = new System.Diagnostics.ProcessStartInfo(tempfile);
  378. info.CreateNoWindow = true;
  379. info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
  380. info.UseShellExecute = true;
  381. info.Verb = "print";
  382. Process.Start(info);
  383. }
  384. });
  385. });
  386. }
  387. protected override DynamicGridColumns LoadColumns()
  388. {
  389. return new DynamicGridColumns();
  390. }
  391. protected override void DoReconfigure(DynamicGridOptions options)
  392. {
  393. base.DoReconfigure(options);
  394. options.SelectColumns = false;
  395. options.DragTarget = true;
  396. }
  397. public override int Order()
  398. {
  399. return int.MaxValue;
  400. }
  401. protected override void HandleDragOver(object sender, DragEventArgs e)
  402. {
  403. if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("FileGroupDescriptor"))
  404. {
  405. e.Effects = DragDropEffects.Copy;
  406. }
  407. else
  408. {
  409. e.Effects = DragDropEffects.None;
  410. }
  411. e.Handled = true;
  412. }
  413. protected override void HandleDragDrop(object sender, DragEventArgs e)
  414. {
  415. var result = DocumentUtils.HandleFileDrop(e);
  416. if(result is not null)
  417. {
  418. var docs = new List<Document>();
  419. foreach (var (filename, stream) in result)
  420. {
  421. var doc = new Document();
  422. doc.FileName = Path.GetFileName(filename).ToLower();
  423. if (stream is null)
  424. {
  425. doc.Data = File.ReadAllBytes(filename);
  426. doc.TimeStamp = new FileInfo(filename).LastWriteTime;
  427. }
  428. else
  429. {
  430. using var memoryStream = new MemoryStream();
  431. stream.CopyTo(memoryStream);
  432. doc.Data = memoryStream.ToArray();
  433. doc.TimeStamp = DateTime.Now;
  434. }
  435. doc.CRC = CoreUtils.CalculateCRC(doc.Data);
  436. docs.Add(doc);
  437. }
  438. AddDocuments(docs);
  439. }
  440. }
  441. protected override void OnDragEnd(Type entity, CoreTable table, DragEventArgs e)
  442. {
  443. if (entity == typeof(Document))
  444. {
  445. var refresh = false;
  446. var docIDS = table.Rows.Select(x => x.Get<Document, Guid>(x => x.ID)).ToArray();
  447. var columns = Columns.None<Document>().Add(x => x.ID);
  448. foreach (var column in VisibleColumns)
  449. {
  450. if (column.ColumnName.StartsWith("DocumentLink."))
  451. {
  452. columns.Add(string.Join('.', column.ColumnName.Split('.').Skip(1)));
  453. }
  454. }
  455. var docs = new Client<Document>()
  456. .Query(
  457. new Filter<Document>(x => x.ID).InList(docIDS),
  458. columns);
  459. foreach (var doc in docs.ToObjects<Document>())
  460. {
  461. var entityDocument = new TDocument();
  462. entityDocument.EntityLink.ID = Item.ID;
  463. entityDocument.DocumentLink.ID = doc.ID;
  464. entityDocument.DocumentLink.Synchronise(doc);
  465. SaveItem(entityDocument);
  466. refresh = true;
  467. }
  468. if (refresh)
  469. {
  470. DoChanged();
  471. Refresh(false, true);
  472. }
  473. }
  474. else
  475. {
  476. base.OnDragEnd(entity, table, e);
  477. }
  478. }
  479. private void AddDocuments(IList<Document> documents)
  480. {
  481. if (documents.Any())
  482. {
  483. new Client<Document>().Save(documents, "Initial Upload");
  484. foreach (var doc in documents)
  485. {
  486. var newitem = CreateItem();
  487. var prop = GetOtherLink(newitem);
  488. prop.ID = doc.ID;
  489. prop.Synchronise(doc);
  490. SaveItem(newitem);
  491. }
  492. DoChanged();
  493. Refresh(false, true);
  494. }
  495. }
  496. protected override void DoAdd(bool OpenEditorOnDirectEdit = false)
  497. {
  498. var dlg = new OpenFileDialog();
  499. dlg.Multiselect = true;
  500. if (dlg.ShowDialog() == true)
  501. {
  502. using (new WaitCursor())
  503. {
  504. var docs = new List<Document>();
  505. foreach (var filename in dlg.FileNames)
  506. {
  507. // Create a Document
  508. var doc = new Document();
  509. doc.FileName = Path.GetFileName(filename).ToLower();
  510. doc.TimeStamp = new FileInfo(dlg.FileName).LastWriteTime;
  511. doc.Data = File.ReadAllBytes(filename);
  512. doc.CRC = CoreUtils.CalculateCRC(doc.Data);
  513. docs.Add(doc);
  514. }
  515. AddDocuments(docs);
  516. }
  517. }
  518. }
  519. }
  520. }