MainWindow.xaml.cs 163 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.Drawing.Drawing2D;
  7. using System.Drawing.Imaging;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net.Http;
  11. using System.Net.Mail;
  12. using System.Reflection;
  13. using System.Runtime.InteropServices;
  14. using System.Text;
  15. using System.Threading.Tasks;
  16. using System.Windows;
  17. using System.Windows.Controls;
  18. using System.Windows.Controls.Primitives;
  19. using System.Windows.Forms;
  20. using System.Windows.Input;
  21. using System.Windows.Interop;
  22. using System.Windows.Media;
  23. using System.Windows.Threading;
  24. using AvalonDock.Layout;
  25. using Comal.Classes;
  26. using Comal.Stores;
  27. using Comal.TaskScheduler.Shared;
  28. using H.Pipes;
  29. using InABox.Client.IPC;
  30. using InABox.Clients;
  31. using InABox.Configuration;
  32. using InABox.Core;
  33. using InABox.Database;
  34. using InABox.Database.SQLite;
  35. using InABox.DeviceIdentifier;
  36. using InABox.DynamicGrid;
  37. using InABox.Mail;
  38. using InABox.Reports;
  39. using InABox.Reports.Common;
  40. using InABox.Scripting;
  41. using InABox.WPF;
  42. using NAudio.Wave;
  43. using PRS.Shared;
  44. using InABox.WPF.Themes;
  45. using NPOI.SS.Formula.Functions;
  46. using PRSDesktop.Configuration;
  47. using PRSDesktop.Forms;
  48. using PRSServer;
  49. using SharpAvi.Codecs;
  50. using SharpAvi.Output;
  51. using Syncfusion.UI.Xaml.Maps;
  52. using Syncfusion.Windows.Shared;
  53. using Syncfusion.Windows.Tools;
  54. using Syncfusion.Windows.Tools.Controls;
  55. using Activity = Comal.Classes.Activity;
  56. using Application = System.Windows.Application;
  57. using ButtonBase = System.Windows.Controls.Primitives.ButtonBase;
  58. using Color = System.Windows.Media.Color;
  59. using ColorConverter = System.Windows.Media.ColorConverter;
  60. using Control = System.Windows.Controls.Control;
  61. using Image = System.Drawing.Image;
  62. using KeyEventArgs = System.Windows.Input.KeyEventArgs;
  63. using MessageBox = System.Windows.MessageBox;
  64. using Pen = System.Drawing.Pen;
  65. using PixelFormat = System.Drawing.Imaging.PixelFormat;
  66. using Role = Comal.Classes.Role;
  67. using SortDirection = InABox.Core.SortDirection;
  68. using ValidationResult = InABox.Clients.ValidationResult;
  69. using System.Diagnostics.CodeAnalysis;
  70. namespace PRSDesktop
  71. {
  72. /// <summary>
  73. /// Interaction logic for Main.xaml
  74. /// </summary>
  75. public partial class MainWindow : IPanelHost
  76. {
  77. //private const int WM_LBUTTONDOWN = 0x201;
  78. private static PipeServer<string>? _client;
  79. private WaveIn? _audio;
  80. private bool _audioMuted;
  81. private MemoryStream? _audioStream;
  82. private readonly Dictionary<DateTime, Stream> _bitmaps = new();
  83. private Console? _console;
  84. private Dictionary<DateTime, Tuple<Rectangle, string>> _notes = new();
  85. //Dictionary<Type, IBasePanel> Panels = new Dictionary<Type, IBasePanel>();
  86. private DispatcherTimer? _recorder;
  87. private Process? _recordingnotes;
  88. private int _screenheight = 720;
  89. private int _screenleft;
  90. private int _screentop;
  91. private int _screenwidth = 1280;
  92. private readonly Dictionary<Guid, SecondaryWindow> _secondarywindows = new();
  93. private CoreTable? _timesheets;
  94. private DailyActivityHistory? ActivityHistory;
  95. private readonly List<Control> CurrentModules = new();
  96. private IBasePanel? CurrentPanel;
  97. private int CurrentPanel_Clicks;
  98. private int CurrentPanel_Keys;
  99. private string CurrentPanel_Label = "";
  100. private DateTime CurrentPanel_Ticks = DateTime.MinValue;
  101. private Fluent.RibbonTabItem? CurrentTab;
  102. private Fluent.Button? CurrentButton;
  103. private readonly int FRAMES_PER_SECOND = 10;
  104. private DatabaseType DatabaseType;
  105. private readonly Dictionary<int, int> messages = new();
  106. private readonly DispatcherTimer NotificationsWatchDog;
  107. private DateTime pausestarted = DateTime.MinValue;
  108. private readonly Scheduler scheduler = new() { Interval = new TimeSpan(0, 5, 0) };
  109. // We use a Guid for the StationID rather than an IP or Mac address
  110. // because we want true single-instance restriction. Using either of
  111. // the above allows for two instances on the once machine, and thus
  112. // double-counting in the Heartbeat() function
  113. private Login station = new() { StationID = Guid.NewGuid().ToString() };
  114. private TimeSpan totalpauses = new(0);
  115. private readonly int VIDEO_HEIGHT = 1080;
  116. private readonly int VIDEO_WIDTH = 1920;
  117. public MainWindow()
  118. {
  119. NotificationsWatchDog = new DispatcherTimer { IsEnabled = false };
  120. NotificationsWatchDog.Tick += Notifications_Tick;
  121. NotificationsWatchDog.Interval = new TimeSpan(0, 1, 0);
  122. ClientFactory.Notifications.AddHandler<Notification>(ReceiveNotification);
  123. ClientFactory.RegisterMailer(EmailType.IMAP, typeof(IMAPMailer));
  124. ClientFactory.RegisterMailer(EmailType.Exchange, typeof(ExchangeMailer));
  125. ClientFactory.OnLog += (_, message) => { Logger.Send(LogType.Information, ClientFactory.UserID, message); };
  126. HotKeyManager.Initialize();
  127. HotKeyManager.RegisterHotKey(Key.F1, ShowHelp);
  128. HotKeyManager.RegisterHotKey(Key.F5, ToggleRecording);
  129. HotKeyManager.RegisterHotKey(Key.F6, ShowRecordingNotes);
  130. HotKeyManager.RegisterHotKey(Key.F4, ToggleRecordingAudio);
  131. DatabaseType = App.DatabaseSettings.DatabaseType;
  132. switch (DatabaseType)
  133. {
  134. case DatabaseType.Standalone:
  135. ClientFactory.SetClientType(typeof(LocalClient<>), "Wpf", CoreUtils.GetVersion(), "");
  136. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  137. DbFactory.Logo = App.DatabaseSettings.Logo;
  138. break;
  139. case DatabaseType.Networked:
  140. ClientFactory.SetClientType(typeof(JsonClient<>), "Wpf", CoreUtils.GetVersion(),
  141. App.DatabaseSettings.URL, App.DatabaseSettings.Port, true);
  142. break;
  143. case DatabaseType.Local:
  144. ClientFactory.SetClientType(typeof(PipeIPCClient<>), "Wpf", CoreUtils.GetVersion(),
  145. DatabaseServerProperties.GetPipeName(App.DatabaseSettings.LocalServerName));
  146. break;
  147. }
  148. ThemeManager.BaseColor = Colors.CornflowerBlue;
  149. Progress.DisplayImage = PRSDesktop.Resources.splash_small.AsBitmapImage();
  150. try
  151. {
  152. var dbInfo = new Client<User>().Info();
  153. ThemeManager.BaseColor = (Color)ColorConverter.ConvertFromString(dbInfo.ColorScheme);
  154. if (dbInfo.Logo?.Any() == true)
  155. using (var ms = new MemoryStream(dbInfo.Logo))
  156. {
  157. Progress.DisplayImage = new Bitmap(ms).AsBitmapImage();
  158. }
  159. }
  160. catch
  161. {
  162. }
  163. InitializeComponent();
  164. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  165. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  166. SecondaryWindowStatus.Source = PRSDesktop.Resources.target.AsGrayScale().AsBitmapImage();
  167. ConsoleStatus.Source = PRSDesktop.Resources.view.AsGrayScale().AsBitmapImage();
  168. SelectTask.Source = PRSDesktop.Resources.uparrow.Invert().AsBitmapImage();
  169. Title = $"{(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  170. CheckForUpdates();
  171. Exception? startupException = null;
  172. Exception? loginException = null;
  173. ValidationResult? loginStatus = null;
  174. Progress.ShowModal("Loading PRS", progress =>
  175. {
  176. DynamicGridUtils.PreviewReport = (t, m) => { ReportUtils.PreviewReport(t, m, false, Security.IsAllowed<CanDesignReports>()); };
  177. DynamicGridUtils.PrintMenu = (e, s, m, p) => { ReportUtils.PrintMenu(e, s, m, Security.IsAllowed<CanDesignReports>(), p); };
  178. ImportFactory.Register(typeof(ExcelImporter<>), "Excel File", "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm");
  179. FormUtils.Register();
  180. Logger.Send(LogType.Information, "", "Registering Classes");
  181. progress.Report("Registering Classes");
  182. var tasks = new List<Task>
  183. {
  184. Task.Run(() => CoreUtils.RegisterClasses(typeof(KanbanGrid).Assembly)),
  185. Task.Run(() => CoreUtils.RegisterClasses()),
  186. Task.Run(() => ComalUtils.RegisterClasses()),
  187. Task.Run(() => ReportUtils.RegisterClasses()),
  188. Task.Run(() => ConfigurationUtils.RegisterClasses()),
  189. Task.Run(() => DynamicGridUtils.RegisterClasses()),
  190. Task.Run(() =>
  191. {
  192. ScriptDocument.DefaultAssemblies.AddRange(
  193. Assembly.Load("RoslynPad.Roslyn.Windows"),
  194. Assembly.Load("RoslynPad.Editor.Windows"),
  195. typeof(Control).Assembly,
  196. typeof(MessageBox).Assembly,
  197. typeof(SolidColorBrush).Assembly
  198. );
  199. ScriptDocument.Initialize();
  200. }),
  201. Task.Run(() => DatabaseUpdateScripts.RegisterScripts())
  202. };
  203. Task.WaitAll(tasks.ToArray());
  204. progress.Report("Configuring Application");
  205. RegisterModules(progress);
  206. if (DatabaseType == DatabaseType.Standalone)
  207. {
  208. progress.Report("Starting local database...");
  209. try
  210. {
  211. StartLocalDatabase(progress);
  212. }
  213. catch (Exception err)
  214. {
  215. startupException = new Exception(
  216. string.Format(
  217. "Unable to open database ({0})\n\n{1}\n\n{2}",
  218. App.DatabaseSettings.FileName,
  219. err.Message,
  220. err.StackTrace
  221. )
  222. );
  223. }
  224. }
  225. /*if (startupException == null && App.DatabaseSettings.Autologin)
  226. {
  227. progress.Report("Logging in...");
  228. if (App.DatabaseSettings.LoginType == LoginType.UserID)
  229. {
  230. ValidationResult? result;
  231. try
  232. {
  233. result = ClientFactory.Validate(App.DatabaseSettings.UserID, App.DatabaseSettings.Password);
  234. }
  235. catch(Exception e)
  236. {
  237. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error connecting to server: {CoreUtils.FormatException(e)}");
  238. loginException = new Exception("Error connecting to server.\nPlease check the server URL and port number.");
  239. result = null;
  240. }
  241. loginStatus = result;
  242. if (result == ValidationResult.INVALID)
  243. {
  244. loginException = new Exception("Unable to Login with User ID: " + App.DatabaseSettings.UserID);
  245. }
  246. }
  247. if(loginStatus == ValidationResult.VALID)
  248. {
  249. LoadCurrentEmployee();
  250. if(!CheckTimesheetBypass(false))
  251. {
  252. loginException = new Exception("You must clock on before logging in to PRS!");
  253. loginStatus = null;
  254. }
  255. }
  256. }*/
  257. });
  258. if (startupException != null)
  259. MessageBox.Show(startupException.Message);
  260. else if (loginException != null)
  261. MessageBox.Show(loginException.Message);
  262. if(DoLogin(App.DatabaseSettings.Autologin) == ValidationResult.VALID)
  263. {
  264. AfterLogin();
  265. }
  266. ProfileName.Content = App.Profile;
  267. URL.Content = DatabaseType switch
  268. {
  269. DatabaseType.Networked => URLCache.IsHTTPS ? App.DatabaseSettings.URL : $"{App.DatabaseSettings.URL} - Not Secure",
  270. DatabaseType.Standalone => App.DatabaseSettings.FileName,
  271. DatabaseType.Local => App.DatabaseSettings.LocalServerName,
  272. _ => ""
  273. };
  274. Progress.ShowModal("Starting Up", progress =>
  275. {
  276. if (loginStatus == ValidationResult.VALID && DatabaseType == DatabaseType.Standalone)
  277. {
  278. progress.Report("Starting Scheduler");
  279. scheduler.Start();
  280. }
  281. });
  282. }
  283. private void ApplyColorScheme()
  284. {
  285. Color baseColor;
  286. try
  287. {
  288. baseColor = (Color)ColorConverter.ConvertFromString(App.DatabaseSettings.ColorScheme);
  289. }
  290. catch
  291. {
  292. baseColor = Colors.CornflowerBlue;
  293. }
  294. ThemeManager.BaseColor = baseColor;
  295. BaseDynamicGrid.SelectionBackground = ThemeManager.SelectionBackgroundBrush;
  296. BaseDynamicGrid.SelectionForeground = ThemeManager.SelectionForegroundBrush;
  297. BaseDynamicGrid.FilterBackground = ThemeManager.FilterBackgroundBrush;
  298. //_ribbon.Background = new SolidColorBrush(Colors.White);
  299. //_ribbon.BackStageColor = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  300. ////_ribbon.BackStage.Background = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  301. ////_ribbon.BackStage.Foreground = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Foreground);
  302. UpdateRibbonColors();
  303. CurrentPanel?.Refresh();
  304. }
  305. #region Configuration
  306. /*
  307. protected override void OnSourceInitialized(EventArgs e)
  308. {
  309. base.OnSourceInitialized(e);
  310. var source = PresentationSource.FromVisual(this) as HwndSource;
  311. source?.AddHook(WndProc);
  312. }
  313. private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  314. {
  315. var message = (App.Message)msg;
  316. switch (message)
  317. {
  318. case App.Message.Maximise:
  319. WindowState = WindowState.Maximized;
  320. break;
  321. }
  322. return IntPtr.Zero;
  323. }*/
  324. private interface ISetupActionItem
  325. {
  326. }
  327. private class SetupActionItem : ISetupActionItem
  328. {
  329. public string Name { get; set; }
  330. public Action Action { get; set; }
  331. public Bitmap? Image { get; set; }
  332. public Type? SecurityToken { get; set; }
  333. public Func<bool>? CanView { get; set; }
  334. public SetupActionItem(string name, Action action, Bitmap? image)
  335. {
  336. Name = name;
  337. Action = action;
  338. Image = image;
  339. }
  340. public bool IsVisible() => (SecurityToken == null || Security.IsAllowed(SecurityToken)) && (CanView == null || CanView());
  341. public SetupActionItem SetSecurityToken<T>() where T : ISecurityDescriptor, new()
  342. {
  343. SecurityToken = typeof(T);
  344. return this;
  345. }
  346. public SetupActionItem SetCanView<T>() where T : Entity
  347. {
  348. return SetSecurityToken<AutoSecurityDescriptor<T, CanView<T>>>();
  349. }
  350. }
  351. private class SetupSeparator : ISetupActionItem { }
  352. private Dictionary<Fluent.RibbonTabItem, List<ISetupActionItem>> SetupActions = new();
  353. private List<ISetupActionItem> GetSetupActionList(Fluent.RibbonTabItem tab)
  354. {
  355. if (!SetupActions.TryGetValue(tab, out var list))
  356. {
  357. list = new();
  358. SetupActions[tab] = list;
  359. }
  360. return list;
  361. }
  362. private SetupActionItem AddSetupAction(Fluent.RibbonTabItem tab, string header, Action action, Bitmap? image)
  363. {
  364. var item = new SetupActionItem(header, action, image);
  365. GetSetupActionList(tab).Add(item);
  366. return item;
  367. }
  368. private SetupActionItem? AddSetupAction(Fluent.RibbonTabItem tab, string header, Action action, Bitmap? image, bool canView)
  369. {
  370. if (!canView)
  371. return null;
  372. return AddSetupAction(tab, header, action, image);
  373. }
  374. private void AddSetupSeparator(Fluent.RibbonTabItem tab)
  375. {
  376. GetSetupActionList(tab).Add(new SetupSeparator());
  377. }
  378. private void AddSetupModulesAndReports(Fluent.RibbonTabItem tab)
  379. {
  380. AddSetupSeparator(tab);
  381. AddSetupAction(tab, "Custom Modules", ManageModules, PRSDesktop.Resources.script).SetSecurityToken<CanCustomiseModules>();
  382. AddSetupAction(tab, "Reports", ManageReports, PRSDesktop.Resources.printer).SetSecurityToken<CanDesignReports>();
  383. }
  384. private void ConfigureMainScreen()
  385. {
  386. var button = _ribbon.FindVisualChildren<Fluent.DropDownButton>().FirstOrDefault();
  387. if (button != null)
  388. button.Visibility = Visibility.Collapsed;
  389. if (ClientFactory.UserGuid == Guid.Empty)
  390. _ribbonRow.Height = new GridLength(30, GridUnitType.Pixel);
  391. else
  392. _ribbonRow.Height = new GridLength(1, GridUnitType.Auto);
  393. var bMaps = Security.CanView<Equipment>()
  394. || Security.CanView<Job>()
  395. || Security.CanView<TimeSheet>()
  396. || Security.CanView<GPSTracker>();
  397. Progress.ShowModal(
  398. new ProgressSection(
  399. "Configuring Main Screen",
  400. () =>
  401. {
  402. ReportUtils.ExportDefinitions.Clear();
  403. ReportUtils.ExportDefinitions.Add(new ReportExportDefinition("Email Report", PRSDesktop.Resources.email, ReportExportType.PDF,
  404. DoEmailReport));
  405. //DockManager.SidePanelSize = OutstandingDailyReports(false) ? 0.00F : 30.00F;
  406. // Notifications Area
  407. SetVisibility(SendNotification, Security.CanView<Notification>());
  408. SetVisibility(Notifications, Security.CanView<Notification>());
  409. SetVisibility(TaskTracking, Security.IsAllowed<CanTrackTasksInDailyReport>());
  410. UserID.Content = ClientFactory.UserID;
  411. if (ClientFactory.PasswordExpiration != DateTime.MinValue)
  412. {
  413. var timeUntilExpiration = ClientFactory.PasswordExpiration - DateTime.Now;
  414. if (timeUntilExpiration.Days < 14)
  415. {
  416. PasswordExpiryNotice.Content = $"Password will expire in {timeUntilExpiration.Days} days!";
  417. PasswordExpiryNotice.Visibility = Visibility.Visible;
  418. }
  419. else
  420. {
  421. PasswordExpiryNotice.Visibility = Visibility.Collapsed;
  422. }
  423. }
  424. }
  425. ),
  426. new ProgressSection(
  427. "Configuring Quotes",
  428. () =>
  429. {
  430. //// Quotes Menu Bar
  431. SetVisibility(QuotesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  432. SetVisibility(QuotesMessagesButton, Security.CanView<Notification>());
  433. SetVisibility(QuotesTaskButton, Security.IsAllowed<CanViewTasks>());
  434. SetVisibility(QuotesAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  435. SetVisibility(QuotesMapButton, bMaps);
  436. SetVisibility(QuotesDailyReportButton,
  437. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  438. SetVisibility(QuotesButton, Security.CanView<Quote>());
  439. SetVisibleIfEither(QuotesTaskSeparator,
  440. new FrameworkElement[]
  441. {
  442. QuotesDashboardButton, QuotesMessagesButton, QuotesTaskButton, QuotesAttendanceButton, QuotesMapButton,
  443. QuotesDailyReportButton
  444. }, new FrameworkElement[] { QuotesButton });
  445. SetVisibility(KitsMasterList, Security.CanView<Kit>());
  446. SetVisibility(CostSheetsMasterList, Security.CanView<CostSheet>());
  447. SetVisibleIfEither(QuotesActionSeparator, new FrameworkElement[] { QuotesButton },
  448. new FrameworkElement[] { KitsMasterList, CostSheetsMasterList });
  449. SetVisibleIfAny(QuotesActions, QuotesButton, KitsMasterList, CostSheetsMasterList);
  450. AddSetupAction(QuotesTab, "Status Codes", QuoteStatusButton_Click, PRSDesktop.Resources.quotestatus,
  451. ClientFactory.IsSupported<Quote>() && Security.IsAllowed<CanModifyQuoteStatuses>());
  452. AddSetupAction(QuotesTab, "Design Sections", QuoteDesignSectionButton_Click, PRSDesktop.Resources.design,
  453. Security.CanView<QuoteDesignSection>());
  454. AddSetupSeparator(QuotesTab);
  455. AddSetupAction(QuotesTab, "Kit Conditions", KitConditionList_Click, PRSDesktop.Resources.kitcondition,
  456. Security.CanView<KitCondition>());
  457. AddSetupAction(QuotesTab, "Kit Formulae", KitFormulaeList_Click, PRSDesktop.Resources.kitformula,
  458. Security.CanView<KitFormula>());
  459. AddSetupAction(QuotesTab, "Cost Sheet Types", CostSheetTypeList_Click, PRSDesktop.Resources.costsheettype,
  460. Security.CanView<CostSheetType>());
  461. AddSetupAction(QuotesTab, "Cost Sheet Brands", CostSheetBrandList_Click, PRSDesktop.Resources.costsheetbrand,
  462. Security.CanView<CostSheetBrand>());
  463. AddSetupAction(QuotesTab, "Cost Sheet Sections", CostSheetSectionList_Click, PRSDesktop.Resources.costsheetsection,
  464. Security.CanView<CostSheetSection>());
  465. AddSetupSeparator(QuotesTab);
  466. AddSetupAction(QuotesTab, "Symbols", QuoteDiagramSymbols_Checked, PRSDesktop.Resources.pencil,
  467. Security.CanView<QuoteDiagramSymbol>());
  468. AddSetupAction(QuotesTab, "Symbol Types", QuoteDiagramSymbolTypes_Checked, PRSDesktop.Resources.attachment,
  469. Security.CanView<QuoteDiagramSymbol>());
  470. AddSetupAction(QuotesTab, "Dimension Types", QuoteTakeOffUnits_Click, PRSDesktop.Resources.box,
  471. Security.CanView<QuoteTakeOffUnit>());
  472. AddSetupModulesAndReports(QuotesTab);
  473. SetTabVisibleIfAny(QuotesTab, QuotesActions);
  474. }
  475. ),
  476. new ProgressSection(
  477. "Configuring Projects",
  478. () =>
  479. {
  480. SetVisibility(ProjectsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  481. SetVisibility(ProjectMessagesButton, Security.CanView<Notification>());
  482. SetVisibility(ProjectTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  483. SetVisibility(ProjectAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  484. SetVisibility(ProjectsMapButton, bMaps);
  485. SetVisibility(ProjectDailyReportButton,
  486. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  487. SetVisibility(ProjectsButton, Security.CanView<Job>());
  488. SetVisibility(ServiceButton, false);
  489. SetVisibleIfEither(ProjectTaskSeparator,
  490. new FrameworkElement[]
  491. {
  492. ProjectsDashboardButton, ProjectMessagesButton, ProjectTaskButton, ProjectAttendanceButton, ProjectsMapButton,
  493. ProjectDailyReportButton
  494. }, new FrameworkElement[] { QuotesButton, ProjectsButton, ServiceButton });
  495. AddSetupAction(ProjectsTab, "Job Statuses", JobStatusButton_Click, PRSDesktop.Resources.view,
  496. Security.CanView<JobStatus>());
  497. AddSetupAction(ProjectsTab, "Document MileStones", JobDocumentMileStoneButton_OnClick, PRSDesktop.Resources.revision,
  498. true);
  499. AddSetupAction(ProjectsTab, "Document Tags", JobDocumentTagButton_OnClick, PRSDesktop.Resources.checklist,
  500. true);
  501. AddSetupAction(ProjectsTab, "Financial Statuses", FinancialStatusButton_Click, PRSDesktop.Resources.view,
  502. Security.CanView<JobFinancial>());
  503. AddSetupAction(ProjectsTab, "Drawing Templates", DrawingTemplatesButton_Click, PRSDesktop.Resources.doc_misc,
  504. true);
  505. AddSetupModulesAndReports(ProjectsTab);
  506. //ProjectsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  507. //ProjectReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  508. SetTabVisibleIfAny(ProjectsTab, ProjectsButton, ServiceButton);
  509. }
  510. ),
  511. new ProgressSection(
  512. "Configuring Manufacturing",
  513. () =>
  514. {
  515. SetVisibility(ManufacturingDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  516. SetVisibility(ManufacturingMessagesButton, Security.CanView<Notification>());
  517. SetVisibility(ManufacturingTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  518. SetVisibility(ManufacturingAttendanceButton,
  519. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  520. SetVisibility(ManufacturingMapButton, bMaps);
  521. SetVisibility(ManufacturingDailyReportButton,
  522. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  523. SetVisibility(FactoryStatusButton,
  524. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket>() && Security.IsAllowed<CanViewFactoryStatus>());
  525. SetVisibility(FactoryAllocationButton,
  526. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket, ManufacturingPacketStage>() &&
  527. Security.IsAllowed<CanViewFactoryAllocation>());
  528. //SetVisibility(FactoryScheduleButton, ClientFactory.IsSupported<Booking>() && ClientFactory.IsEnabled<>());
  529. SetVisibility(FactoryFloorButton,
  530. ClientFactory.IsSupported<ManufacturingPacket>() && Security.IsAllowed<CanViewFactoryFloor>());
  531. //SetVisibility(FactoryReadyButton, ClientFactory.IsSupported<ManufacturingPacket>() && Security.IsAllowed<CanViewFactoryReadyToGo>());
  532. SetVisibleIfEither(ManufacturingTaskSeparator,
  533. new FrameworkElement[]
  534. {
  535. ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton, ManufacturingAttendanceButton,
  536. ManufacturingMapButton, ManufacturingDailyReportButton
  537. }, new FrameworkElement[] { FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton /* , FactoryReadyButton */ });
  538. SetVisibleIfAny(ManufacturingActions, ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton,
  539. ManufacturingAttendanceButton, ManufacturingDailyReportButton, FactoryStatusButton, FactoryAllocationButton,
  540. FactoryFloorButton);
  541. AddSetupAction(ManufacturingTab, "Factory Settings", FactorySetup_Click, PRSDesktop.Resources.factorysetup,
  542. ClientFactory.IsSupported<ManufacturingFactory>() && Security.IsAllowed<CanViewFactorySettings>());
  543. AddSetupAction(ManufacturingTab, "Manufacturing Templates", TemplateSetup_Click, PRSDesktop.Resources.template,
  544. Security.CanView<ManufacturingTemplate>());
  545. AddSetupAction(ManufacturingTab, "Manufacturing Trolleys", TrolleySetup_Click, PRSDesktop.Resources.trolley,
  546. Security.CanView<ManufacturingTrolley>());
  547. AddSetupAction(ManufacturingTab, "Lost Time Types", LostTimeSetup_Click, PRSDesktop.Resources.smiley,
  548. Security.CanView<ManufacturingLostTime>());
  549. //ManufacturingActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  550. //ManufacturingReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  551. AddSetupModulesAndReports(ManufacturingTab);
  552. SetTabVisibleIfAny(ManufacturingTab, FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton);
  553. }
  554. ),
  555. new ProgressSection(
  556. "Configuring Logistics",
  557. () =>
  558. {
  559. SetVisibility(LogisticsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  560. SetVisibility(LogisticsMessagesButton, Security.CanView<Notification>());
  561. SetVisibility(LogisticsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  562. SetVisibility(LogisticsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  563. SetVisibility(LogisticsMapButton, bMaps);
  564. SetVisibility(LogisticsDailyReportButton,
  565. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  566. SetVisibility(ReadyToGoItemsButton,
  567. ClientFactory.IsSupported<DeliveryItem>() && Security.IsAllowed<CanViewLogisticsReadyToGo>());
  568. SetVisibility(DispatchButton, Security.CanView<Shipment>() && Security.CanView<DeliveryItem>());
  569. SetVisibility(RequisitionsButton, Security.CanView<Requisition>());
  570. SetVisibility(DeliveriesButton, Security.CanView<Delivery>());
  571. SetVisibility(DeliveredItemsButton,
  572. ClientFactory.IsSupported<DeliveryItem>() && Security.IsAllowed<CanViewDeliveredOnSite>());
  573. SetVisibility(ConsignmentButton, Security.CanView<Consignment>());
  574. SetVisibleIfEither(LogisticsTaskSeparator1,
  575. new FrameworkElement[]
  576. {
  577. LogisticsDashboardButton, LogisticsMessagesButton, LogisticsTaskButton, LogisticsAttendanceButton, LogisticsMapButton,
  578. LogisticsDailyReportButton
  579. },
  580. new FrameworkElement[]
  581. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton });
  582. SetVisibleIfEither(LogisticsTaskSeparator2,
  583. new FrameworkElement[]
  584. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton },
  585. new FrameworkElement[] { ConsignmentButton });
  586. AddSetupAction(LogisticsTab, "Delivery Types", DeliveryTypesButton_Click, PRSDesktop.Resources.truck,
  587. Security.CanView<ConsignmentType>());
  588. AddSetupAction(LogisticsTab, "Consignment Types", ConsignmentTypesButton_Click, PRSDesktop.Resources.service,
  589. Security.CanView<DeliveryType>());
  590. //LogisticsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  591. //LogisticsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  592. AddSetupModulesAndReports(LogisticsTab);
  593. SetTabVisibleIfAny(LogisticsTab, DispatchButton, RequisitionsButton, DeliveriesButton, ReadyToGoItemsButton,
  594. DeliveredItemsButton,
  595. ConsignmentButton);
  596. }
  597. ),
  598. new ProgressSection(
  599. "Configuring Products",
  600. () =>
  601. {
  602. SetVisibility(ProductsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  603. SetVisibility(ProductsMessagesButton, Security.CanView<Notification>());
  604. SetVisibility(ProductsTaskButton, Security.CanView<Kanban>());
  605. SetVisibility(ProductsAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  606. SetVisibility(ProductsMapButton, bMaps);
  607. SetVisibility(ProductsDailyReportButton,
  608. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  609. SetVisibility(ProductsMasterList, Security.CanView<Product>());
  610. SetVisibility(StockLocationList, Security.CanView<StockLocation>());
  611. SetVisibility(StockMovementList, Security.CanView<StockMovement>());
  612. SetVisibleIfEither(ProductsTaskSeparator,
  613. new FrameworkElement[]
  614. {
  615. ProductsDashboardButton, ProductsMessagesButton, ProductsTaskButton, ProductsAttendanceButton, ProductsMapButton,
  616. ProductsDailyReportButton
  617. }, new FrameworkElement[] { ProductsMasterList, StockLocationList });
  618. SetVisibleIfAny(ProductActions, ProductsDashboardButton, ProductsMessagesButton, ProductsTaskButton, ProductsAttendanceButton,
  619. ProductsDailyReportButton, ProductsMasterList, StockLocationList, StockMovementList);
  620. AddSetupAction(ProductTab, "Units of Measure", ProductDimensionUnitsList_Click, PRSDesktop.Resources.unitofmeasure,
  621. Security.CanView<ProductDimensionUnit>());
  622. AddSetupAction(ProductTab, "Product Groups", ProductGroupsList_Click, PRSDesktop.Resources.productgroup,
  623. Security.CanView<ProductGroup>());
  624. AddSetupAction(ProductTab, "Product Styles", ProductStylesList_Click, PRSDesktop.Resources.palette,
  625. Security.CanView<ProductStyle>());
  626. AddSetupAction(ProductTab, "Stock Areas", StockAreasList_Click, PRSDesktop.Resources.rack,
  627. Security.CanView<StockArea>());
  628. AddSetupAction(ProductTab, "Stock Warehouses", StockWarehouseList_Click, PRSDesktop.Resources.factorysetup,
  629. Security.CanView<StockWarehouse>());
  630. AddSetupModulesAndReports(ProductTab);
  631. SetTabVisibleIfAny(ProductTab, ProductActions);
  632. }
  633. ),
  634. new ProgressSection(
  635. "Configuring Human Resources",
  636. () =>
  637. {
  638. SetVisibility(HumanResourcesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  639. SetVisibility(HumanResourcesMessagesButton, Security.CanView<Notification>());
  640. SetVisibility(HumanResourcesTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  641. SetVisibility(HumanResourcesAttendanceButton,
  642. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  643. SetVisibility(HumanResourcesMapButton, bMaps);
  644. SetVisibility(HumanResourcesDailyReportButton,
  645. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  646. SetVisibility(AssignmentsButton, Security.CanView<Assignment>());
  647. SetVisibility(TimesheetsButton, Security.CanView<TimeSheet>());
  648. SetVisibility(LeaveRequestsButton, Security.CanView<LeaveRequest>());
  649. SetVisibility(OrgChartButton,
  650. ClientFactory.IsSupported<Employee>()
  651. && (
  652. Security.IsAllowed<CanViewOrgChartByEmployee>()
  653. || Security.IsAllowed<CanViewOrgChartByPosition>()
  654. || Security.IsAllowed<CanViewOrgChartByRole>()
  655. )
  656. );
  657. SetVisibleIfEither(HumanResourcesTaskSeparator,
  658. new FrameworkElement[]
  659. {
  660. HumanResourcesDashboardButton, HumanResourcesMessagesButton, HumanResourcesTaskButton, HumanResourcesAttendanceButton,
  661. HumanResourcesMapButton, HumanResourcesDailyReportButton
  662. }, new FrameworkElement[] { AssignmentsButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton });
  663. SetVisibleIfAny(HumanResourcesActions, HumanResourcesDashboardButton, HumanResourcesTaskButton,
  664. HumanResourcesAttendanceButton,
  665. HumanResourcesDailyReportButton, AssignmentsButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton);
  666. SetVisibility(UsersButton, Security.CanView<User>());
  667. SetVisibility(EmployeesButton, Security.CanView<Employee>());
  668. AddSetupAction(HumanResourcesTab, "Security Groups", SecurityGroupsButton_Click, PRSDesktop.Resources.securitygroup,
  669. Security.CanView<SecurityGroup>());
  670. AddSetupSeparator(HumanResourcesTab);
  671. AddSetupAction(HumanResourcesTab, "Employee Groups", GroupsSetup_Click, PRSDesktop.Resources.employees,
  672. Security.CanView<EmployeeGroup>());
  673. AddSetupAction(HumanResourcesTab, "Positions", PositionsSetup_Click, PRSDesktop.Resources.position,
  674. Security.CanView<EmployeePosition>());
  675. AddSetupAction(HumanResourcesTab, "Roles", RolesSetup_Click, PRSDesktop.Resources.employeerole,
  676. Security.CanView<EmployeeRole>());
  677. AddSetupAction(HumanResourcesTab, "Teams", EmployeeTeamsButton_Click, PRSDesktop.Resources.team,
  678. Security.CanView<EmployeeTeam>());
  679. AddSetupAction(HumanResourcesTab, "Activities", ActivityMenu_Click, PRSDesktop.Resources.quality,
  680. Security.CanView<Activity>());
  681. AddSetupAction(HumanResourcesTab, "Qualifications", QualificationMenu_Click, PRSDesktop.Resources.certificate,
  682. Security.CanView<Qualification>());
  683. AddSetupSeparator(HumanResourcesTab);
  684. AddSetupAction(HumanResourcesTab, "Overtime Rules", OvertimeRulesButton_Click, PRSDesktop.Resources.overtime,
  685. Security.CanView<OvertimeRule>());
  686. AddSetupAction(HumanResourcesTab, "Standard Leave", StandardLeaveButton_Click, PRSDesktop.Resources.fireworks,
  687. Security.CanView<StandardLeave>());
  688. SetVisibleIfEither(HumanResourcesSetupSeparator1,
  689. new FrameworkElement[] { AssignmentsButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton },
  690. new FrameworkElement[] { UsersButton, EmployeesButton });
  691. //HumanResourcesActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  692. //HumanResourcesReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  693. AddSetupModulesAndReports(HumanResourcesTab);
  694. SetTabVisibleIfAny(HumanResourcesTab, AssignmentsButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton, UsersButton, EmployeesButton);
  695. }
  696. ),
  697. new ProgressSection(
  698. "Configuring Accounts",
  699. () =>
  700. {
  701. SetVisibility(AccountsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  702. SetVisibility(AccountsMessagesButton, Security.CanView<Notification>());
  703. SetVisibility(AccountsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  704. SetVisibility(AccountsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  705. SetVisibility(AccountsMapButton, bMaps);
  706. SetVisibility(AccountsDailyReportButton,
  707. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  708. SetVisibility(CustomerList, ClientFactory.IsSupported<Customer>() && Security.CanView<Customer>());
  709. SetVisibility(InvoiceList, ClientFactory.IsSupported<Invoice>() && Security.CanView<Invoice>());
  710. SetVisibility(ReceiptList, ClientFactory.IsSupported<Receipt>() && Security.CanView<Receipt>());
  711. SetVisibility(SupplierList, ClientFactory.IsSupported<Supplier>() && Security.CanView<Supplier>());
  712. SetVisibility(PurchasesList, ClientFactory.IsSupported<PurchaseOrder>() && Security.CanView<PurchaseOrder>());
  713. SetVisibility(BillsList, ClientFactory.IsSupported<Bill>() && Security.CanView<Bill>());
  714. SetVisibility(PaymentsList, ClientFactory.IsSupported<Payment>() && Security.CanView<Payment>());
  715. SetVisibleIfEither(AccountsTaskSeparator1,
  716. new FrameworkElement[]
  717. {
  718. AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton, AccountsAttendanceButton, AccountsMapButton,
  719. AccountsDailyReportButton
  720. }, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList });
  721. SetVisibleIfEither(AccountsTaskSeparator2, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList },
  722. new FrameworkElement[] { SupplierList, PurchasesList, BillsList, PaymentsList });
  723. SetVisibleIfAny(AccountsActions, AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton,
  724. AccountsAttendanceButton,
  725. AccountsDailyReportButton, CustomerList, InvoiceList, ReceiptList, SupplierList, PurchasesList, BillsList, PaymentsList);
  726. AddSetupAction(AccountsTab, "Contact Types", ContactTypeList_Click, PRSDesktop.Resources.contacttype,
  727. ClientFactory.IsSupported<Contact>() && Security.CanView<ContactType>());
  728. AddSetupAction(AccountsTab, "Tax Codes", TaxCodeList_Click, PRSDesktop.Resources.taxcode,
  729. ClientFactory.IsSupported<GLCode>() && Security.CanView<TaxCode>());
  730. AddSetupAction(AccountsTab, "Receipt Types", ReceiptTypeList_Click, PRSDesktop.Resources.receipt,
  731. ClientFactory.IsSupported<GLCode>() && Security.CanView<ReceiptType>());
  732. AddSetupAction(AccountsTab, "Payment Types", PaymentTypeList_Click, PRSDesktop.Resources.payment,
  733. ClientFactory.IsSupported<GLCode>() && Security.CanView<PaymentType>());
  734. AddSetupAction(AccountsTab, "Cost Centres", CostCentresList_Click, PRSDesktop.Resources.costcentre,
  735. ClientFactory.IsSupported<CostCentre>() && Security.CanView<CostCentre>());
  736. AddSetupAction(AccountsTab, "GL Codes", GLCodesList_Click, PRSDesktop.Resources.glcode,
  737. ClientFactory.IsSupported<GLCode>() && Security.CanView<GLCode>());
  738. AddSetupAction(AccountsTab, "Purchase Order Categories", PurchaseOrderCategoriesButton_Click, PRSDesktop.Resources.service,
  739. ClientFactory.IsSupported<PurchaseOrderCategory>() && Security.CanView<PurchaseOrderCategory>());
  740. //AccountsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  741. //AccountsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  742. AddSetupModulesAndReports(AccountsTab);
  743. SetTabVisibleIfAny(AccountsTab, CustomerList, InvoiceList, ReceiptList, SupplierList, PurchasesList, BillsList, PaymentsList);
  744. }
  745. ),
  746. new ProgressSection(
  747. "Configuring Equipment",
  748. () =>
  749. {
  750. SetVisibility(EquipmentDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  751. SetVisibility(EquipmentMessagesButton, Security.CanView<Notification>());
  752. SetVisibility(EquipmentTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  753. SetVisibility(EquipmentAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  754. SetVisibility(EquipmentMapButton, bMaps);
  755. SetVisibility(EquipmentDailyReportButton,
  756. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  757. SetVisibility(EquipmentButton, ClientFactory.IsSupported<Equipment>() && Security.CanView<Equipment>());
  758. SetVisibleIfEither(EquipmentTaskSeparator,
  759. new FrameworkElement[]
  760. {
  761. EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton, EquipmentAttendanceButton, EquipmentMapButton,
  762. EquipmentDailyReportButton
  763. }, new FrameworkElement[] { EquipmentButton });
  764. SetVisibleIfAny(EquipmentActions, EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton,
  765. EquipmentAttendanceButton, EquipmentDailyReportButton, EquipmentButton);
  766. SetVisibility(TrackersMasterList, Security.CanView<GPSTracker>());
  767. AddSetupAction(EquipmentTab, "Tracker Types", TrackerTypes_Click, PRSDesktop.Resources.milestone,
  768. Security.CanView<GPSTrackerType>());
  769. AddSetupAction(EquipmentTab, "Stickers", Stickers_Click, PRSDesktop.Resources.barcode,
  770. Security.CanView<WebSticker>());
  771. AddSetupAction(EquipmentTab, "Digital Keys", DigitalKeys_Click, PRSDesktop.Resources.key,
  772. Security.CanView<DigitalKey>());
  773. AddSetupAction(EquipmentTab, "Equipment Groups", EquipmentGroupList_Click, PRSDesktop.Resources.specifications,
  774. Security.CanView<EquipmentGroup>());
  775. //EquipmentActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  776. //EquipmentReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  777. AddSetupModulesAndReports(EquipmentTab);
  778. SetTabVisibleIfAny(EquipmentTab, EquipmentButton, TrackersMasterList);
  779. }
  780. ),
  781. new ProgressSection(
  782. "Configuring Dashboards",
  783. () =>
  784. {
  785. SetVisibility(DashboardsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  786. SetVisibility(DashboardMessagesButton, Security.CanView<Notification>());
  787. SetVisibility(DashboardsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  788. SetVisibility(DashboardsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  789. SetVisibility(DashboardsMapButton, bMaps);
  790. SetVisibility(DashboardsDailyReportButton,
  791. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  792. SetVisibility(FactoryProductivityButton,
  793. ClientFactory.IsSupported<ManufacturingHistory>() && Security.IsAllowed<CanViewFactoryKPIs>());
  794. SetVisibility(TemplateAnalysisButton,
  795. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>() &&
  796. Security.IsAllowed<CanViewTemplateAnalysis>());
  797. SetVisibility(FactoryAnalysisButton,
  798. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>() && Security.IsAllowed<CanViewFactoryAnalysis>());
  799. SetVisibility(DatabaseActivityButton,
  800. ClientFactory.IsSupported<UserTracking>() && Security.IsAllowed<CanViewDatabaseActivity>());
  801. SetVisibility(UserActivityButton, ClientFactory.IsSupported<ModuleTracking>() && Security.IsAllowed<CanViewUserActivity>());
  802. SetVisibility(QAAnalysisButton, Security.IsAllowed<CanViewDigitalFormsDashbaord>());
  803. SetVisibility(QuickStatusButton, Security.IsAllowed<CanViewQuickStatus>());
  804. SetVisibleIfEither(DashboardsTaskSeparator,
  805. new FrameworkElement[]
  806. {
  807. DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton, DashboardsAttendanceButton,
  808. DashboardsMapButton,
  809. DashboardsDailyReportButton
  810. },
  811. new FrameworkElement[]
  812. {
  813. FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton,
  814. QAAnalysisButton, QuickStatusButton
  815. });
  816. SetVisibleIfAny(DashboardsActions, DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton,
  817. DashboardsAttendanceButton, DashboardsDailyReportButton, FactoryProductivityButton, TemplateAnalysisButton,
  818. FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton, QAAnalysisButton, QuickStatusButton);
  819. //DashboardsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  820. //DashboardsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  821. AddSetupModulesAndReports(DashboardsTab);
  822. SetVisibleIfAny(DashboardsTab, FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton,
  823. DatabaseActivityButton,
  824. UserActivityButton, QAAnalysisButton, QuickStatusButton);
  825. }
  826. ),
  827. new ProgressSection(
  828. "Configuring System Modules",
  829. () =>
  830. {
  831. SetVisibility(CompanyInformation, Security.CanView<CompanyInformation>());
  832. SetVisibleIfAny(BackstageSeparator0, CompanyInformation);
  833. SetVisibility(SecurityDefaultsButton,
  834. ClientFactory.IsSupported<GlobalSecurityToken>() && Security.IsAllowed<CanCustomiseSecurityDefaults>());
  835. SetVisibleIfAny(BackstageSeparator1, SecurityDefaultsButton);
  836. BackstageSeparator1a.Visibility = Visibility.Visible;
  837. SystemLogsButton.Visibility = Visibility.Visible;
  838. SetVisibility(DocumentTypeList, ClientFactory.IsSupported<DocumentType>() && Security.IsAllowed<CanViewDocumentTypes>());
  839. SetVisibility(DocumentList, ClientFactory.IsSupported<Document>() && Security.IsAllowed<CanViewDocumentList>());
  840. SetVisibility(QAFormSetupButton,
  841. ClientFactory.IsSupported<DigitalForm>() && Security.IsAllowed<CanAdministerDigitalFormsLibrary>());
  842. SetVisibility(TaskSetupButton, ClientFactory.IsSupported<KanbanType>() && Security.IsAllowed<CanViewTaskTypes>());
  843. SetVisibleIfAny(BackstageSeparator2, DocumentTypeList, DocumentList, QAFormSetupButton);
  844. SetVisibility(VideoRecordingButton, Security.IsAllowed<CanRecordScreen>());
  845. LogoutButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  846. LoginButton.Visibility = ClientFactory.UserGuid != Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  847. EditDetailsButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  848. SetupDock<CanViewContactsDock>(ContactDock, Contacts);
  849. SetupDock<CanViewJobDock>(JobDock, Jobs);
  850. SetupDock<CanViewConsignmentDock>(ConsignmentDock, Consignments);
  851. SetupDock<CanViewDeliveryDock>(DeliveryDock, Deliveries);
  852. SetupDock<CanViewProductDock>(ProductLookupDock, ProductLookup);
  853. SetupDock<CanViewDigitalFormsDock>(DigitalFormsDock, DigitalForms);
  854. _ribbon.InvalidateArrange();
  855. }
  856. )
  857. );
  858. }
  859. private void SetupDock<TSecurityDescriptor>(LayoutAnchorable layout, IDockPanel dock)
  860. where TSecurityDescriptor : ISecurityDescriptor, new()
  861. {
  862. if (Security.IsAllowed<TSecurityDescriptor>())
  863. {
  864. if(!DockGroup.Children.Any(x => x == layout))
  865. {
  866. DockGroup.Children.Add(layout);
  867. }
  868. if (layout.IsVisible && (ClientFactory.UserGuid != Guid.Empty))
  869. dock.Setup();
  870. }
  871. else
  872. {
  873. DockGroup.RemoveChild(layout);
  874. }
  875. }
  876. private void LoadApplicationState()
  877. {
  878. if (ClientFactory.UserGuid != Guid.Empty)
  879. {
  880. _ribbon.IsCollapsed = false;
  881. if (OutstandingDailyReports(false))
  882. {
  883. MessageBox.Show("There are outstanding Daily Reports that must be filled out before continuing!" +
  884. "\n\nAccess to PRS is restricted until this is corrected.",
  885. "Outstanding Reports"
  886. );
  887. var dailyReportPanel = LoadWindow<DailyReport>(ProjectDailyReportButton);
  888. dailyReportPanel.OnTimeSheetConfirmed += e =>
  889. {
  890. if (!OutstandingDailyReports(true))
  891. {
  892. ConfigureMainScreen();
  893. LoadApplicationState();
  894. }
  895. };
  896. return;
  897. }
  898. using (new WaitCursor())
  899. {
  900. _ribbon.IsCollapsed = false;
  901. LoadInitialWindow();
  902. }
  903. }
  904. }
  905. private void LoadInitialWindow()
  906. {
  907. var app = new LocalConfiguration<AppSettings>().Load();
  908. if (app.Settings.ContainsKey("CurrentPanel"))
  909. {
  910. try
  911. {
  912. var bFound = false;
  913. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  914. if (module.Length == 2)
  915. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  916. {
  917. if (String.Equals(tab.Header,module.First()))
  918. {
  919. _ribbon.SelectedTabItem = tab;
  920. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  921. {
  922. foreach (var item in bar.Items)
  923. {
  924. var button = item as Fluent.Button;
  925. if (button != null && String.Equals(button.Header, module.Last()))
  926. {
  927. bFound = true;
  928. button.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
  929. break;
  930. }
  931. }
  932. if (bFound)
  933. break;
  934. }
  935. }
  936. if (bFound)
  937. break;
  938. }
  939. }
  940. catch (Exception e)
  941. {
  942. MessageBox.Show(string.Format("Unable to Load {0}!\n\n{1}\n{2}", app.Settings["CurrentPanel"], e.Message, e.StackTrace));
  943. }
  944. }
  945. }
  946. private void _ribbon_OnLoaded(object sender, RoutedEventArgs e)
  947. {
  948. _ribbon.SelectedTabItem = CurrentTab;
  949. }
  950. private void LoadSecondaryWindows()
  951. {
  952. if (ClientFactory.UserGuid != Guid.Empty)
  953. {
  954. var windows = App.DatabaseSettings.SecondaryWindows;
  955. foreach (var key in windows.Keys.ToArray())
  956. {
  957. _secondarywindows[key] = new SecondaryWindow(
  958. key,
  959. windows[key].Item1,
  960. windows[key].Item2,
  961. windows[key].Item3,
  962. windows[key].Item4,
  963. windows[key].Item5,
  964. windows[key].Item6
  965. );
  966. _secondarywindows[key].Closed += (o, e) => { _secondarywindows.Remove(key); };
  967. _secondarywindows[key].Show();
  968. }
  969. }
  970. else
  971. {
  972. foreach (var key in _secondarywindows.Keys.ToArray())
  973. {
  974. App.IsClosing = true;
  975. _secondarywindows[key].Close();
  976. App.IsClosing = false;
  977. }
  978. }
  979. }
  980. private Fluent.RibbonTabItem GetTabItem(FrameworkElement? sender)
  981. {
  982. if (sender == null)
  983. throw new Exception("No Tab Found!");
  984. if (sender is Fluent.RibbonTabItem)
  985. return (Fluent.RibbonTabItem)sender;
  986. return GetTabItem(sender.Parent as FrameworkElement);
  987. }
  988. private T LoadWindow<T>(Fluent.Button sender) where T : IBasePanel, new()
  989. {
  990. using (new WaitCursor())
  991. {
  992. UnloadWindow();
  993. CurrentTab = GetTabItem(sender);
  994. CurrentButton = sender;
  995. //CurrentButton.IsSelected = true;
  996. UpdateRibbonColors();
  997. var panel = new T();
  998. CurrentPanel = panel;
  999. InitializePanelProperties(panel);
  1000. CurrentPanel.IsReady = false;
  1001. CurrentPanel.Setup();
  1002. CurrentPanel.IsReady = true;
  1003. CurrentPanel.OnUpdateDataModel += (s, m) => {
  1004. ReloadModules(s, m);
  1005. ReloadReports(s, m);
  1006. };
  1007. CurrentPanel_Label = sender.Header?.ToString() ?? "";
  1008. CurrentPanel_Ticks = DateTime.Now;
  1009. ContentControl.Content = CurrentPanel;
  1010. Title =
  1011. $"{CurrentPanel_Label} - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1012. if (sender != null)
  1013. {
  1014. var model = CurrentPanel.DataModel(Selection.None);
  1015. var section = CurrentPanel.SectionName;
  1016. ReloadModules(section, model);
  1017. ReloadReports(section, model);
  1018. }
  1019. CurrentPanel.Refresh();
  1020. if (CurrentPanel is NotificationPanel)
  1021. {
  1022. Logger.Send(LogType.Information, ClientFactory.UserID, "Disabling Heartbeat");
  1023. NotificationsWatchDog.IsEnabled = false;
  1024. Notifications.Visibility = Visibility.Collapsed;
  1025. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  1026. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  1027. }
  1028. else
  1029. {
  1030. ReloadNotifications();
  1031. }
  1032. if (sender != null)
  1033. {
  1034. var settings = new LocalConfiguration<AppSettings>().Load();
  1035. var module = string.Format("{0} / {1}", CurrentTab?.Header, sender.Header);
  1036. if (!settings.Settings.ContainsKey("CurrentPanel") || module != settings.Settings["CurrentPanel"])
  1037. {
  1038. settings.Settings["CurrentPanel"] = module;
  1039. try
  1040. {
  1041. new LocalConfiguration<AppSettings>().Save(settings);
  1042. }
  1043. catch (Exception e)
  1044. {
  1045. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1046. }
  1047. }
  1048. }
  1049. //stopwatch.Stop();
  1050. //Logger.Send(LogType.Information, ClientFactory.UserID, String.Format("Loading {0} to took {1} ms", sender != null ? sender.Label : module, stopwatch.ElapsedMilliseconds));
  1051. return panel;
  1052. }
  1053. }
  1054. private void UpdateRibbonColors()
  1055. {
  1056. foreach (var tab in _ribbon.Tabs)
  1057. {
  1058. bool bFound = false;
  1059. foreach (var grp in tab.Groups)
  1060. {
  1061. foreach (var btn in grp.Items)
  1062. {
  1063. if (btn is Fluent.Button fluentbutton)
  1064. {
  1065. bFound = bFound || (btn == CurrentButton);
  1066. fluentbutton.Background = (btn == CurrentButton) ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1067. fluentbutton.Foreground = (btn == CurrentButton) ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1068. }
  1069. }
  1070. tab.Background = bFound ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1071. tab.Foreground = bFound ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1072. }
  1073. }
  1074. }
  1075. private static void StartLocalDatabase(IProgress<string> progress)
  1076. {
  1077. var dirName = Path.GetDirectoryName(App.DatabaseSettings.FileName);
  1078. if (!Directory.Exists(dirName) && dirName != null)
  1079. Directory.CreateDirectory(dirName);
  1080. var FileName = App.DatabaseSettings.FileName;
  1081. var Exists = File.Exists(FileName);
  1082. progress.Report("Configuring Stores");
  1083. DbFactory.Stores = CoreUtils.TypeList(
  1084. new[]
  1085. {
  1086. typeof(DocumentStore).Assembly,
  1087. typeof(EquipmentStore).Assembly
  1088. },
  1089. myType =>
  1090. myType.IsClass
  1091. && !myType.IsAbstract
  1092. && !myType.IsGenericType
  1093. && myType.GetInterfaces().Contains(typeof(IStore))
  1094. ).ToArray();
  1095. DbFactory.Provider = new SQLiteProvider(App.DatabaseSettings.FileName);
  1096. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  1097. DbFactory.Logo = App.DatabaseSettings.Logo;
  1098. progress.Report("Starting Local Database");
  1099. var deviceid = DeviceID.Value(App.DatabaseSettings.Port.ToString(), null); //, (m) => Logger.Send(LogType.Information, "", m));
  1100. DbFactory.Start(deviceid);
  1101. progress.Report("Checking Database");
  1102. var users = DbFactory.Provider.Load<User>();
  1103. if (!users.Any())
  1104. {
  1105. var user = new User { UserID = "ADMIN", Password = "admin" };
  1106. DbFactory.Provider.Save(user);
  1107. var employee = DbFactory.Provider.Load(new Filter<Employee>(x => x.Code).IsEqualTo("ADMIN")).FirstOrDefault();
  1108. employee ??= new Employee { Code = "ADMIN", Name = "Administrator Account" };
  1109. employee.UserLink.ID = user.ID;
  1110. DbFactory.Provider.Save(employee);
  1111. }
  1112. StoreUtils.GoogleAPIKey = App.DatabaseSettings.GoogleAPIKey;
  1113. JobStore.AutoIncrementPrefix = App.DatabaseSettings.JobPrefix;
  1114. PurchaseOrderStore.AutoIncrementPrefix = App.DatabaseSettings.PurchaseOrderPrefix;
  1115. }
  1116. #endregion
  1117. #region Login Management
  1118. private ValidationResult? DoLogin(bool autoLogin)
  1119. {
  1120. ValidationResult? result = null;
  1121. if (autoLogin)
  1122. {
  1123. if (App.DatabaseSettings.LoginType == LoginType.UserID)
  1124. {
  1125. try
  1126. {
  1127. result = ClientFactory.Validate(App.DatabaseSettings.UserID, App.DatabaseSettings.Password);
  1128. }
  1129. catch (Exception e)
  1130. {
  1131. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error connecting to server: {CoreUtils.FormatException(e)}");
  1132. MessageBox.Show("Error connecting to server.\nPlease check the server URL and port number.");
  1133. result = null;
  1134. }
  1135. if (result == ValidationResult.INVALID)
  1136. {
  1137. MessageBox.Show("Unable to Login with User ID: " + App.DatabaseSettings.UserID);
  1138. }
  1139. }
  1140. }
  1141. if (result != ValidationResult.VALID)
  1142. {
  1143. var login = new PinLogin(CoreUtils.GetVersion(), result ?? ValidationResult.INVALID);
  1144. if (login.ShowDialog() == true)
  1145. {
  1146. result = ValidationResult.VALID;
  1147. }
  1148. }
  1149. return result ?? ValidationResult.INVALID;
  1150. }
  1151. /// <summary>
  1152. /// To be called after <see cref="DoLogin(bool)"/> and if a valid login session exists. Configures the main screen and loads the windows.
  1153. /// </summary>
  1154. private void AfterLogin()
  1155. {
  1156. LoadCurrentEmployee();
  1157. if (CheckTimesheetBypass(true))
  1158. {
  1159. UpdateCurrentLogin();
  1160. }
  1161. else
  1162. {
  1163. MessageBox.Show("You must clock on before logging in to PRS!");
  1164. ClientFactory.InvalidateUser();
  1165. App.EmployeeID = Guid.Empty;
  1166. }
  1167. ApplyColorScheme();
  1168. ConfigureMainScreen();
  1169. LoadApplicationState();
  1170. LoadSecondaryWindows();
  1171. //if (_ribbon.Menu.IsVisible)
  1172. //{
  1173. // _ribbon.;
  1174. //}
  1175. }
  1176. /// <summary>
  1177. /// Creates a new <see cref="Login"/> if one does not already exist. Otherwise, updates the <see cref="Login"/> entry in the database with new Station ID.
  1178. /// </summary>
  1179. private void UpdateCurrentLogin()
  1180. {
  1181. if (CoreUtils.GetVersion().Equals("???"))
  1182. return;
  1183. // Register this station with the Server
  1184. // Later on, the heartbeat will check to make sure
  1185. // that the StationID hasn't changed. If it has,
  1186. // then we've logged in somewhere else and we'll
  1187. // drop out of this station
  1188. var curr = new Client<Login>().Query(
  1189. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  1190. null
  1191. ).Rows.FirstOrDefault();
  1192. if (curr != null)
  1193. {
  1194. var c = curr.ToObject<Login>();
  1195. c.StationID = station.StationID;
  1196. station = c;
  1197. }
  1198. else
  1199. {
  1200. station.User.ID = ClientFactory.UserGuid;
  1201. station.TimeStamp = DateTime.Now;
  1202. }
  1203. new Client<Login>().Save(station, "", (o, e) => { });
  1204. }
  1205. private void LoadCurrentEmployee()
  1206. {
  1207. var me = new Client<Employee>().Query(
  1208. new Filter<Employee>(x => x.UserID).IsEqualTo(ClientFactory.UserGuid),
  1209. new Columns<Employee>(x => x.ID).Add(x => x.Email)
  1210. );
  1211. App.EmployeeID = me.Rows.FirstOrDefault()?.Get<Employee,Guid>(x=>x.ID) ?? Guid.Empty;
  1212. App.EmployeeEmail = me.Rows.FirstOrDefault()?.Get<Employee,String>(x=>x.Email) ?? "";
  1213. }
  1214. private void ExecuteLogout()
  1215. {
  1216. new Client<Login>().Delete(station, "");
  1217. station.ID = Guid.Empty;
  1218. App.EmployeeID = Guid.Empty;
  1219. }
  1220. /// <summary>
  1221. /// Logs the user out and unloads windows
  1222. /// </summary>
  1223. /// <param name="message">A message to display as the reason for logging out, or <c>null</c> for no message.</param>
  1224. private bool Logout(string? message = null)
  1225. {
  1226. FinalizeAutoTimesheet();
  1227. UnloadWindow();
  1228. if (DatabaseType == DatabaseType.Standalone && !CoreUtils.GetVersion().Equals("???"))
  1229. scheduler.Stop();
  1230. if (!CoreUtils.GetVersion().Equals("???"))
  1231. if (station.ID != Guid.Empty)
  1232. {
  1233. ExecuteLogout();
  1234. }
  1235. ClearTrackingKanban();
  1236. ClientFactory.InvalidateUser();
  1237. ConfigureMainScreen();
  1238. LoadSecondaryWindows();
  1239. if(message != null)
  1240. {
  1241. MessageBox.Show(message);
  1242. }
  1243. if (DoLogin(false) == ValidationResult.VALID)
  1244. {
  1245. AfterLogin();
  1246. }
  1247. return true;
  1248. }
  1249. #endregion
  1250. #region Timesheets
  1251. private void RefreshTimeSheets()
  1252. {
  1253. if (App.EmployeeID == Guid.Empty)
  1254. return;
  1255. var filter = new Filter<TimeSheet>(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID);
  1256. filter = filter.And(new Filter<TimeSheet>(x => x.Confirmed).IsEqualTo(DateTime.MinValue).Or(x => x.Date).IsEqualTo(DateTime.Today));
  1257. _timesheets = new Client<TimeSheet>().Query(
  1258. filter,
  1259. new Columns<TimeSheet>(
  1260. x => x.ID,
  1261. x => x.Date,
  1262. x => x.Finish
  1263. )
  1264. );
  1265. }
  1266. private CoreTable GetTimesheet()
  1267. {
  1268. return new Client<TimeSheet>().Query(
  1269. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today)
  1270. .And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID)
  1271. .And(x => x.Finish).IsEqualTo(TimeSpan.Zero)
  1272. );
  1273. }
  1274. private bool CheckTimesheetBypass(bool message)
  1275. {
  1276. if (!ClientFactory.IsSupported<TimeSheet>())
  1277. return true;
  1278. var isClockedOn = IsClockedOn();
  1279. if (!Security.IsAllowed<CanBypassTimeBench>())
  1280. {
  1281. if (!isClockedOn)
  1282. {
  1283. if (message)
  1284. MessageBox.Show("You must clock on before opening this screen");
  1285. return false;
  1286. }
  1287. return true;
  1288. }
  1289. if (Security.IsAllowed<AutoGenerateTimesheet>())
  1290. if (!isClockedOn)
  1291. {
  1292. var ts = new TimeSheet();
  1293. ts.Date = DateTime.Today;
  1294. ts.Start = DateTime.Now.TimeOfDay;
  1295. ts.EmployeeLink.ID = App.EmployeeID;
  1296. ts.Notes = "Automatic Login from PRS Desktop";
  1297. new Client<TimeSheet>().Save(ts, "AutoLogon because Timebench Bypass is enabled", (o, e) => { });
  1298. }
  1299. return true;
  1300. }
  1301. private bool IsClockedOn()
  1302. {
  1303. RefreshTimeSheets();
  1304. if (_timesheets == null)
  1305. return false;
  1306. return _timesheets.Rows.Any(r =>
  1307. r.Get<TimeSheet, DateTime>(c => c.Date).Date == DateTime.Today && r.Get<TimeSheet, TimeSpan>(c => c.Finish) == new TimeSpan());
  1308. }
  1309. #endregion
  1310. private string CurrentPanelSlug()
  1311. {
  1312. var app = new LocalConfiguration<AppSettings>().Load();
  1313. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1314. return module.LastOrDefault()?.Replace(" ", "_").Replace("/", "") ?? "";
  1315. }
  1316. private bool ShowHelp()
  1317. {
  1318. Process.Start(new ProcessStartInfo("https://prs-software.com.au/wiki/index.php/" + CurrentPanelSlug()) { UseShellExecute = true});
  1319. return true;
  1320. }
  1321. private void Wiki_Click(object sender, RoutedEventArgs e)
  1322. {
  1323. ShowHelp();
  1324. }
  1325. private void Window_Loaded(object sender, RoutedEventArgs e)
  1326. {
  1327. }
  1328. private void UnloadWindow()
  1329. {
  1330. if (CurrentPanel != null)
  1331. {
  1332. Heartbeat(DateTime.Now - CurrentPanel_Ticks, true);
  1333. try
  1334. {
  1335. CurrentPanel.Shutdown();
  1336. }
  1337. catch (Exception e)
  1338. {
  1339. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Error in UnloadWindow(): {0}\n{1}", e.Message, e.StackTrace));
  1340. }
  1341. CurrentPanel_Ticks = DateTime.MinValue;
  1342. CurrentPanel_Label = "";
  1343. CurrentPanel_Clicks = 0;
  1344. CurrentPanel_Keys = 0;
  1345. Title =
  1346. $"{CurrentPanel_Label} - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1347. if (CurrentTab != null)
  1348. {
  1349. var border = VisualUtils.EnumChildrenOfType(CurrentTab, typeof(Border)).LastOrDefault();
  1350. if (border != null)
  1351. {
  1352. ((Border)border).Background = new SolidColorBrush(Colors.Transparent);
  1353. ((Border)border).BorderBrush = new SolidColorBrush(Colors.Transparent);
  1354. }
  1355. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  1356. if (ReportsBar is not null)
  1357. {
  1358. ReportsBar.Items.Clear();
  1359. ReportsBar.Visibility = Visibility.Collapsed;
  1360. ReportsBar.IsLauncherVisible = false;
  1361. }
  1362. var ActionBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  1363. if (ActionBar is not null)
  1364. {
  1365. ActionBar.IsLauncherVisible = false;
  1366. foreach (var module in CurrentModules)
  1367. ActionBar.Items.Remove(module);
  1368. }
  1369. }
  1370. }
  1371. CurrentTab = null;
  1372. CurrentButton = null;
  1373. CurrentPanel = null;
  1374. ContentControl.Content = null;
  1375. }
  1376. private void SecondaryWindow_Click(object sender, RoutedEventArgs e)
  1377. {
  1378. if (CurrentPanel == null)
  1379. return;
  1380. var id = Guid.NewGuid();
  1381. var window = new Tuple<string, string, double, double, double, double>(
  1382. CurrentPanel.GetType().EntityName(),
  1383. CurrentPanel_Label,
  1384. Left + 100,
  1385. Top + 100,
  1386. Width - 200,
  1387. Height - 200
  1388. );
  1389. App.DatabaseSettings.SecondaryWindows[id] = window;
  1390. new LocalConfiguration<DatabaseSettings>(App.Profile).Save(App.DatabaseSettings);
  1391. _secondarywindows[id] = new SecondaryWindow(
  1392. id,
  1393. window.Item1,
  1394. window.Item2,
  1395. window.Item3,
  1396. window.Item4,
  1397. window.Item5,
  1398. window.Item6
  1399. );
  1400. _secondarywindows[id].Show();
  1401. }
  1402. private void RibbonWindow_Activated(object sender, EventArgs e)
  1403. {
  1404. }
  1405. private void RegisterModules(IProgress<string> progress)
  1406. {
  1407. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1408. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1409. foreach (var item in bar.Items)
  1410. Dispatcher.Invoke(() =>
  1411. {
  1412. var button = item as RibbonButton;
  1413. if (button != null && button.Label != "Refresh")
  1414. if (bar.Header.Equals("Actions"))
  1415. Modules.Register(button.Label);
  1416. });
  1417. //foreach (var item in _ribbon.BackStage.Items)
  1418. //{
  1419. // BackStageCommandButton button = item as BackStageCommandButton;
  1420. // if ((button != null) && (button.Header != "Log Out") && (button.Header != "Exit"))
  1421. // SecurityFactory.Register("System", button.Header, String.Format("System: Configure {0}", button.Header));
  1422. //}
  1423. }
  1424. private void SetVisibility(FrameworkElement button, bool visible)
  1425. {
  1426. var vResult = true;
  1427. var eResult = ClientFactory.UserGuid != Guid.Empty && visible;
  1428. button.Visibility = vResult && eResult ? Visibility.Visible : Visibility.Collapsed;
  1429. if (button is RibbonButton rb)
  1430. {
  1431. CustomModules.Register(rb.Label);
  1432. rb.IsEnabled = !OutstandingDailyReports(false);
  1433. }
  1434. }
  1435. private void SetVisibleIfEither(FrameworkElement separator, FrameworkElement[] left, FrameworkElement[] right)
  1436. {
  1437. var bLeft = false;
  1438. foreach (var button in left)
  1439. bLeft = bLeft || button.Visibility == Visibility.Visible;
  1440. var bRight = false;
  1441. foreach (var button in right)
  1442. bRight = bRight || button.Visibility == Visibility.Visible;
  1443. separator.Visibility = bLeft && bRight ? Visibility.Visible : Visibility.Collapsed;
  1444. }
  1445. private void SetVisibleIfAny(FrameworkElement separator, params FrameworkElement[] buttons)
  1446. {
  1447. var bVisible = false;
  1448. foreach (var button in buttons)
  1449. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1450. separator.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1451. }
  1452. private void SetTabVisibleIfAny(Fluent.RibbonTabItem tab, params FrameworkElement[] buttons)
  1453. {
  1454. var bVisible = false;
  1455. foreach (var button in buttons)
  1456. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1457. bVisible = bVisible || (SetupActions.GetValueOrDefault(tab)?.Count(x => x is SetupActionItem) ?? 0) > 0;
  1458. tab.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1459. }
  1460. #region Email
  1461. private void DoEmailReport(DataModel model, byte[] data)
  1462. {
  1463. //var mailer = ClientFactory.CreateMailer();
  1464. //if (mailer == null)
  1465. CreateEMLFile(model, data);
  1466. //else
  1467. //{
  1468. //}
  1469. }
  1470. private void CreateEMLFile(DataModel model, byte[] data)
  1471. {
  1472. var attachment = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(model.Name, ".pdf"));
  1473. File.WriteAllBytes(attachment, data);
  1474. var message = new MailMessage();
  1475. message.From = new MailAddress(App.EmployeeEmail);
  1476. message.Subject = "Your subject here";
  1477. message.IsBodyHtml = true;
  1478. message.Body = "<span style='font-size: 12pt; color: red;'>My HTML formatted body</span>";
  1479. message.Attachments.Add(new Attachment(attachment));
  1480. var filename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(model.Name, ".eml"));
  1481. using (var filestream = File.Open(filename, FileMode.Create))
  1482. {
  1483. var binaryWriter = new BinaryWriter(filestream);
  1484. //Write the Unsent header to the file so the mail client knows this mail must be presented in "New message" mode
  1485. binaryWriter.Write(Encoding.UTF8.GetBytes("X-Unsent: 1" + Environment.NewLine));
  1486. var assembly = typeof(SmtpClient).Assembly;
  1487. var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter")!;
  1488. // Get reflection info for MailWriter contructor
  1489. var mailWriterConstructor =
  1490. mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null)!;
  1491. // Construct MailWriter object with our FileStream
  1492. var mailWriter = mailWriterConstructor.Invoke(new object[] { filestream });
  1493. // Get reflection info for Send() method on MailMessage
  1494. var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic)!;
  1495. sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);
  1496. // Finally get reflection info for Close() method on our MailWriter
  1497. var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic)!;
  1498. // Call close method
  1499. closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
  1500. }
  1501. // Open the file with the default associated application registered on the local machine
  1502. Process.Start(new ProcessStartInfo(filename) { UseShellExecute = true });
  1503. //String attachment = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.ChangeExtension(Report.FileName, ".pdf"));
  1504. //File.WriteAllBytes(attachment, data);
  1505. //Outlook.Application outlookApp = new Outlook.Application();
  1506. //Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
  1507. //mailItem.Subject = System.IO.Path.ChangeExtension(Report.FileName, "");
  1508. //mailItem.To = "";
  1509. //mailItem.HTMLBody = "";
  1510. //mailItem.Attachments.Add(attachment, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
  1511. //mailItem.Display(false);
  1512. }
  1513. #endregion
  1514. private Fluent.RibbonGroupBox? FindRibbonBar(Fluent.RibbonTabItem tab, Func<Fluent.RibbonGroupBox, bool> predicate)
  1515. {
  1516. foreach (var group in tab.Groups)
  1517. {
  1518. if (group != null)
  1519. if (predicate.Invoke(group))
  1520. return group;
  1521. }
  1522. return null;
  1523. }
  1524. //private Style tabselected = null;
  1525. //private Style tabunselected = null;
  1526. //private Style Getstyle(bool selected)
  1527. //{
  1528. // if (tabunselected == null)
  1529. // {
  1530. // tabunselected = new Style(typeof(TabButton));
  1531. // Setter st1 = new Setter(TabButton.BackgroundProperty, new SolidColorBrush(Colors.Transparent));
  1532. // tabunselected.Setters.Add(st1);
  1533. // }
  1534. // if (tabselected == null)
  1535. // {
  1536. // tabselected = new Style(typeof(TabButton));
  1537. // Setter st1 = new Setter(TabButton.BackgroundProperty, new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0x9E, 0xDA, 0x11)));
  1538. // tabselected.Setters.Add(st1);
  1539. // }
  1540. // return selected ? tabselected : tabunselected;
  1541. //}
  1542. #region Button Event Handlers
  1543. private void DataEntry_Click(object sender, RoutedEventArgs e)
  1544. {
  1545. LoadWindow<DataEntryPanel>((Fluent.Button)sender);
  1546. }
  1547. private void Console_Click(object sender, RoutedEventArgs a)
  1548. {
  1549. if (_console is null)
  1550. {
  1551. _console = new Console();
  1552. _console.Closing += (o, args) => _console = null;
  1553. }
  1554. _console.Show();
  1555. }
  1556. private void Quotes_Checked(object sender, RoutedEventArgs e)
  1557. {
  1558. LoadWindow<QuotePanel>((Fluent.Button)sender);
  1559. }
  1560. private void Jobs_Checked(object sender, RoutedEventArgs e)
  1561. {
  1562. LoadWindow<JobPanel>((Fluent.Button)sender);
  1563. }
  1564. private void Service_Checked(object sender, RoutedEventArgs e)
  1565. {
  1566. MessageBox.Show("Not Implemented");
  1567. //LoadWindow<JobPanel>((RibbonButton)sender);
  1568. }
  1569. private void Tasks_Checked(object sender, RoutedEventArgs e)
  1570. {
  1571. //LoadWindow<KanbanPanel>((RibbonButton)sender);
  1572. LoadWindow<TaskPanel>((Fluent.Button)sender);
  1573. }
  1574. private void ManufacturingMenu_Checked(object sender, RoutedEventArgs e)
  1575. {
  1576. LoadWindow<ManufacturingPanel>((Fluent.Button)sender);
  1577. }
  1578. // private void Schedule_Checked(object sender, RoutedEventArgs e)
  1579. // {
  1580. // LoadWindow<SchedulePanel>((RibbonButton)sender);
  1581. // }
  1582. private void FactoryFloorButton_Click(object sender, RoutedEventArgs e)
  1583. {
  1584. LoadWindow<FactoryPanel>((Fluent.Button)sender);
  1585. }
  1586. private void DispatchMenu_Checked(object sender, RoutedEventArgs e)
  1587. {
  1588. LoadWindow<DispatchPanel>((Fluent.Button)sender);
  1589. }
  1590. private void ReadyToGoMenu_Checked(object sender, RoutedEventArgs e)
  1591. {
  1592. LoadWindow<ReadyToGoPanel>((Fluent.Button)sender);
  1593. }
  1594. private void Equipment_Checked(object sender, RoutedEventArgs e)
  1595. {
  1596. LoadWindow<EquipmentPanel>((Fluent.Button)sender);
  1597. }
  1598. private void Requisitions_Checked(object sender, RoutedEventArgs e)
  1599. {
  1600. LoadWindow<RequisitionPanel>((Fluent.Button)sender);
  1601. }
  1602. //private void Purchases_Checked(object sender, RoutedEventArgs e)
  1603. //{
  1604. // LoadWindow(PurchasesMenu, new PurchasesPanel());
  1605. //}
  1606. private void Timesheets_Checked(object sender, RoutedEventArgs e)
  1607. {
  1608. LoadWindow<TimesheetPanel>((Fluent.Button)sender);
  1609. }
  1610. private void Attendance_Checked(object sender, RoutedEventArgs e)
  1611. {
  1612. LoadWindow<AttendancePanel>((Fluent.Button)sender);
  1613. }
  1614. private void Maps_Checked(object sender, RoutedEventArgs e)
  1615. {
  1616. LoadWindow<MapsPanel>((Fluent.Button)sender);
  1617. }
  1618. private void FactorySetup_Click()
  1619. {
  1620. var list = new MasterList(typeof(ManufacturingFactory));
  1621. list.ShowDialog();
  1622. }
  1623. private void TemplateSetup_Click()
  1624. {
  1625. var list = new MasterList(typeof(ManufacturingTemplate), "Factory.Name", null, true);
  1626. list.ShowDialog();
  1627. }
  1628. private void RefreshMenu_Click(object sender, RoutedEventArgs e)
  1629. {
  1630. if (CurrentPanel != null)
  1631. CurrentPanel.Refresh();
  1632. }
  1633. private void MenuItem_Click(object sender, RoutedEventArgs e)
  1634. {
  1635. }
  1636. private void QuoteStatusButton_Click()
  1637. {
  1638. var list = new MasterList(typeof(QuoteStatus));
  1639. list.ShowDialog();
  1640. }
  1641. private void QuoteDesignSectionButton_Click()
  1642. {
  1643. var list = new MasterList(typeof(QuoteDesignSection));
  1644. list.ShowDialog();
  1645. }
  1646. private void JobStatusButton_Click()
  1647. {
  1648. var list = new MasterList(typeof(JobStatus));
  1649. list.ShowDialog();
  1650. }
  1651. private void FinancialStatusButton_Click()
  1652. {
  1653. var list = new MasterList(typeof(JobFinancialStatus));
  1654. list.ShowDialog();
  1655. }
  1656. private void DrawingTemplatesButton_Click()
  1657. {
  1658. var list = new MasterList(typeof(DrawingTemplate));
  1659. list.ShowDialog();
  1660. }
  1661. private void RolesSetup_Click()
  1662. {
  1663. var list = new MasterList(typeof(Role));
  1664. list.ShowDialog();
  1665. }
  1666. private void GroupsSetup_Click()
  1667. {
  1668. var list = new MasterList(typeof(EmployeeGroup));
  1669. list.ShowDialog();
  1670. }
  1671. private void PositionsSetup_Click()
  1672. {
  1673. var list = new MasterList(typeof(EmployeePosition));
  1674. list.ShowDialog();
  1675. }
  1676. private void UserSetup_Click(object sender, RoutedEventArgs e)
  1677. {
  1678. LoadWindow<UserPanel>((Fluent.Button)sender);
  1679. //MasterList list = new MasterList(typeof(User));
  1680. //list.ShowDialog();
  1681. }
  1682. private void Employees_Click(object sender, RoutedEventArgs e)
  1683. {
  1684. LoadWindow<EmployeePanel>((Fluent.Button)sender);
  1685. //MasterList list = new MasterList(typeof(Employee));
  1686. //list.ShowDialog();
  1687. }
  1688. private void Customers_Click(object sender, RoutedEventArgs e)
  1689. {
  1690. var list = new MasterList(typeof(Customer));
  1691. list.ShowDialog();
  1692. }
  1693. private void Stickers_Click()
  1694. {
  1695. var list = new MasterList(typeof(WebSticker));
  1696. list.ShowDialog();
  1697. }
  1698. private void Trackers_Click(object sender, RoutedEventArgs e)
  1699. {
  1700. LoadWindow<GPSTrackers>((Fluent.Button)sender);
  1701. //MasterList list = new MasterList(typeof(GPSTracker));
  1702. //list.ShowDialog();
  1703. }
  1704. private void TrackerTypes_Click()
  1705. {
  1706. var list = new MasterList(typeof(GPSTrackerType));
  1707. list.ShowDialog();
  1708. }
  1709. private void DigitalKeys_Click()
  1710. {
  1711. var list = new MasterList(typeof(DigitalKey));
  1712. list.ShowDialog();
  1713. }
  1714. private void SupplierMenu_Click(object sender, RoutedEventArgs e)
  1715. {
  1716. var list = new MasterList(typeof(Supplier));
  1717. list.ShowDialog();
  1718. }
  1719. private void DeliveredOnSiteMenu_Checked(object sender, RoutedEventArgs e)
  1720. {
  1721. LoadWindow<DeliveredOnSitePanel>((Fluent.Button)sender);
  1722. }
  1723. private void DatabaseScripts_Click(object sender, RoutedEventArgs e)
  1724. {
  1725. var list = new MasterList(typeof(Script), "Section", null, true);
  1726. list.ShowDialog();
  1727. }
  1728. private void WebTemplates_Click(object sender, RoutedEventArgs e)
  1729. {
  1730. MasterList list = new MasterList(typeof(WebTemplate), null, null, true);
  1731. list.ShowDialog();
  1732. }
  1733. private void ActivityMenu_Click()
  1734. {
  1735. var list = new MasterList(typeof(Activity));
  1736. list.ShowDialog();
  1737. }
  1738. private void QualificationMenu_Click()
  1739. {
  1740. var list = new MasterList(typeof(Qualification));
  1741. list.ShowDialog();
  1742. }
  1743. private void Reports_LauncherClick(object sender, RoutedEventArgs e)
  1744. {
  1745. }
  1746. private void Products_Checked(object sender, RoutedEventArgs e)
  1747. {
  1748. LoadWindow<ProductsPanel>((Fluent.Button)sender);
  1749. }
  1750. private void StockLocations_Checked(object sender, RoutedEventArgs e)
  1751. {
  1752. LoadWindow<StockLocationPanel>((Fluent.Button)sender);
  1753. }
  1754. private void StockMovements_Checked(object sender, RoutedEventArgs e)
  1755. {
  1756. LoadWindow<StockMovementPanel>((Fluent.Button)sender);
  1757. }
  1758. private void KitsMasterList_Click(object sender, RoutedEventArgs e)
  1759. {
  1760. LoadWindow<KitPanel>((Fluent.Button)sender);
  1761. }
  1762. private void CostSheetsMasterList_Click(object sender, RoutedEventArgs e)
  1763. {
  1764. LoadWindow<CostSheetPanel>((Fluent.Button)sender);
  1765. }
  1766. private void LeaveRequestsButton_Click(object sender, RoutedEventArgs e)
  1767. {
  1768. LoadWindow<LeaveRequestPanel>((Fluent.Button)sender);
  1769. }
  1770. private void OrgChartButton_Click(object sender, RoutedEventArgs e)
  1771. {
  1772. LoadWindow<OrgChartPanel>((Fluent.Button)sender);
  1773. }
  1774. private void EquipmentGroupList_Click()
  1775. {
  1776. var list = new MasterList(typeof(EquipmentGroup));
  1777. list.ShowDialog();
  1778. }
  1779. private void KitConditionList_Click()
  1780. {
  1781. var list = new MasterList(typeof(KitCondition));
  1782. list.ShowDialog();
  1783. }
  1784. //private void KitGroupList_Click(object sender, RoutedEventArgs e)
  1785. //{
  1786. // MasterList list = new MasterList(typeof(KitGroup));
  1787. // list.ShowDialog();
  1788. //}
  1789. private void KitFormulaeList_Click()
  1790. {
  1791. var list = new MasterList(typeof(KitFormula));
  1792. list.ShowDialog();
  1793. }
  1794. private void CustomFields_Click(object sender, RoutedEventArgs e)
  1795. {
  1796. var list = new MasterList(typeof(CustomProperty), "Class", null, true);
  1797. list.ShowDialog();
  1798. }
  1799. private void CostSheetTypeList_Click()
  1800. {
  1801. var list = new MasterList(typeof(CostSheetType));
  1802. list.ShowDialog();
  1803. }
  1804. private void CostSheetBrandList_Click()
  1805. {
  1806. var list = new MasterList(typeof(CostSheetBrand));
  1807. list.ShowDialog();
  1808. }
  1809. private void CostSheetSectionList_Click()
  1810. {
  1811. var list = new MasterList(typeof(CostSheetSection));
  1812. list.ShowDialog();
  1813. }
  1814. private void ProductDimensionUnitsList_Click()
  1815. {
  1816. var list = new MasterList(typeof(ProductDimensionUnit));
  1817. list.ShowDialog();
  1818. }
  1819. private void SupplierList_Click(object sender, RoutedEventArgs e)
  1820. {
  1821. LoadWindow<SupplierPanel>((Fluent.Button)sender);
  1822. }
  1823. private void CustomerList_Click(object sender, RoutedEventArgs e)
  1824. {
  1825. LoadWindow<CustomerPanel>((Fluent.Button)sender);
  1826. }
  1827. private void ProductGroupsList_Click()
  1828. {
  1829. var list = new MasterList(typeof(ProductGroup));
  1830. list.ShowDialog();
  1831. }
  1832. private void ProductStylesList_Click()
  1833. {
  1834. var list = new MasterList(typeof(ProductStyle));
  1835. list.ShowDialog();
  1836. }
  1837. private void StockAreasList_Click()
  1838. {
  1839. var list = new MasterList(typeof(StockArea));
  1840. list.ShowDialog();
  1841. }
  1842. private void CostCentresList_Click()
  1843. {
  1844. var list = new MasterList(typeof(CostCentre));
  1845. list.ShowDialog();
  1846. }
  1847. private void GLCodesList_Click()
  1848. {
  1849. var list = new MasterList(typeof(GLCode));
  1850. list.ShowDialog();
  1851. }
  1852. private void AssignmentsButton_Click(object sender, RoutedEventArgs e)
  1853. {
  1854. LoadWindow<AssignmentPanel>((Fluent.Button)sender);
  1855. }
  1856. private void InvoiceList_Click(object sender, RoutedEventArgs e)
  1857. {
  1858. LoadWindow<CustomerInvoices>((Fluent.Button)sender);
  1859. }
  1860. private void ReceiptList_Click(object sender, RoutedEventArgs e)
  1861. {
  1862. LoadWindow<CustomerReceipts>((Fluent.Button)sender);
  1863. }
  1864. private void PaymentsList_Click(object sender, RoutedEventArgs e)
  1865. {
  1866. LoadWindow<SupplierPayments>((Fluent.Button)sender);
  1867. }
  1868. private void BillsList_Click(object sender, RoutedEventArgs e)
  1869. {
  1870. LoadWindow<SupplierBills>((Fluent.Button)sender);
  1871. }
  1872. private void PurchasesList_Click(object sender, RoutedEventArgs e)
  1873. {
  1874. LoadWindow<SupplierPurchaseOrderPanel>((Fluent.Button)sender);
  1875. }
  1876. private void ReceiptTypeList_Click()
  1877. {
  1878. var list = new MasterList(typeof(ReceiptType));
  1879. list.ShowDialog();
  1880. }
  1881. private void PaymentTypeList_Click()
  1882. {
  1883. var list = new MasterList(typeof(PaymentType));
  1884. list.ShowDialog();
  1885. }
  1886. private void TaxCodeList_Click()
  1887. {
  1888. var list = new MasterList(typeof(TaxCode));
  1889. list.ShowDialog();
  1890. }
  1891. private void ContactTypeList_Click()
  1892. {
  1893. var list = new MasterList(typeof(ContactType));
  1894. list.ShowDialog();
  1895. }
  1896. private void EmployeeTeamsButton_Click()
  1897. {
  1898. var list = new MasterList(typeof(Team));
  1899. list.ShowDialog();
  1900. }
  1901. private void OvertimeRulesButton_Click()
  1902. {
  1903. var list = new MasterList(typeof(OvertimeRule));
  1904. list.ShowDialog();
  1905. }
  1906. private void StandardLeaveButton_Click()
  1907. {
  1908. var list = new MasterList(typeof(StandardLeave));
  1909. list.ShowDialog();
  1910. }
  1911. private void SecurityGroupsButton_Click()
  1912. {
  1913. var list = new MasterList(typeof(SecurityGroup));
  1914. list.ShowDialog();
  1915. Security.Reset();
  1916. }
  1917. private void ImportDatabase_Click(object sender, RoutedEventArgs e)
  1918. {
  1919. Utility.DuplicateDatabase();
  1920. }
  1921. private void DeliveriesButton_Click(object sender, RoutedEventArgs e)
  1922. {
  1923. LoadWindow<DeliveryPanel>((Fluent.Button)sender);
  1924. }
  1925. private void TaskSetupButton_Click(object sender, RoutedEventArgs e)
  1926. {
  1927. var list = new MasterList(typeof(KanbanType));
  1928. list.ShowDialog();
  1929. }
  1930. private void TrolleySetup_Click()
  1931. {
  1932. var list = new MasterList(typeof(ManufacturingTrolley));
  1933. list.ShowDialog();
  1934. }
  1935. private void LostTimeSetup_Click()
  1936. {
  1937. var list = new MasterList(typeof(ManufacturingLostTime));
  1938. list.ShowDialog();
  1939. }
  1940. private void FactoryAllocationButton_Click(object sender, RoutedEventArgs e)
  1941. {
  1942. LoadWindow<ManufacturingAllocationPanel>((Fluent.Button)sender);
  1943. }
  1944. private void Messages_Checked(object sender, RoutedEventArgs e)
  1945. {
  1946. LoadWindow<NotificationPanel>((Fluent.Button)sender);
  1947. }
  1948. private void DatabaseActivityButton_Click(object sender, RoutedEventArgs e)
  1949. {
  1950. LoadWindow<DatabaseActivityDashboard>((Fluent.Button)sender);
  1951. }
  1952. private void FactoryProductivityButton_Click(object sender, RoutedEventArgs e)
  1953. {
  1954. LoadWindow<FactoryProductivityDashboard>((Fluent.Button)sender);
  1955. }
  1956. private void TemplateAnalysisButton_Click(object sender, RoutedEventArgs e)
  1957. {
  1958. LoadWindow<ManufacturingTemplateAnalysis>((Fluent.Button)sender);
  1959. }
  1960. private void FactoryAnalysisButton_Click(object sender, RoutedEventArgs e)
  1961. {
  1962. LoadWindow<FactoryFloorAnalysis>((Fluent.Button)sender);
  1963. }
  1964. private void UserActivityButton_Click(object sender, RoutedEventArgs e)
  1965. {
  1966. LoadWindow<UserActivity>((Fluent.Button)sender);
  1967. }
  1968. private void QAAnalysisButton_Click(object sender, RoutedEventArgs e)
  1969. {
  1970. LoadWindow<QADashboard>((Fluent.Button)sender);
  1971. }
  1972. private void QuickStatus_Click(object sender, RoutedEventArgs e)
  1973. {
  1974. LoadWindow<WidgetDashboard>((Fluent.Button)sender);
  1975. }
  1976. private void ConsignmentButton_Click(object sender, RoutedEventArgs e)
  1977. {
  1978. LoadWindow<ConsignmentsPanel>((Fluent.Button)sender);
  1979. }
  1980. private void ConsignmentTypesButton_Click()
  1981. {
  1982. var list = new MasterList(typeof(ConsignmentType));
  1983. list.ShowDialog();
  1984. }
  1985. private void PurchaseOrderCategoriesButton_Click()
  1986. {
  1987. var list = new MasterList(typeof(PurchaseOrderCategory));
  1988. list.ShowDialog();
  1989. }
  1990. private void DeliveryTypesButton_Click()
  1991. {
  1992. var list = new MasterList(typeof(DeliveryType));
  1993. list.ShowDialog();
  1994. }
  1995. private void ConfigureModules_Click(object sender, RoutedEventArgs e)
  1996. {
  1997. var window = new ModuleConfigurationWindow(DbFactory.Provider.URL);
  1998. if (window.ShowDialog() == true)
  1999. MessageBox.Show("These changes will be applied when the database is restarted!");
  2000. }
  2001. //private void NotificationsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
  2002. //{
  2003. // if (NotificationsList.SelectedIndex < 0)
  2004. // return;
  2005. // var editors = NotificationsList.FindVisualChildren<InABox.DynamicGrid.ExtendedRichTextEditor>().ToArray();
  2006. // var selected = editors[NotificationsList.SelectedIndex];
  2007. // selected.Text = (String)selected.Tag; //NotificationsList.SelectedIndex.ToString();
  2008. //}
  2009. //private void ViewNotification_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
  2010. //{
  2011. // Notification notification = (sender as Label).Tag as Notification;
  2012. // NotificationDetails details = new NotificationDetails(notification);
  2013. // details.ShowDialog();
  2014. // ReloadNotifications();
  2015. //}
  2016. private void DailyReport_Checked(object sender, RoutedEventArgs e)
  2017. {
  2018. LoadWindow<DailyReport>((Fluent.Button)sender);
  2019. }
  2020. private void Library_Click(object sender, RoutedEventArgs e)
  2021. {
  2022. Process.Start(
  2023. new ProcessStartInfo
  2024. {
  2025. FileName = App.DatabaseSettings.LibraryLocation,
  2026. UseShellExecute = true,
  2027. Verb = "open"
  2028. }
  2029. );
  2030. }
  2031. private void SendNotificationClick(object sender, RoutedEventArgs e)
  2032. {
  2033. var form = new NotificationForm { Description = "" };
  2034. if (form.ShowDialog() == true)
  2035. ReloadNotifications();
  2036. }
  2037. private void CompanyInformation_Click(object sender, RoutedEventArgs e)
  2038. {
  2039. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  2040. if (info == null)
  2041. info = new CompanyInformation();
  2042. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  2043. }
  2044. private void StockWarehouseList_Click()
  2045. {
  2046. var list = new MasterList(typeof(StockWarehouse));
  2047. list.ShowDialog();
  2048. }
  2049. private void Dashboards_Checked(object sender, RoutedEventArgs e)
  2050. {
  2051. LoadWindow<UtilityDashboard>((Fluent.Button)sender);
  2052. }
  2053. private void QuoteDiagramSymbols_Checked()
  2054. {
  2055. var list = new MasterList(typeof(QuoteDiagramSymbol), "Section.Name");
  2056. list.ShowDialog();
  2057. QuoteDiagramSymbolCache.Refresh();
  2058. }
  2059. private void QuoteDiagramSymbolTypes_Checked()
  2060. {
  2061. var list = new MasterList(typeof(QuoteDiagramSymbolSection));
  2062. list.ShowDialog();
  2063. QuoteDiagramSymbolCache.Refresh();
  2064. }
  2065. private void QuoteTakeOffUnits_Click()
  2066. {
  2067. var list = new MasterList(typeof(QuoteTakeOffUnit));
  2068. list.ShowDialog();
  2069. }
  2070. private void JobDocumentMileStoneButton_OnClick()
  2071. {
  2072. var list = new MasterList(typeof(JobDocumentSetMileStoneType));
  2073. list.ShowDialog();
  2074. }
  2075. private void JobDocumentTagButton_OnClick()
  2076. {
  2077. var list = new MasterList(typeof(JobDocumentSetTag));
  2078. list.ShowDialog();
  2079. }
  2080. private void Setup_Click(object sender, RoutedEventArgs e)
  2081. {
  2082. var tab = _ribbon.SelectedTabItem;
  2083. if (tab is null)
  2084. return;
  2085. if (!SetupActions.TryGetValue(tab, out var items))
  2086. items = new();
  2087. items = items.Where(x => x is not SetupActionItem setup || setup.IsVisible()).ToList();
  2088. var menu = new ContextMenu();
  2089. for (var i = 0; i < items.Count; ++i)
  2090. {
  2091. var item = items[i];
  2092. if (item is SetupActionItem setupAction)
  2093. {
  2094. menu.AddItem(setupAction.Name, setupAction.Image, setupAction.Action);
  2095. }
  2096. else if (item is SetupSeparator && i > 0 && i < items.Count - 1)
  2097. {
  2098. var last = items[i - 1];
  2099. if (last is not SetupSeparator)
  2100. menu.AddSeparator();
  2101. }
  2102. }
  2103. if(CurrentPanel?.GetType().HasInterface(typeof(IPropertiesPanel<>)) == true && Security.IsAllowed<CanConfigurePanels>())
  2104. {
  2105. menu.AddItem("Configure Panel", PRSDesktop.Resources.edit, ConfigurePanel_Click);
  2106. }
  2107. if (menu.Items.Count == 0)
  2108. {
  2109. menu.AddItem("No Items", null, null, false);
  2110. }
  2111. menu.IsOpen = true;
  2112. }
  2113. private void InitializePanelProperties(IBasePanel panel)
  2114. {
  2115. var propertiesInterface = panel.GetType().GetInterfaceDefinition(typeof(IPropertiesPanel<>));
  2116. if (propertiesInterface is not null)
  2117. {
  2118. var propertiesType = propertiesInterface.GenericTypeArguments[0];
  2119. var method = typeof(MainWindow)
  2120. .GetMethod(nameof(InitializePanelPropertiesGeneric), BindingFlags.NonPublic | BindingFlags.Instance)
  2121. ?.MakeGenericMethod(panel.GetType(), propertiesType)
  2122. .Invoke(this, new object?[] { panel });
  2123. }
  2124. }
  2125. private void InitializePanelPropertiesGeneric<TPanel, TProperties>(TPanel panel)
  2126. where TPanel : IPropertiesPanel<TProperties>
  2127. where TProperties : BaseObject, GlobalConfigurationSettings, new()
  2128. {
  2129. panel.Properties = LoadPanelProperties<TPanel, TProperties>();
  2130. }
  2131. private TProperties LoadPanelProperties<TPanel, TProperties>()
  2132. where TPanel : IPropertiesPanel<TProperties>
  2133. where TProperties : BaseObject, GlobalConfigurationSettings, new()
  2134. {
  2135. var config = new GlobalConfiguration<TProperties>();
  2136. return config.Load();
  2137. }
  2138. private void SavePanelProperties<TPanel, TProperties>(TProperties properties)
  2139. where TPanel : IPropertiesPanel<TProperties>
  2140. where TProperties : BaseObject, GlobalConfigurationSettings, new()
  2141. {
  2142. var config = new GlobalConfiguration<TProperties>();
  2143. config.Save(properties);
  2144. }
  2145. private void EditPanelProperties<TPanel, TProperties>()
  2146. where TPanel : IPropertiesPanel<TProperties>
  2147. where TProperties : BaseObject, GlobalConfigurationSettings, new()
  2148. {
  2149. var properties = LoadPanelProperties<TPanel, TProperties>();
  2150. var editor = new DynamicEditorForm(typeof(TProperties));
  2151. editor.Items = new BaseObject[] { properties };
  2152. if(editor.ShowDialog() == true)
  2153. {
  2154. SavePanelProperties<TPanel, TProperties>(properties);
  2155. }
  2156. }
  2157. private void ConfigurePanel_Click()
  2158. {
  2159. if (CurrentPanel is null) return;
  2160. var propertiesInterface = CurrentPanel.GetType().GetInterfaceDefinition(typeof(IPropertiesPanel<>))!;
  2161. var propertiesType = propertiesInterface.GenericTypeArguments[0];
  2162. var method = typeof(MainWindow)
  2163. .GetMethod(nameof(EditPanelProperties), BindingFlags.NonPublic | BindingFlags.Instance)
  2164. ?.MakeGenericMethod(CurrentPanel.GetType(), propertiesType)
  2165. .Invoke(this, Array.Empty<object?>());
  2166. }
  2167. private void StartForm<TEntityForm, TEntity, TEntityLink>(DigitalForm form)
  2168. where TEntityForm : EntityForm<TEntity, TEntityLink>, new()
  2169. where TEntity : Entity, new()
  2170. where TEntityLink : EntityLink<TEntity>, new()
  2171. {
  2172. var entityForm = new TEntityForm();
  2173. entityForm.Form.ID = form.ID;
  2174. entityForm.Form.Description = form.Description;
  2175. var entity = DFUtils.NewEntity<TEntityForm, TEntity, TEntityLink>(form);
  2176. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel, entity))
  2177. {
  2178. dataModel.Update(null);
  2179. }
  2180. }
  2181. private void Forms_Click(object sender, RoutedEventArgs e)
  2182. {
  2183. var select = new MultiSelectDialog<DigitalForm>(
  2184. Filter<DigitalForm>.And(
  2185. LookupFactory.DefineFilter<KanbanForm, DigitalForm>(Array.Empty<KanbanForm>()),
  2186. new Filter<DigitalForm>(x => x.ID).InQuery(
  2187. new Filter<EmployeeDigitalForm>(x => x.Employee.ID).IsEqualTo(App.EmployeeID),
  2188. x => x.Form.ID)),
  2189. LookupFactory.DefineColumns<DigitalForm>()
  2190. .Add(x => x.Description),
  2191. false);
  2192. if (select.ShowDialog() == true)
  2193. {
  2194. var digitalForm = select.Data().Rows.FirstOrDefault()?.ToObject<DigitalForm>();
  2195. if (digitalForm is not null)
  2196. {
  2197. StartForm<KanbanForm, Kanban, KanbanLink>(digitalForm);
  2198. }
  2199. };
  2200. }
  2201. #endregion
  2202. private bool OutstandingDailyReports(bool refresh)
  2203. {
  2204. if (!Security.IsAllowed<CanViewDailyReports>() || Security.IsAllowed<BypassOutstandingDailyReports>())
  2205. return false;
  2206. if (refresh)
  2207. RefreshTimeSheets();
  2208. if (_timesheets == null)
  2209. return false;
  2210. return _timesheets.Rows.Any(r => r.Get<TimeSheet, DateTime>(c => c.Date).Date < DateTime.Today);
  2211. }
  2212. private void Window_Unloaded(object sender, RoutedEventArgs e)
  2213. {
  2214. }
  2215. //private bool _closingFromSystemMenu = false;
  2216. private void Window_Closing(object sender, CancelEventArgs e)
  2217. {
  2218. /*if (!_closingFromSystemMenu && !CoreUtils.GetVersion().Equals("???"))
  2219. {
  2220. WindowState = WindowState.Minimized;
  2221. e.Cancel = true;
  2222. return;
  2223. }*/
  2224. App.IsClosing = true;
  2225. FinalizeAutoTimesheet();
  2226. if (!CoreUtils.GetVersion().Equals("???"))
  2227. scheduler.Stop();
  2228. if (CurrentPanel != null)
  2229. CurrentPanel.Shutdown();
  2230. CurrentPanel = null;
  2231. CurrentTab = null;
  2232. UpdateRibbonColors();
  2233. if (!CoreUtils.GetVersion().Equals("???"))
  2234. if (station.ID != Guid.Empty)
  2235. ExecuteLogout();
  2236. }
  2237. private void FinalizeAutoTimesheet()
  2238. {
  2239. if (Security.IsAllowed<AutoGenerateTimesheet>())
  2240. {
  2241. var check = new Client<TimeSheet>().Query(
  2242. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today).And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID).And(x => x.Finish)
  2243. .IsEqualTo(TimeSpan.Zero)
  2244. );
  2245. if (check.Rows.Any())
  2246. {
  2247. var ts = check.Rows.First().ToObject<TimeSheet>();
  2248. if (DateTime.Now.TimeOfDay < ts.Start.Add(new TimeSpan(0, 2, 0)))
  2249. {
  2250. new Client<TimeSheet>().Delete(ts, "Deleting Auto TimeSheet because TimeBench Bypass is enabled", (o, ex) => { });
  2251. }
  2252. else
  2253. {
  2254. ts.Finish = DateTime.Now.TimeOfDay;
  2255. new Client<TimeSheet>().Save(ts, "Clocking off Auto Timesheet because Timesheet Bypass is enabled", (o, ex) => { });
  2256. }
  2257. }
  2258. }
  2259. }
  2260. private void RibbonWindow_Closed(object sender, EventArgs e)
  2261. {
  2262. DisconnectRecorderNotes();
  2263. Application.Current.Shutdown();
  2264. }
  2265. #region Notifications + Heartbeat
  2266. private void ReceiveNotification(Notification notification)
  2267. {
  2268. if (Security.CanView<Notification>())
  2269. {
  2270. Notifications.AddNotification(notification);
  2271. }
  2272. if(CurrentPanel is NotificationPanel panel)
  2273. {
  2274. panel.AddNotification(notification);
  2275. }
  2276. }
  2277. private void Notifications_Tick(object? sender, EventArgs e)
  2278. {
  2279. if (ClientFactory.UserGuid != Guid.Empty)
  2280. {
  2281. try
  2282. {
  2283. ReloadNotifications();
  2284. }
  2285. catch (Exception err)
  2286. {
  2287. Logger.Send(LogType.Error, ClientFactory.UserID,
  2288. string.Format("Exception in Notifications_Tick:ReloadNotifications() {0}\n{1}", err.Message, err.StackTrace));
  2289. }
  2290. Heartbeat(DateTime.Now - CurrentPanel_Ticks, false);
  2291. try
  2292. {
  2293. CheckIsLoggedOn();
  2294. }
  2295. catch (Exception err2)
  2296. {
  2297. Logger.Send(LogType.Error, ClientFactory.UserID,
  2298. string.Format("Exception in Notifications_Tick:CheckIsLoggedOn() {0}\n{1}", err2.Message, err2.StackTrace));
  2299. }
  2300. }
  2301. //else
  2302. //{
  2303. // Logger.Send(LogType.Information, ClientFactory.UserID, "Notifications_Tick: ClientFactory.UserGuid is empty");
  2304. //}
  2305. }
  2306. private void CheckIsLoggedOn()
  2307. {
  2308. if (CoreUtils.GetVersion().Equals("???"))
  2309. return;
  2310. var bLogout = false;
  2311. if (!Security.IsAllowed<CanBypassTimeBench>())
  2312. if (!IsClockedOn())
  2313. {
  2314. Logger.Send(LogType.Information, ClientFactory.UserID, "User is no longer clocked in!");
  2315. bLogout = true;
  2316. Dispatcher.Invoke(() => { Logout(); });
  2317. }
  2318. if (!bLogout)
  2319. new Client<Login>().Query(
  2320. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  2321. new Columns<Login>(x => x.StationID),
  2322. null,
  2323. (o, e) =>
  2324. {
  2325. if(e is RemoteException remote)
  2326. {
  2327. if(remote.Status == StatusCode.Unauthenticated)
  2328. {
  2329. Logger.Send(LogType.Information, ClientFactory.UserID, "User has been logged out");
  2330. Dispatcher.Invoke(() => {
  2331. Logout("You have been logged out due to inactivity");
  2332. });
  2333. }
  2334. else
  2335. {
  2336. Logger.Send(LogType.Information, ClientFactory.UserID, CoreUtils.FormatException(remote));
  2337. }
  2338. }
  2339. else if(e is not null)
  2340. {
  2341. Logger.Send(LogType.Information, ClientFactory.UserID, CoreUtils.FormatException(e));
  2342. }
  2343. else if(o is not null)
  2344. {
  2345. var row = o.Rows.FirstOrDefault();
  2346. if (row == null)
  2347. {
  2348. station.ID = Guid.Empty;
  2349. new Client<Login>().Save(station, "", (o1, e1) => { });
  2350. }
  2351. else if (!row.Get<Login, string>(c => c.StationID).Equals(station.StationID))
  2352. {
  2353. Logger.Send(LogType.Information, ClientFactory.UserID, "User logged in somewhere else!");
  2354. bLogout = true;
  2355. Dispatcher.Invoke(() => { Logout(); });
  2356. }
  2357. }
  2358. }
  2359. );
  2360. }
  2361. private void Heartbeat(TimeSpan time, bool closing)
  2362. {
  2363. //Task.Run(() =>
  2364. //{
  2365. bool IsClockedOn = this.IsClockedOn();
  2366. try
  2367. {
  2368. if (IsClockedOn)
  2369. {
  2370. if ((_kanbantrackingassignment != null) && (_kanbantrackingassignment.Finish < DateTime.Now.TimeOfDay))
  2371. {
  2372. _kanbantrackingassignment.Finish = DateTime.Now.TimeOfDay;
  2373. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2374. }
  2375. if (Security.IsAllowed<MonitorApplicationWindows>())
  2376. {
  2377. if (ActivityHistory == null)
  2378. ActivityHistory = new LocalConfiguration<DailyActivityHistory>().Load();
  2379. var appname = OpenWindowGetter.GetActiveWindowProcess();
  2380. var title = OpenWindowGetter.GetActiveWindowTitle();
  2381. ActivityHistory.Activities[DateTime.Now] = (!string.IsNullOrWhiteSpace(appname) ? appname.Trim() + " - " : "") + title;
  2382. new LocalConfiguration<DailyActivityHistory>().Save(ActivityHistory);
  2383. }
  2384. }
  2385. //Logger.Send(LogType.Information, "", string.Format("Heartbeat: {0:hh\\:mm}{1}", time, closing ? " (closing)" : ""));
  2386. if (!closing && time.TotalMinutes < 5)
  2387. return;
  2388. CurrentPanel_Ticks = DateTime.Now;
  2389. if (CurrentPanel != null)
  2390. {
  2391. //Logger.Send(LogType.Information, "", string.Format("Heartbeat: {0}", CurrentPanel_Label));
  2392. if (ClientFactory.IsSupported<ModuleTracking>())
  2393. {
  2394. var keys = CurrentPanel_Keys;
  2395. CurrentPanel_Keys = 0;
  2396. var clicks = CurrentPanel_Clicks;
  2397. CurrentPanel_Clicks = 0;
  2398. var tracking = new ModuleTracking
  2399. {
  2400. Date = DateTime.Today,
  2401. Module = CurrentPanel_Label,
  2402. Clicks = clicks,
  2403. Keys = keys,
  2404. ActiveTime = clicks + keys > 0 ? time : new TimeSpan(),
  2405. IdleTime = clicks + keys == 0 ? time : new TimeSpan()
  2406. };
  2407. tracking.User.ID = ClientFactory.UserGuid;
  2408. new Client<ModuleTracking>().Save(tracking, "", (mt, ex) => { });
  2409. }
  2410. CurrentPanel.Heartbeat(time);
  2411. }
  2412. }
  2413. catch (Exception err)
  2414. {
  2415. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Exception in Heartbeat: {0}\n{1}", err.Message, err.StackTrace));
  2416. }
  2417. //});
  2418. }
  2419. private void Notifications_Changed(object sender)
  2420. {
  2421. if (Notifications.IsActive)
  2422. {
  2423. Notifications.Visibility = Visibility.Visible;
  2424. DockingGrid.ColumnDefinitions[1].Width = new GridLength(4, GridUnitType.Pixel);
  2425. DockingGrid.ColumnDefinitions[2].Width = Equals(0.0, DockingGrid.ColumnDefinitions[2].Width.Value)
  2426. ? new GridLength(300, GridUnitType.Pixel)
  2427. : DockingGrid.ColumnDefinitions[2].Width;
  2428. }
  2429. else
  2430. {
  2431. Notifications.Visibility = Visibility.Collapsed;
  2432. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  2433. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  2434. }
  2435. }
  2436. private void ReloadNotifications()
  2437. {
  2438. if (Security.CanView<Notification>())
  2439. Notifications.Refresh();
  2440. if (!NotificationsWatchDog.IsEnabled)
  2441. {
  2442. //Logger.Send(LogType.Information, ClientFactory.UserID, "Enabling Heartbeat");
  2443. NotificationsWatchDog.IsEnabled = true;
  2444. }
  2445. }
  2446. #endregion
  2447. private void RibbonWindow_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  2448. {
  2449. if (CurrentPanel != null)
  2450. CurrentPanel_Clicks++;
  2451. }
  2452. private void RibbonWindow_PreviewKeyUp(object sender, KeyEventArgs e)
  2453. {
  2454. if (CurrentPanel != null)
  2455. CurrentPanel_Keys++;
  2456. }
  2457. #region Recording
  2458. //private IntPtr myHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  2459. //{
  2460. // switch (msg)
  2461. // {
  2462. // case 0x100:
  2463. // if (_subject != null)
  2464. // {
  2465. // _recorder.Stop();
  2466. // pausestarted = DateTime.Now;
  2467. // _subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2468. // }
  2469. // break;
  2470. // default:
  2471. // messages.TryGetValue(msg, out int value);
  2472. // messages[msg] = value + 1;
  2473. // break;
  2474. // }
  2475. // return IntPtr.Zero;
  2476. //}
  2477. private void RecordScreenButton_Click(object sender, RoutedEventArgs e)
  2478. {
  2479. ToggleRecording();
  2480. }
  2481. private bool ToggleRecording()
  2482. {
  2483. if (!Security.IsAllowed<CanRecordScreen>())
  2484. return true;
  2485. if (_recorder is null)
  2486. {
  2487. var windowInteropHelper = new WindowInteropHelper(this);
  2488. var screen = Screen.FromHandle(windowInteropHelper.Handle);
  2489. _screenleft = screen.WorkingArea.Left;
  2490. _screentop = screen.WorkingArea.Top;
  2491. _screenwidth = screen.WorkingArea.Width;
  2492. _screenheight = screen.WorkingArea.Height;
  2493. //VIDEO_WIDTH = _screenwidth;
  2494. //VIDEO_HEIGHT = _screenheight;
  2495. //SetupJPEGEncoder();
  2496. messages.Clear();
  2497. _bitmaps.Clear();
  2498. ConnectToRecordNotes();
  2499. StartAudio();
  2500. _recorder = new DispatcherTimer();
  2501. _recorder.Tick += (timer, args) => { TakeScreenShot(); };
  2502. _recorder.Interval = TimeSpan.FromMilliseconds(1000 / FRAMES_PER_SECOND);
  2503. _recorder.Start();
  2504. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsBitmapImage();
  2505. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2506. RecordingNotesButton.Visibility = Visibility.Visible;
  2507. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2508. AudioRecordingButton.Visibility = Visibility.Visible;
  2509. }
  2510. else
  2511. {
  2512. using (new WaitCursor())
  2513. {
  2514. StopRecording();
  2515. _recorder.Stop();
  2516. _recorder = null;
  2517. DisconnectRecorderNotes();
  2518. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  2519. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2520. RecordingNotesButton.Visibility = Visibility.Hidden;
  2521. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2522. AudioRecordingButton.Visibility = Visibility.Hidden;
  2523. var filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos),
  2524. string.Format("PRS Screen Recording {0:yyyy-MM-dd hh-mm-ss-ff}.avi", DateTime.Now));
  2525. ProcessScreenShots(filename);
  2526. }
  2527. }
  2528. return true;
  2529. }
  2530. private void StopRecording()
  2531. {
  2532. try
  2533. {
  2534. _audio?.StopRecording();
  2535. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2536. }
  2537. catch (Exception e)
  2538. {
  2539. Logger.Send(LogType.Error, "", string.Format("Unable to stop Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2540. }
  2541. }
  2542. private void StartAudio()
  2543. {
  2544. _audioMuted = true;
  2545. _audioStream = new MemoryStream();
  2546. _audio = new WaveIn
  2547. {
  2548. DeviceNumber = 0,
  2549. WaveFormat = new WaveFormat(44100, 16, 2)
  2550. };
  2551. _audio.DataAvailable += (o, e) =>
  2552. {
  2553. var buf = _audioMuted ? new byte[e.BytesRecorded] : e.Buffer;
  2554. _audioStream.Write(buf, 0, e.BytesRecorded);
  2555. };
  2556. try
  2557. {
  2558. _audio.StartRecording();
  2559. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2560. }
  2561. catch (Exception e)
  2562. {
  2563. Logger.Send(LogType.Error, "", string.Format("Unable to start Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2564. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2565. }
  2566. }
  2567. private bool ToggleRecordingAudio()
  2568. {
  2569. if (!Security.IsAllowed<CanRecordScreen>())
  2570. return true;
  2571. if (_recorder != null)
  2572. {
  2573. _audioMuted = !_audioMuted;
  2574. AudioRecordingStatus.Source = _audioMuted
  2575. ? PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage()
  2576. : PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2577. }
  2578. return true;
  2579. }
  2580. private void DisconnectRecorderNotes()
  2581. {
  2582. if (_client != null)
  2583. {
  2584. _client.WriteAsync("QUIT");
  2585. _client.StopAsync();
  2586. _client = null;
  2587. }
  2588. }
  2589. private void ConnectToRecordNotes()
  2590. {
  2591. var filename = Debugger.IsAttached
  2592. ? "c:\\development\\comal\\prsrecordingnotes\\bin\\debug\\prsrecordingnotes.exe"
  2593. : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "recordingnotes", "prsrecordingnotes.exe");
  2594. Logger.Send(LogType.Information, "", "Recording Notes: " + filename);
  2595. _recordingnotes = Process.Start(filename);
  2596. //PipeSecurity sec = new System.IO.Pipes.PipeSecurity();
  2597. //sec.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));
  2598. _client = new PipeServer<string>("PRSScreenRecorder"); //, sec);
  2599. _client.ClientConnected += (o, args) => args.Connection.WriteAsync("Connected to PRSScreenRecorder");
  2600. _client.MessageReceived += (o, args) =>
  2601. {
  2602. if (string.Equals(args.Message, "RESUME"))
  2603. Dispatcher.Invoke(() =>
  2604. {
  2605. _audio?.StartRecording();
  2606. totalpauses += DateTime.Now - pausestarted;
  2607. _recorder?.Start();
  2608. Activate();
  2609. Focus();
  2610. });
  2611. };
  2612. _client.StartAsync();
  2613. }
  2614. private bool ShowRecordingNotes()
  2615. {
  2616. if (_recorder != null)
  2617. {
  2618. _audio?.StopRecording();
  2619. _recorder.Stop();
  2620. pausestarted = DateTime.Now;
  2621. _client?.WriteAsync("EDIT");
  2622. //_subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2623. }
  2624. return true;
  2625. }
  2626. private void TakeScreenShot()
  2627. {
  2628. using (var bmp = new ScreenCapture().CaptureScreen(_screenleft, _screentop, _screenwidth, _screenheight))
  2629. {
  2630. var cursor = PointToScreen(Mouse.GetPosition(this));
  2631. using (var g = Graphics.FromImage(bmp))
  2632. {
  2633. var brush = new SolidBrush(System.Drawing.Color.FromArgb(128, 255, 255, 0));
  2634. g.FillEllipse(brush, new RectangleF((float)cursor.X - 25F, (float)cursor.Y - 25F, 50F, 50F));
  2635. var pen = new Pen(System.Drawing.Color.Black, 0.75F);
  2636. g.DrawLine(pen, (float)cursor.X - 10F, (float)cursor.Y, (float)cursor.X + 10F, (float)cursor.Y);
  2637. g.DrawLine(pen, (float)cursor.X, (float)cursor.Y - 10F, (float)cursor.X, (float)cursor.Y + 10F);
  2638. }
  2639. var key = DateTime.Now - totalpauses;
  2640. using (var reduced = ReduceBitmap(bmp, VIDEO_WIDTH, VIDEO_HEIGHT))
  2641. {
  2642. var ms = new MemoryStream();
  2643. reduced.Save(ms, ImageFormat.Png);
  2644. ms.Position = 0;
  2645. _bitmaps[key] = ms;
  2646. }
  2647. }
  2648. }
  2649. public Bitmap ReduceBitmap(Bitmap original, int reducedWidth, int reducedHeight)
  2650. {
  2651. var reduced = new Bitmap(reducedWidth, reducedHeight);
  2652. using (var dc = Graphics.FromImage(reduced))
  2653. {
  2654. // Figure out the ratio
  2655. var ratioX = (double)reducedWidth / original.Width;
  2656. var ratioY = (double)reducedHeight / original.Height;
  2657. // use whichever multiplier is smaller
  2658. var ratio = ratioX < ratioY ? ratioX : ratioY;
  2659. // now we can get the new height and width
  2660. var newHeight = Convert.ToInt32(original.Height * ratio);
  2661. var newWidth = Convert.ToInt32(original.Width * ratio);
  2662. // Now calculate the X,Y position of the upper-left corner
  2663. // (one of these will always be zero)
  2664. var posX = Convert.ToInt32((reducedWidth - original.Width * ratio) / 2);
  2665. var posY = Convert.ToInt32((reducedHeight - original.Height * ratio) / 2);
  2666. dc.InterpolationMode = InterpolationMode.HighQualityBicubic;
  2667. dc.Clear(System.Drawing.Color.Black); // white padding
  2668. //dc.DrawImage(original, posX, posY, newWidth, newHeight);
  2669. dc.DrawImage(original, new Rectangle(posX, posY, newWidth, newHeight), new Rectangle(0, 0, original.Width, original.Height),
  2670. GraphicsUnit.Pixel);
  2671. }
  2672. return reduced;
  2673. }
  2674. public static byte[] BitmapToByteArray(Bitmap bitmap, int width, int height)
  2675. {
  2676. // and buffer of appropriate size for storing its bits
  2677. var buffer = new byte[width * height * 4];
  2678. var pixelFormat = PixelFormat.Format32bppRgb;
  2679. // Now copy bits from bitmap to buffer
  2680. var bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);
  2681. //Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2682. Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2683. bitmap.UnlockBits(bits);
  2684. return buffer;
  2685. }
  2686. private void ProcessScreenShots(string filename)
  2687. {
  2688. if (!_bitmaps.Any() || _audioStream is null)
  2689. return;
  2690. Progress.Show("Saving Video");
  2691. var framRate = 10;
  2692. using (var writer = new AviWriter(filename))
  2693. {
  2694. writer.FramesPerSecond = framRate;
  2695. writer.EmitIndex1 = true;
  2696. _audioStream.Position = 0;
  2697. var audio = writer.AddAudioStream(2);
  2698. //audio.WriteBlock(_audioStream.GetBuffer(), 0, (int)_audioStream.Length);
  2699. //File.WriteAllBytes(Path.ChangeExtension(filename, "wav"), _audioStream.GetBuffer());
  2700. var audioByteRate = audio.BitsPerSample / 8 * audio.ChannelCount * audio.SamplesPerSecond;
  2701. var audioBlockSize = (int)(audioByteRate / writer.FramesPerSecond);
  2702. var audioBuffer = new byte[audioBlockSize];
  2703. _audioStream.Position = 0;
  2704. var encoder = new MJpegWpfVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT, 50);
  2705. var stream = writer.AddEncodingVideoStream(encoder, true, VIDEO_WIDTH, VIDEO_HEIGHT);
  2706. //var encoder = new SharpAvi.Codecs.UncompressedVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT);
  2707. //var stream = writer.AddEncodingVideoStream(encoder,true,VIDEO_WIDTH, VIDEO_HEIGHT);
  2708. //stream.Codec = CodecIds.Uncompressed;
  2709. //stream.BitsPerPixel = BitsPerPixel.Bpp16;
  2710. IEnumerable<DateTime> keys = _bitmaps.Keys.OrderBy(x => x);
  2711. var start = keys.First();
  2712. var end = keys.Last();
  2713. for (var cur = start; cur <= end; cur = cur + TimeSpan.FromMilliseconds(100))
  2714. {
  2715. Progress.SetMessage(string.Format("Processing ({0:F2} complete)",
  2716. (cur - start).TotalSeconds * 100.0F / (end - start).TotalSeconds));
  2717. var key = keys.LastOrDefault(x => x <= cur);
  2718. if (_bitmaps.ContainsKey(key))
  2719. {
  2720. var frame = (Image.FromStream(_bitmaps[key]) as Bitmap)!;
  2721. //frame.RotateFlip(RotateFlipType.RotateNoneFlipY);
  2722. var buf = BitmapToByteArray(frame, stream.Width, stream.Height);
  2723. stream.WriteFrame(true, buf, 0, buf.Length);
  2724. if (_audioStream.Position < _audioStream.Length)
  2725. {
  2726. var bytes = _audioStream.Read(audioBuffer, 0, audioBlockSize);
  2727. audio.WriteBlock(audioBuffer, 0, bytes);
  2728. }
  2729. }
  2730. }
  2731. writer.Close();
  2732. //foreach (var key in _bitmaps.Keys)
  2733. // File.Delete(_bitmaps[key]);
  2734. }
  2735. Progress.SetMessage("Transcoding");
  2736. //var inputFile = new MediaFile { Filename = filename };
  2737. //var outputFile = new MediaFile { Filename = Path.ChangeExtension(filename, "mp4") };
  2738. //using (var engine = new Engine())
  2739. //{
  2740. // //engine.ConvertProgressEvent += ConvertProgressEvent;
  2741. // engine.Convert(inputFile, outputFile);
  2742. //}
  2743. Progress.Close();
  2744. var dirName = Path.GetDirectoryName(filename);
  2745. if(dirName is not null)
  2746. {
  2747. var startInfo = new ProcessStartInfo(dirName);
  2748. startInfo.Verb = "open";
  2749. startInfo.UseShellExecute = true;
  2750. Process.Start(startInfo);
  2751. //MessageBox.Show("Recording Saved");
  2752. }
  2753. }
  2754. private void VideoRecordingButton_Click(object sender, RoutedEventArgs e)
  2755. {
  2756. ToggleRecording();
  2757. }
  2758. private void AudioRecordingButton_Click(object sender, RoutedEventArgs e)
  2759. {
  2760. ToggleRecordingAudio();
  2761. }
  2762. private void RecordingNotesButton_Click(object sender, RoutedEventArgs e)
  2763. {
  2764. ShowRecordingNotes();
  2765. }
  2766. #endregion
  2767. public static void ActivateWindow(Window window)
  2768. {
  2769. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2770. var threadId1 = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
  2771. var threadId2 = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
  2772. if (threadId1 != threadId2)
  2773. {
  2774. AttachThreadInput(threadId1, threadId2, true);
  2775. SetForegroundWindow(hwnd);
  2776. AttachThreadInput(threadId1, threadId2, false);
  2777. }
  2778. else
  2779. {
  2780. SetForegroundWindow(hwnd);
  2781. }
  2782. }
  2783. private static IntPtr GetForegroundWindow()
  2784. {
  2785. var active = GetActiveWindow();
  2786. var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => new WindowInteropHelper(x).Handle == active);
  2787. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2788. return hwnd;
  2789. }
  2790. [DllImport("user32.dll", SetLastError = true)]
  2791. private static extern IntPtr SetForegroundWindow(IntPtr hWnd);
  2792. [DllImport("user32.dll")]
  2793. private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
  2794. [DllImport("user32.dll")]
  2795. private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
  2796. [DllImport("user32.dll")]
  2797. private static extern IntPtr GetActiveWindow();
  2798. //private void ConvertProgressEvent(object sender, ConvertProgressEventArgs e)
  2799. //{
  2800. // Dispatcher.Invoke(() =>
  2801. // {
  2802. // try
  2803. // {
  2804. // if (e.TotalDuration.TotalSeconds != 0.0F)
  2805. // Progress.SetMessage(String.Format("Transcoding ({0:F2}% complete)", e.ProcessedDuration.TotalSeconds * 100.0F / e.TotalDuration.TotalSeconds));
  2806. // }
  2807. // catch (Exception err)
  2808. // {
  2809. // }
  2810. // });
  2811. //}
  2812. #region Check For Updates
  2813. private string GetUpdateLocation()
  2814. {
  2815. if (App.DatabaseSettings.DatabaseType == DatabaseType.Networked)
  2816. {
  2817. var domain = App.DatabaseSettings.URL.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).Last();
  2818. var port = App.DatabaseSettings.Port;
  2819. var client = new HttpClient { BaseAddress = new Uri($"https://{domain}:{port}") };
  2820. string url;
  2821. try
  2822. {
  2823. client.GetAsync("operations").Wait();
  2824. url = $"https://{domain}";
  2825. }
  2826. catch (Exception)
  2827. {
  2828. url = $"http://{domain}";
  2829. }
  2830. return $"{url}:{port}";
  2831. }
  2832. else
  2833. return Path.Combine(CoreUtils.GetCommonAppData("PRSServer"),"update");
  2834. }
  2835. private string GetLatestVersion(string location)
  2836. {
  2837. return App.DatabaseSettings.DatabaseType switch
  2838. {
  2839. DatabaseType.Networked => Update.GetRemoteFile($"{location}/version").Content,
  2840. DatabaseType.Standalone or DatabaseType.Local => File.ReadAllText(Path.Combine(location, "version.txt")),
  2841. _ => "",
  2842. };
  2843. }
  2844. private string GetReleaseNotes(string location)
  2845. {
  2846. return App.DatabaseSettings.DatabaseType switch
  2847. {
  2848. DatabaseType.Networked => Update.GetRemoteFile($"{location}/releasenotes").Content,
  2849. DatabaseType.Standalone or DatabaseType.Local => File.ReadAllText(Path.Combine(location, "Release Notes.txt")),
  2850. _ => "",
  2851. };
  2852. }
  2853. private byte[]? GetInstaller(string location)
  2854. {
  2855. return App.DatabaseSettings.DatabaseType switch
  2856. {
  2857. DatabaseType.Networked => Update.GetRemoteFile($"{location}/install").RawBytes,
  2858. DatabaseType.Standalone or DatabaseType.Local => File.ReadAllBytes(Path.Combine(location, "PRSDesktopSetup.exe")),
  2859. _ => null,
  2860. };
  2861. }
  2862. private void CheckForUpdates()
  2863. {
  2864. Update.CheckForUpdates(
  2865. GetUpdateLocation, GetLatestVersion, GetReleaseNotes, GetInstaller, null, App.AutoUpdateSettings.Elevated, "PRSDesktopSetup.exe");
  2866. }
  2867. #endregion
  2868. #region Modules
  2869. public void CreatePanelAction(PanelAction action)
  2870. {
  2871. if (_ribbon.SelectedTabItem is null)
  2872. return;
  2873. var Actions = FindRibbonBar(_ribbon.SelectedTabItem, x => x.Header.Equals("Actions"));
  2874. if (Actions is not null)
  2875. {
  2876. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  2877. {
  2878. var sep = new RibbonSeparator();
  2879. CurrentModules.Add(sep);
  2880. Actions.Items.Add(sep);
  2881. }
  2882. var button = new RibbonButton
  2883. {
  2884. Label = action.Caption,
  2885. LargeIcon = action.Image.AsBitmapImage(),
  2886. SizeForm = SizeForm.Large,
  2887. MinWidth = 60,
  2888. Tag = action
  2889. };
  2890. button.Click += PaneActionClick;
  2891. CurrentModules.Add(button);
  2892. Actions.Items.Add(button);
  2893. }
  2894. }
  2895. private void PaneActionClick(object sender, RoutedEventArgs e)
  2896. {
  2897. var button = (Control)sender;
  2898. var action = (PanelAction)button.Tag;
  2899. action.Execute();
  2900. }
  2901. private void ReloadModules(string sectionName, DataModel model)
  2902. {
  2903. foreach (var module in CurrentModules)
  2904. {
  2905. if (module.Parent is Fluent.RibbonGroupBox bar)
  2906. bar.Items.Remove(module);
  2907. }
  2908. CurrentModules.Clear();
  2909. if (CurrentPanel != null)
  2910. {
  2911. CurrentPanel.CreateToolbarButtons(this);
  2912. CreateModules(sectionName, model, new Progress<Tuple<string, Bitmap, CustomModule>>(CreateModuleButton));
  2913. }
  2914. }
  2915. private void CreateModules(string section, DataModel model, IProgress<Tuple<string, Bitmap, CustomModule>> progress)
  2916. {
  2917. if (ClientFactory.IsSupported<CustomModule>())
  2918. {
  2919. foreach(var (module, image) in CustomModuleUtils.LoadCustomModuleThumbnails(section, model))
  2920. {
  2921. progress.Report(new Tuple<string, Bitmap, CustomModule>(module.Name ?? "", image, module));
  2922. }
  2923. }
  2924. }
  2925. private void CreateModuleButton(Tuple<string, Bitmap, CustomModule> module)
  2926. {
  2927. Fluent.RibbonGroupBox? Actions = CurrentTab != null
  2928. ? FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"))
  2929. : null;
  2930. if (Actions != null)
  2931. {
  2932. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  2933. {
  2934. var sep = new RibbonSeparator();
  2935. CurrentModules.Add(sep);
  2936. Actions.Items.Add(sep);
  2937. }
  2938. if (!CurrentModules.Any(x => x is Fluent.Button button && module.Item1.Equals(button.Header)))
  2939. {
  2940. var button = new Fluent.Button
  2941. {
  2942. Header = module.Item1,
  2943. LargeIcon = module.Item2.AsBitmapImage(),
  2944. MinWidth = 60,
  2945. Tag = module.Item3
  2946. };
  2947. button.Click += Module_Click;
  2948. CurrentModules.Add(button);
  2949. Actions.Items.Add(button);
  2950. }
  2951. }
  2952. }
  2953. private void Module_Click(object sender, RoutedEventArgs e)
  2954. {
  2955. if (CurrentPanel != null)
  2956. {
  2957. var item = (Fluent.Button)sender;
  2958. var code = (CustomModule)item.Tag;
  2959. if (!string.IsNullOrWhiteSpace(code.Script))
  2960. try
  2961. {
  2962. Selection selection;
  2963. if (code.SelectedRecords && code.AllRecords)
  2964. selection = RecordSelectionDialog.Execute();
  2965. else if (code.SelectedRecords)
  2966. selection = Selection.Selected;
  2967. else if (code.AllRecords)
  2968. selection = Selection.All;
  2969. else
  2970. selection = Selection.None;
  2971. var result = ScriptDocument.RunCustomModule(CurrentPanel.DataModel(selection), CurrentPanel.Selected(), code.Script);
  2972. if (result)
  2973. CurrentPanel.Refresh();
  2974. }
  2975. catch(CompileException c)
  2976. {
  2977. MessageBox.Show(c.Message);
  2978. }
  2979. catch (Exception err)
  2980. {
  2981. MessageBox.Show(CoreUtils.FormatException(err));
  2982. }
  2983. else
  2984. MessageBox.Show("Unable to load " + item.Header);
  2985. }
  2986. }
  2987. private void ManageModules()
  2988. {
  2989. if (CurrentPanel != null)
  2990. {
  2991. var section = CurrentPanel.SectionName;
  2992. var dataModel = CurrentPanel.DataModel(Selection.Selected);
  2993. var manager = new CustomModuleManager()
  2994. {
  2995. Section = section,
  2996. DataModel = dataModel
  2997. };
  2998. manager.ShowDialog();
  2999. ReloadModules(section, dataModel);
  3000. }
  3001. }
  3002. private void ManageModulesClick(object sender, RoutedEventArgs e)
  3003. {
  3004. ManageModules();
  3005. }
  3006. #endregion
  3007. #region Report Buttons
  3008. private void ReloadReports(string section, DataModel model)
  3009. {
  3010. if (CurrentTab is null)
  3011. return;
  3012. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  3013. if(ReportsBar is not null)
  3014. {
  3015. ReportsBar.Visibility = Security.IsAllowed<CanPrintReports>() ? Visibility.Visible : Visibility.Collapsed;
  3016. //ReportsBar.IsLauncherVisible = Security.IsAllowed<CanDesignReports>();
  3017. ReportsBar.Items.Clear();
  3018. CreateReports(section, model, new Progress<Tuple<string, Guid>>(CreateReportButton));
  3019. }
  3020. }
  3021. private void CreateReports(string section, DataModel model, IProgress<Tuple<string, Guid>> progress)
  3022. {
  3023. var client = new Client<ReportTemplate>();
  3024. var templates = client.Query(
  3025. new Filter<ReportTemplate>(x => x.DataModel).IsEqualTo(model.Name)
  3026. .And(x => x.Section).IsEqualTo(section)
  3027. .And(x => x.Visible).IsEqualTo(true),
  3028. new Columns<ReportTemplate>(x => x.ID, x => x.Name),
  3029. new SortOrder<ReportTemplate>(x => x.Name)
  3030. );
  3031. foreach (var row in templates.Rows)
  3032. progress.Report(new Tuple<string, Guid>(row.Get<ReportTemplate, string>(x => x.Name), row.Get<ReportTemplate, Guid>(x => x.ID)));
  3033. }
  3034. public void CreateReportButton(Tuple<string, Guid> report)
  3035. {
  3036. if (CurrentTab is null)
  3037. return;
  3038. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  3039. if(ReportsBar is not null)
  3040. {
  3041. var bFound = false;
  3042. foreach (var item in ReportsBar.Items)
  3043. {
  3044. if(item is RibbonButton button && report.Item2.Equals(button.Tag))
  3045. bFound = true;
  3046. }
  3047. if (!bFound)
  3048. {
  3049. var button = new RibbonButton
  3050. {
  3051. Label = report.Item1,
  3052. LargeIcon = PRSDesktop.Resources.printer.AsBitmapImage(),
  3053. Tag = report.Item2,
  3054. SizeForm = SizeForm.Large,
  3055. MinWidth = 60
  3056. };
  3057. if (Security.IsAllowed<CanDesignReports>())
  3058. {
  3059. var menu = new ContextMenu();
  3060. menu.AddItem("Design Report", PRSDesktop.Resources.pencil, report.Item2, ReportButtonMenu_DesignReport_Click);
  3061. button.ContextMenu = menu;
  3062. }
  3063. button.Click += ReportMenu_Checked;
  3064. ReportsBar.Items.Add(button);
  3065. }
  3066. }
  3067. }
  3068. private void ReportButtonMenu_DesignReport_Click(Guid templateID)
  3069. {
  3070. if (CurrentPanel is null)
  3071. return;
  3072. var template = new Client<ReportTemplate>().Load(new Filter<ReportTemplate>(x => x.ID).IsEqualTo(templateID)).FirstOrDefault();
  3073. if (template is null)
  3074. {
  3075. Logger.Send(LogType.Error, "", $"No Report Template with ID '{templateID}'");
  3076. MessageBox.Show("Report does not exist!");
  3077. return;
  3078. }
  3079. ReportUtils.DesignReport(template, CurrentPanel.DataModel(Selection.None));
  3080. }
  3081. private void ReportMenu_Checked(object sender, RoutedEventArgs e)
  3082. {
  3083. if (CurrentPanel is null)
  3084. return;
  3085. var item = (RibbonButton)sender;
  3086. var id = (Guid)item.Tag;
  3087. var template = new Client<ReportTemplate>().Load(new Filter<ReportTemplate>(x => x.ID).IsEqualTo(id)).FirstOrDefault();
  3088. if(template == null)
  3089. {
  3090. Logger.Send(LogType.Error, "", $"No Report Template with ID '{id}'");
  3091. MessageBox.Show("Report does not exist!");
  3092. return;
  3093. }
  3094. var selection = Selection.None;
  3095. if (template.SelectedRecords && template.AllRecords)
  3096. selection = RecordSelectionDialog.Execute();
  3097. else if (template.SelectedRecords)
  3098. selection = Selection.Selected;
  3099. else if (template.AllRecords)
  3100. selection = Selection.All;
  3101. else
  3102. MessageBox.Show("Report must have either [Selected Records] or [All Records] checked to display!");
  3103. if (selection != Selection.None)
  3104. ReportUtils.PreviewReport(template, CurrentPanel.DataModel(selection), false, Security.IsAllowed<CanDesignReports>());
  3105. }
  3106. private void ManageReports()
  3107. {
  3108. if (CurrentTab is null || CurrentPanel is null)
  3109. return;
  3110. var section = CurrentPanel.SectionName;
  3111. var model = CurrentPanel.DataModel(Selection.None);
  3112. if (model == null)
  3113. {
  3114. MessageBox.Show("No DataModel for " + CurrentTab.Header);
  3115. return;
  3116. }
  3117. var form = new ReportManager { DataModel = model, Section = section, Populate = true };
  3118. form.ShowDialog();
  3119. ReloadReports(section, model);
  3120. }
  3121. private void ManageReportsMenu_Click(object sender, RoutedEventArgs e)
  3122. {
  3123. ManageReports();
  3124. }
  3125. #endregion
  3126. #region Tracking Kanban
  3127. private void SelectTask_Click(object sender, RoutedEventArgs e)
  3128. {
  3129. ContextMenu menu = new ContextMenu();
  3130. MenuItem others = new MenuItem() { Header = "Other Tasks" };
  3131. using (new WaitCursor())
  3132. {
  3133. var kanbans = new Client<KanbanSubscriber>().Query(
  3134. new Filter<KanbanSubscriber>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
  3135. .And(x => x.Kanban.Completed).IsEqualTo(DateTime.MinValue)
  3136. .And(x => x.Kanban.Closed).IsEqualTo(DateTime.MinValue),
  3137. new Columns<KanbanSubscriber>(x => x.Kanban.ID)
  3138. .Add(x => x.Kanban.Number)
  3139. .Add(x => x.Kanban.Title)
  3140. .Add(x=>x.Assignee),
  3141. new SortOrder<KanbanSubscriber>(x => x.Kanban.Number, SortDirection.Ascending)
  3142. );
  3143. foreach (var row in kanbans.Rows)
  3144. {
  3145. CreateTaskMenu(row.Get<KanbanSubscriber, bool>(c => c.Assignee) ? menu.Items : others.Items,
  3146. String.Format("{0} {1}",
  3147. row.Get<KanbanSubscriber, int>(c => c.Kanban.Number),
  3148. row.Get<KanbanSubscriber, String>(c => c.Kanban.Title)),
  3149. row.Get<KanbanSubscriber, Guid>(c => c.Kanban.ID)
  3150. );
  3151. }
  3152. menu.Items.Add(new Separator());
  3153. menu.Items.Add(others);
  3154. menu.Items.Add(new Separator());
  3155. CreateTaskMenu(menu.Items, "(No Task Selected)", Guid.Empty);
  3156. }
  3157. menu.IsOpen = true;
  3158. }
  3159. private Assignment? _kanbantrackingassignment = null;
  3160. private void SetTrackingKanban(Guid kanbanID, string header)
  3161. {
  3162. SelectedTaskName.Content = header;
  3163. var createNewAssignment = false;
  3164. if (_kanbantrackingassignment is not null)
  3165. {
  3166. if (_kanbantrackingassignment.Finish < DateTime.Now.TimeOfDay)
  3167. {
  3168. _kanbantrackingassignment.Finish = DateTime.Now.TimeOfDay;
  3169. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  3170. }
  3171. // Update Existing Kanban
  3172. if (kanbanID == Guid.Empty)
  3173. _kanbantrackingassignment = null;
  3174. else if (_kanbantrackingassignment.Task.ID != kanbanID)
  3175. {
  3176. createNewAssignment = true;
  3177. }
  3178. }
  3179. else if (kanbanID != Guid.Empty)
  3180. {
  3181. createNewAssignment = true;
  3182. }
  3183. if(createNewAssignment)
  3184. {
  3185. _kanbantrackingassignment = new Assignment();
  3186. _kanbantrackingassignment.Task.ID = kanbanID;
  3187. _kanbantrackingassignment.EmployeeLink.ID = App.EmployeeID;
  3188. _kanbantrackingassignment.Title = header;
  3189. _kanbantrackingassignment.Date = DateTime.Today;
  3190. _kanbantrackingassignment.Start = DateTime.Now.TimeOfDay;
  3191. _kanbantrackingassignment.Finish = DateTime.Now.TimeOfDay.Add(new TimeSpan(0, 2, 0));
  3192. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  3193. }
  3194. }
  3195. private void ClearTrackingKanban()
  3196. => SetTrackingKanban(Guid.Empty, "(No Task Selected)");
  3197. private void CreateTaskMenu(ItemCollection items, String title, Guid id)
  3198. {
  3199. var item = new MenuItem()
  3200. {
  3201. Header = title,
  3202. Tag = id
  3203. };
  3204. item.Click += (o, args) =>
  3205. {
  3206. if (o is not MenuItem menu) return;
  3207. SetTrackingKanban((Guid)item.Tag, (menu.Header as string) ?? "");
  3208. };
  3209. items.Add(item);
  3210. }
  3211. #endregion
  3212. private void DockPanel_OnIsActiveChanged(object? sender, EventArgs e)
  3213. {
  3214. var layout = sender as LayoutAnchorable;
  3215. if (layout == null)
  3216. return;
  3217. var content = layout.Content as DependencyObject;
  3218. var dock = content is IDockPanel panel ? panel : content?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  3219. if (dock == null)
  3220. return;
  3221. if (layout.IsActive && layout.IsVisible)
  3222. dock.Refresh();
  3223. }
  3224. private void _ribbon_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  3225. {
  3226. e.Handled = true;
  3227. }
  3228. #region Backstage Functions
  3229. private void DatabaseSettings_OnClick(object sender, RoutedEventArgs e)
  3230. {
  3231. var config = new DataBaseConfiguration();
  3232. if (config.ShowDialog() == true)
  3233. {
  3234. var newsettings = new LocalConfiguration<DatabaseSettings>(App.Profile).Load();
  3235. if (newsettings.RestartRequired(App.DatabaseSettings))
  3236. MessageBox.Show("Please restart the application to apply these changes!");
  3237. if ((newsettings.DatabaseType == DatabaseType.Standalone) && (newsettings.ColorScheme != App.DatabaseSettings.ColorScheme))
  3238. {
  3239. App.DatabaseSettings.ColorScheme = newsettings.ColorScheme;
  3240. ApplyColorScheme();
  3241. }
  3242. }
  3243. }
  3244. private void CompanyInformation_OnClick(object sender, RoutedEventArgs e)
  3245. {
  3246. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  3247. if (info == null)
  3248. info = new CompanyInformation();
  3249. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  3250. }
  3251. private void SecurityDefaultsButton_OnClick(object sender, RoutedEventArgs e)
  3252. {
  3253. var window = new GlobalTokenWindow();
  3254. window.ShowDialog();
  3255. Security.Reset();
  3256. }
  3257. private void SystemLogsButton_OnClick(object sender, RoutedEventArgs e)
  3258. {
  3259. var logfile = Path.Combine(CoreUtils.GetPath(), string.Format("{0:yyyy-MM-dd}.log", DateTime.Today));
  3260. if (File.Exists(logfile))
  3261. {
  3262. var startInfo = new ProcessStartInfo("notepad.exe", logfile);
  3263. startInfo.Verb = "open";
  3264. startInfo.UseShellExecute = true;
  3265. Process.Start(startInfo);
  3266. }
  3267. else
  3268. {
  3269. MessageBox.Show(logfile + " does not exist!");
  3270. }
  3271. }
  3272. private void DocumentTypeList_OnClick(object sender, RoutedEventArgs e)
  3273. {
  3274. var list = new MasterList(typeof(DocumentType));
  3275. list.ShowDialog();
  3276. }
  3277. private void DocumentList_OnClick(object sender, RoutedEventArgs e)
  3278. {
  3279. var list = new MasterList(typeof(Document));
  3280. list.ShowDialog();
  3281. }
  3282. private void QAFormSetupButton_OnClick(object sender, RoutedEventArgs e)
  3283. {
  3284. var list = new MasterList(typeof(DigitalForm), "AppliesTo", null, true);
  3285. list.ShowDialog();
  3286. }
  3287. private void TaskSetupButton_OnClick(object sender, RoutedEventArgs e)
  3288. {
  3289. var list = new MasterList(typeof(KanbanType));
  3290. list.ShowDialog();
  3291. }
  3292. private void EditDetailsButton_OnClick(object sender, RoutedEventArgs e)
  3293. {
  3294. var employee = new Client<Employee>().Query(
  3295. new Filter<Employee>(x => x.UserID).IsEqualTo(ClientFactory.UserGuid))
  3296. .Rows.FirstOrDefault()?.ToObject<Employee>();
  3297. var item = new MyDetailsConfiguration(employee);
  3298. item.User = ClientFactory.UserGuid;
  3299. var buttons = new DynamicEditorButtons();
  3300. buttons.Add("Change Password", null, item, (sender, item) =>
  3301. {
  3302. var details = (item as MyDetailsConfiguration)!;
  3303. var changePassword = new ChangePassword(details.User);
  3304. if (changePassword.ShowDialog() == true && changePassword.Password != null)
  3305. {
  3306. var newUser = new User();
  3307. newUser.ID = details.User;
  3308. ChangePassword.ChangeUserPassword(newUser, changePassword.Password);
  3309. new Client<User>().Save(newUser, "Changed Password");
  3310. MessageBox.Show("Password changed!");
  3311. }
  3312. });
  3313. var editor = new DynamicEditorForm(typeof(MyDetailsConfiguration), buttons: buttons);
  3314. if (employee == null)
  3315. {
  3316. editor.OnFormCustomiseEditor += (sender, items, column, editor) =>
  3317. {
  3318. editor.Editable = Editable.Disabled;
  3319. };
  3320. }
  3321. editor.Items = new BaseObject[] { item };
  3322. if (editor.ShowDialog() == true)
  3323. {
  3324. if (employee != null)
  3325. {
  3326. item.SaveTo(employee);
  3327. new Client<Employee>().Save(employee, "Edited by user");
  3328. }
  3329. }
  3330. }
  3331. private void LogoutButton_OnClick(object sender, RoutedEventArgs e)
  3332. {
  3333. Logout();
  3334. }
  3335. private void LoginButton_OnClick(object sender, RoutedEventArgs e)
  3336. {
  3337. if (DoLogin(false) == ValidationResult.VALID)
  3338. AfterLogin();
  3339. }
  3340. private void ExitButton_OnClick(object sender, RoutedEventArgs e)
  3341. {
  3342. //_closingFromSystemMenu = true;
  3343. Close();
  3344. }
  3345. #endregion
  3346. }
  3347. }