MainWindow.xaml.cs 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556
  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.Reflection;
  12. using System.Runtime.InteropServices;
  13. using System.Threading.Tasks;
  14. using System.Windows;
  15. using System.Windows.Controls;
  16. using System.Windows.Forms;
  17. using System.Windows.Input;
  18. using System.Windows.Interop;
  19. using System.Windows.Media;
  20. using System.Windows.Threading;
  21. using AvalonDock.Layout;
  22. using Comal.Classes;
  23. using Comal.Stores;
  24. using Comal.TaskScheduler.Shared;
  25. using H.Pipes;
  26. using InABox.Clients;
  27. using InABox.Configuration;
  28. using InABox.Core;
  29. using InABox.Database;
  30. using InABox.Database.SQLite;
  31. using InABox.DynamicGrid;
  32. using InABox.Mail;
  33. using InABox.Core.Reports;
  34. using InABox.IPC;
  35. using InABox.Rpc;
  36. using InABox.Scripting;
  37. using InABox.Wpf;
  38. using InABox.Wpf.Console;
  39. using InABox.WPF;
  40. using NAudio.Wave;
  41. using PRS.Shared;
  42. using InABox.WPF.Themes;
  43. using PRSDesktop.Configuration;
  44. using PRSDesktop.Forms;
  45. using PRSServer;
  46. using SharpAvi.Codecs;
  47. using SharpAvi.Output;
  48. using Syncfusion.Windows.Shared;
  49. using Syncfusion.Windows.Tools;
  50. using Syncfusion.Windows.Tools.Controls;
  51. using Activity = Comal.Classes.Activity;
  52. using Application = System.Windows.Application;
  53. using ButtonBase = System.Windows.Controls.Primitives.ButtonBase;
  54. using Color = System.Windows.Media.Color;
  55. using ColorConverter = System.Windows.Media.ColorConverter;
  56. using Control = System.Windows.Controls.Control;
  57. using Image = System.Drawing.Image;
  58. using KeyEventArgs = System.Windows.Input.KeyEventArgs;
  59. using MessageBox = System.Windows.MessageBox;
  60. using Pen = System.Drawing.Pen;
  61. using PixelFormat = System.Drawing.Imaging.PixelFormat;
  62. using Role = Comal.Classes.Role;
  63. using SortDirection = InABox.Core.SortDirection;
  64. using PRSDesktop.Components.Spreadsheet;
  65. using InABox.Wpf.Reports;
  66. using Comal.Classes.SecurityDescriptors;
  67. using System.Threading;
  68. using System.Windows.Data;
  69. using System.Windows.Media.Imaging;
  70. using H.Formatters;
  71. using PRSDesktop.Panels;
  72. using Syncfusion.SfSkinManager;
  73. namespace PRSDesktop;
  74. /// <summary>
  75. /// Interaction logic for Main.xaml
  76. /// </summary>
  77. public partial class MainWindow : IPanelHostControl
  78. {
  79. //private const int WM_LBUTTONDOWN = 0x201;
  80. private static PipeServer<string>? _client;
  81. private IRpcClientTransport? _transport;
  82. private WaveIn? _audio;
  83. private bool _audioMuted;
  84. private MemoryStream? _audioStream;
  85. private readonly Dictionary<DateTime, Stream> _bitmaps = new();
  86. private DesktopConsole? _console;
  87. private Dictionary<DateTime, Tuple<Rectangle, string>> _notes = new();
  88. private DispatcherTimer? _recorder;
  89. private Process? _recordingnotes;
  90. private int _screenheight = 720;
  91. private int _screenleft;
  92. private int _screentop;
  93. private int _screenwidth = 1280;
  94. private readonly Dictionary<Guid, SecondaryWindow> SecondaryWindows = new();
  95. private CoreTable? _timesheets;
  96. private DailyActivityHistory? ActivityHistory;
  97. private readonly List<Control> CurrentModules = new();
  98. private Fluent.RibbonTabItem? CurrentTab;
  99. private Fluent.Button? CurrentButton;
  100. private readonly int FRAMES_PER_SECOND = 10;
  101. private DatabaseType DatabaseType;
  102. private readonly Dictionary<int, int> messages = new();
  103. private readonly DispatcherTimer NotificationsWatchDog;
  104. private DateTime pausestarted = DateTime.MinValue;
  105. private readonly Scheduler scheduler = new() { Interval = new TimeSpan(0, 5, 0) };
  106. // We use a Guid for the StationID rather than an IP or Mac address
  107. // because we want true single-instance restriction. Using either of
  108. // the above allows for two instances on the once machine, and thus
  109. // double-counting in the Heartbeat() function
  110. private Login station = new() { StationID = Guid.NewGuid().ToString() };
  111. private TimeSpan totalpauses = new(0);
  112. private readonly int VIDEO_HEIGHT = 1080;
  113. private readonly int VIDEO_WIDTH = 1920;
  114. private PanelHost PanelHost;
  115. public MainWindow()
  116. {
  117. PanelHost = new PanelHost(this);
  118. NotificationsWatchDog = new DispatcherTimer { IsEnabled = false };
  119. NotificationsWatchDog.Tick += Notifications_Tick;
  120. NotificationsWatchDog.Interval = new TimeSpan(0, 2, 0);
  121. ClientFactory.PushHandlers.AddHandler<Notification>(ReceiveNotification);
  122. ClientFactory.RegisterMailer(EmailType.IMAP, typeof(IMAPMailer));
  123. ClientFactory.RegisterMailer(EmailType.Exchange, typeof(ExchangeMailer));
  124. ClientFactory.OnLog += (type, userid, message, parameters) => Logger.Send(LogType.Information, ClientFactory.UserID, message, parameters);
  125. ClientFactory.OnRequestError += ClientFactory_OnRequestError;
  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. Logger.Send(LogType.Information, "", "Connecting to server");
  132. var settings = App.DatabaseSettings;
  133. bool dbConnected;
  134. DatabaseType = settings.DatabaseType;
  135. switch (DatabaseType)
  136. {
  137. case DatabaseType.Standalone:
  138. ClientFactory.SetClientType(typeof(LocalClient<>), Platform.Wpf, CoreUtils.GetVersion());
  139. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  140. DbFactory.Logo = App.DatabaseSettings.Logo;
  141. dbConnected = true;
  142. break;
  143. case DatabaseType.Networked:
  144. if (App.DatabaseSettings.Protocol == SerializerProtocol.RPC)
  145. {
  146. _transport = new RpcClientSocketTransport(App.DatabaseSettings.URLs);
  147. _transport.OnClose += TransportConnectionLost;
  148. _transport.OnException += Transport_OnException;
  149. _transport.OnOpen += Transport_OnOpen; ;
  150. dbConnected = _transport.Connect();
  151. ClientFactory.SetClientType(typeof(RpcClient<>), Platform.Wpf, CoreUtils.GetVersion(),
  152. _transport);
  153. }
  154. else
  155. {
  156. var url = RestClient<User>.Ping(App.DatabaseSettings.URLs, out DatabaseInfo info);
  157. ClientFactory.SetClientType(typeof(RestClient<>), Platform.Wpf, CoreUtils.GetVersion(), url, true);
  158. dbConnected = true;
  159. }
  160. break;
  161. case DatabaseType.Local:
  162. //new RPC stuff (temporary disabled - for enabling when RPC is ready)
  163. var pipename = DatabaseServerProperties.GetPipeName(App.DatabaseSettings.LocalServerName, true);
  164. _transport = new RpcClientPipeTransport(pipename);
  165. _transport.OnClose += TransportConnectionLost;
  166. dbConnected = _transport.Connect();
  167. ClientFactory.SetClientType(typeof(RpcClient<>), Platform.Wpf, CoreUtils.GetVersion(), _transport );
  168. //ClientFactory.SetClientType(typeof(IPCClient<>), Platform.Wpf, CoreUtils.GetVersion(),
  169. // DatabaseServerProperties.GetPipeName(App.DatabaseSettings.LocalServerName, false));
  170. //dbConnected = true;
  171. break;
  172. default:
  173. throw new Exception($"Invalid database type {DatabaseType}");
  174. }
  175. InitializeComponent();
  176. if (!dbConnected)
  177. {
  178. switch (DoConnectionFailed())
  179. {
  180. case ConnectionFailedResult.Quit:
  181. Close();
  182. return;
  183. case ConnectionFailedResult.Restart:
  184. App.ShouldRestart = true;
  185. Close();
  186. return;
  187. case ConnectionFailedResult.Ok:
  188. // Do nothing
  189. break;
  190. }
  191. }
  192. ThemeManager.BaseColor = Colors.CornflowerBlue;
  193. Progress.DisplayImage = PRSDesktop.Resources.splash_small.AsBitmapImage();
  194. try
  195. {
  196. var dbInfo = new Client<User>().Info();
  197. ClientFactory.DatabaseID = dbInfo.DatabaseID;
  198. ThemeManager.BaseColor = (Color)ColorConverter.ConvertFromString(dbInfo.ColorScheme);
  199. if (dbInfo.Logo?.Any() == true)
  200. using (var ms = new MemoryStream(dbInfo.Logo))
  201. {
  202. Progress.DisplayImage = new Bitmap(ms).AsBitmapImage();
  203. }
  204. }
  205. catch
  206. {
  207. }
  208. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  209. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  210. SecondaryWindowStatus.Source = PRSDesktop.Resources.target.AsGrayScale().AsBitmapImage();
  211. ConsoleStatus.Source = PRSDesktop.Resources.view.AsGrayScale().AsBitmapImage();
  212. SelectTask.Source = PRSDesktop.Resources.uparrow.Invert().AsBitmapImage();
  213. Title = $"{(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  214. Logger.Send(LogType.Information, "", "Checking for updates");
  215. CheckForUpdates();
  216. Exception? startupException = null;
  217. ValidationStatus? loginStatus = null;
  218. Progress.ShowModal("Loading PRS", progress =>
  219. {
  220. DynamicGridUtils.PreviewReport = (t, m) => { ReportUtils.PreviewReport(t, m, false, Security.IsAllowed<CanDesignReports>()); };
  221. DynamicGridUtils.PrintMenu = (e, s, m, p) => { ReportUtils.PrintMenu(e, s, m, Security.IsAllowed<CanDesignReports>(), p); };
  222. ImportFactory.Register(typeof(ExcelImporter<>), "Excel File", "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm");
  223. ImportFactory.Register(typeof(CustomImporter<>), "Custom", "All Files (*.*)|*.*");
  224. FormUtils.Register();
  225. DigitalFormDocumentFactory.Init(
  226. new WpfDigitalFormDocumentHandler(
  227. b => Dispatcher.BeginInvoke(() =>
  228. {
  229. BackgroundUploadStatus.Visibility = b
  230. ? Visibility.Visible
  231. : Visibility.Hidden;
  232. }
  233. ),
  234. () => _transport?.IsConnected() ?? false
  235. )
  236. );
  237. DigitalFormDocumentFactory.Run();
  238. Logger.Send(LogType.Information, "", "Registering Classes");
  239. progress.Report("Registering Classes");
  240. var tasks = new List<Task>
  241. {
  242. Task.Run(() =>
  243. {
  244. CoreUtils.RegisterClasses(typeof(TaskGrid).Assembly);
  245. CoreUtils.RegisterClasses();
  246. ComalUtils.RegisterClasses();
  247. PRSSharedUtils.RegisterClasses();
  248. ReportUtils.RegisterClasses();
  249. ConfigurationUtils.RegisterClasses();
  250. DynamicGridUtils.RegisterClasses();
  251. }),
  252. Task.Run(() =>
  253. {
  254. ScriptDocument.DefaultAssemblies.AddRange(
  255. Assembly.Load("RoslynPad.Roslyn.Windows"),
  256. Assembly.Load("RoslynPad.Editor.Windows"),
  257. typeof(Control).Assembly,
  258. typeof(MessageBox).Assembly,
  259. typeof(SolidColorBrush).Assembly
  260. );
  261. ScriptDocument.Initialize();
  262. }),
  263. Task.Run(() => DatabaseUpdateScripts.RegisterScripts())
  264. };
  265. Task.WaitAll(tasks.ToArray());
  266. Logger.Send(LogType.Information, "", "Configuring Application");
  267. progress.Report("Configuring Application");
  268. RegisterModules(progress);
  269. if (DatabaseType == DatabaseType.Standalone)
  270. {
  271. progress.Report("Starting local database...");
  272. try
  273. {
  274. StartLocalDatabase(progress);
  275. }
  276. catch (Exception err)
  277. {
  278. startupException = new Exception(
  279. string.Format(
  280. "Unable to open database ({0})\n\n{1}\n\n{2}",
  281. App.DatabaseSettings.FileName,
  282. err.Message,
  283. err.StackTrace
  284. )
  285. );
  286. }
  287. }
  288. if (startupException is null && App.DatabaseSettings.Autologin)
  289. {
  290. try
  291. {
  292. Logger.Send(LogType.Information, "", "Logging in");
  293. progress.Report("Logging in");
  294. Dispatcher.Invoke(() =>
  295. {
  296. loginStatus = TryAutoLogin();
  297. });
  298. if(loginStatus == ValidationStatus.VALID)
  299. {
  300. // Do the AfterLogin() here so that we aren't opening and closing progress windows again and again.
  301. AfterLogin(progress);
  302. }
  303. }
  304. catch(Exception e)
  305. {
  306. startupException = e;
  307. }
  308. }
  309. });
  310. if (startupException != null)
  311. {
  312. MessageWindow.ShowError("Error during startup.", startupException);
  313. }
  314. // If the login status is valid, then we've already loaded everything, so we don't here.
  315. if(loginStatus != ValidationStatus.VALID)
  316. {
  317. Logger.Send(LogType.Information, "", "Logging in");
  318. if (DoLogin() == ValidationStatus.VALID)
  319. {
  320. AfterLogin(null);
  321. }
  322. }
  323. ProfileName.Content = App.Profile;
  324. URL.Content = GetDatabaseConnectionDescription();
  325. if (loginStatus == ValidationStatus.VALID && DatabaseType == DatabaseType.Standalone)
  326. {
  327. Progress.ShowModal("Starting Scheduler", progress =>
  328. {
  329. scheduler.Start();
  330. });
  331. }
  332. }
  333. #region Connection Management
  334. private string GetDatabaseConnectionDescription()
  335. {
  336. return DatabaseType switch
  337. {
  338. #if RPC
  339. DatabaseType.Networked => (ClientFactory.Parameters?.FirstOrDefault() as RpcClientSocketTransport)?.Host,
  340. #else
  341. DatabaseType.Networked => ClientFactory.Parameters?.FirstOrDefault() as string,
  342. #endif
  343. DatabaseType.Standalone => App.DatabaseSettings?.FileName,
  344. DatabaseType.Local => App.DatabaseSettings?.LocalServerName,
  345. _ => ""
  346. } ?? "";
  347. }
  348. /// <summary>
  349. /// Reconnect to the server.
  350. /// </summary>
  351. /// <returns><see langword="true"/> if connection was successful.</returns>
  352. private bool Reconnect()
  353. {
  354. if (_transport != null)
  355. {
  356. return _transport.Connect();
  357. }
  358. Logger.Send(LogType.Error, ClientFactory.UserID, "Trying to reconnect without a transport set.");
  359. return true; // Returning true so we don't get stuck in infinite loops in exceptional circumstances.
  360. }
  361. private enum ConnectionFailedResult
  362. {
  363. Quit,
  364. Restart,
  365. Ok
  366. }
  367. /// <summary>
  368. /// To be called when initial connection to the server has failed; asks the user if they want to retry,
  369. /// change the database settings, or simply quit PRS.
  370. /// </summary>
  371. /// <returns>The action to take next.</returns>
  372. /// <exception cref="Exception"></exception>
  373. private ConnectionFailedResult DoConnectionFailed()
  374. {
  375. bool connected = false;
  376. while (!connected)
  377. {
  378. var connectionFailedWindow = new ConnectionFailed();
  379. connectionFailedWindow.ShowDialog();
  380. var reconnect = false;
  381. switch (connectionFailedWindow.Result)
  382. {
  383. case ConnectionFailedWindowResult.OpenDatabaseConfiguration:
  384. var result = ShowDatabaseConfiguration();
  385. switch (result)
  386. {
  387. case DatabaseConfigurationResult.RestartRequired:
  388. var shouldRestart = MessageBox.Show(
  389. "A restart is required to apply these changes. Do you wish to restart now?",
  390. "Restart?",
  391. MessageBoxButton.YesNo);
  392. if (shouldRestart == MessageBoxResult.Yes)
  393. {
  394. return ConnectionFailedResult.Restart;
  395. }
  396. else
  397. {
  398. reconnect = true;
  399. }
  400. break;
  401. case DatabaseConfigurationResult.RestartNotRequired:
  402. reconnect = true;
  403. break;
  404. case DatabaseConfigurationResult.Cancel:
  405. reconnect = true;
  406. break;
  407. default:
  408. throw new Exception($"Invalid enum result {result}");
  409. }
  410. break;
  411. case ConnectionFailedWindowResult.RetryConnection:
  412. reconnect = true;
  413. break;
  414. case ConnectionFailedWindowResult.Quit:
  415. return ConnectionFailedResult.Quit;
  416. default:
  417. throw new Exception($"Invalid enum result {connectionFailedWindow.Result}");
  418. }
  419. if (!reconnect)
  420. {
  421. return ConnectionFailedResult.Quit;
  422. }
  423. connected = Reconnect();
  424. }
  425. return ConnectionFailedResult.Ok;
  426. }
  427. private void Transport_OnOpen(IRpcTransport transport, RpcTransportOpenArgs e)
  428. {
  429. Logger.Send(LogType.Information, ClientFactory.UserID, "Connection opened");
  430. }
  431. private void Transport_OnException(IRpcTransport transport, RpcTransportExceptionArgs e)
  432. {
  433. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error in connection: {CoreUtils.FormatException(e.Exception)}");
  434. }
  435. private void TransportConnectionLost(IRpcTransport transport, RpcTransportCloseArgs e)
  436. {
  437. Logger.Send(LogType.Information, ClientFactory.UserID, "Connection lost");
  438. if (transport is IRpcClientTransport client)
  439. {
  440. Dispatcher.Invoke(() =>
  441. {
  442. var reconnection = new ReconnectionWindow();
  443. var cancellationTokenSource = new CancellationTokenSource();
  444. reconnection.OnCancelled = () => cancellationTokenSource.Cancel();
  445. var ct = cancellationTokenSource.Token;
  446. var work = () =>
  447. {
  448. try
  449. {
  450. DateTime lost = DateTime.Now;
  451. while (!client.IsConnected() && !ct.IsCancellationRequested)
  452. {
  453. try
  454. {
  455. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnecting - ({DateTime.Now - lost:hh\\:mm})");
  456. if (client.Connect(ct))
  457. {
  458. break;
  459. }
  460. }
  461. catch (System.Exception e1)
  462. {
  463. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnect Failed: {e1.Message}");
  464. // TODO: Remove this suppression
  465. if (e1.Message.StartsWith("The socket is connected, you needn't connect again!"))
  466. {
  467. break;
  468. }
  469. }
  470. }
  471. if (client.IsConnected())
  472. {
  473. Logger.Send(LogType.Information, ClientFactory.UserID, "Reconnected");
  474. ClientFactory.Validate(ClientFactory.SessionID);
  475. Logger.Send(LogType.Information, ClientFactory.UserID, "Validated");
  476. return true;
  477. }
  478. }
  479. catch (Exception e)
  480. {
  481. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnect Failed: {e.Message}");
  482. }
  483. return false;
  484. };
  485. var task = Task.Run(() =>
  486. {
  487. var result = work();
  488. Dispatcher.Invoke(() =>
  489. {
  490. reconnection.Close();
  491. });
  492. return result;
  493. }, ct);
  494. reconnection.ShowDialog();
  495. if (!task.Result)
  496. {
  497. Close();
  498. }
  499. });
  500. }
  501. }
  502. #endregion
  503. private bool _loggingOut = false;
  504. private void ClientFactory_OnRequestError(RequestException e)
  505. {
  506. if (e.Status == StatusCode.Unauthenticated)
  507. {
  508. switch (e.Method)
  509. {
  510. case RequestMethod.Query:
  511. case RequestMethod.Save:
  512. case RequestMethod.Delete:
  513. case RequestMethod.MultiQuery:
  514. case RequestMethod.MultiSave:
  515. case RequestMethod.MultiDelete:
  516. if (!_loggingOut)
  517. {
  518. Dispatcher.InvokeAsync(() =>
  519. {
  520. _loggingOut = true;
  521. try
  522. {
  523. Logout(null, true);
  524. }
  525. finally
  526. {
  527. _loggingOut = false;
  528. }
  529. });
  530. }
  531. break;
  532. default:
  533. break;
  534. }
  535. }
  536. }
  537. private void ApplyColorScheme()
  538. {
  539. Color baseColor;
  540. try
  541. {
  542. baseColor = (Color)ColorConverter.ConvertFromString(App.DatabaseSettings.ColorScheme);
  543. }
  544. catch
  545. {
  546. baseColor = Colors.CornflowerBlue;
  547. }
  548. ThemeManager.BaseColor = baseColor;
  549. DynamicGridUtils.SelectionBackground = ThemeManager.SelectionBackgroundBrush;
  550. DynamicGridUtils.SelectionForeground = ThemeManager.SelectionForegroundBrush;
  551. DynamicGridUtils.FilterBackground = ThemeManager.FilterBackgroundBrush;
  552. //_ribbon.Background = new SolidColorBrush(Colors.White);
  553. //_ribbon.BackStageColor = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  554. ////_ribbon.BackStage.Background = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  555. ////_ribbon.BackStage.Foreground = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Foreground);
  556. UpdateRibbonColors();
  557. PanelHost.Refresh();
  558. }
  559. #region Configuration
  560. /*
  561. protected override void OnSourceInitialized(EventArgs e)
  562. {
  563. base.OnSourceInitialized(e);
  564. var source = PresentationSource.FromVisual(this) as HwndSource;
  565. source?.AddHook(WndProc);
  566. }
  567. private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  568. {
  569. var message = (App.Message)msg;
  570. switch (message)
  571. {
  572. case App.Message.Maximise:
  573. WindowState = WindowState.Maximized;
  574. break;
  575. }
  576. return IntPtr.Zero;
  577. }*/
  578. private void ConfigureMainScreen(IProgress<string>? progress)
  579. {
  580. var bMaps = Security.CanView<Equipment>()
  581. || Security.CanView<Job>()
  582. || Security.CanView<TimeSheet>()
  583. || Security.CanView<GPSTracker>();
  584. var sections = new[]
  585. {
  586. new ProgressSection("Configuring Main Screen", SetupMainScreen),
  587. new ProgressSection("Configuring Quotes Screen", () => SetupQuotesTab(bMaps)),
  588. new ProgressSection("Configuring Projects", () => SetupProjectsTab(bMaps)),
  589. new ProgressSection("Configuring Manufacturing", () => SetupManufacturingTab(bMaps)),
  590. new ProgressSection("Configuring Logistics", () => SetupLogisticsTab(bMaps)),
  591. new ProgressSection("Configuring Products", () => SetupProductsTab(bMaps)),
  592. new ProgressSection("Configuring Human Resources", () => SetupHumanResourcesTab(bMaps)),
  593. new ProgressSection("Configuring Accounts", () => SetupAccountsTab(bMaps)),
  594. new ProgressSection("Configuring Equipment", () => SetupEquipmentTab(bMaps)),
  595. new ProgressSection("Configuring DigitalForms", () => SetupDigitalFormsTab(bMaps)),
  596. new ProgressSection("Configuring Dashboards", () => SetupDashboardsTab(bMaps)),
  597. new ProgressSection("Configuring System Modules", SetupSystemModules)
  598. };
  599. if(progress is not null)
  600. {
  601. Dispatcher.Invoke(SetupScreen);
  602. foreach(var section in sections)
  603. {
  604. progress.Report(section.Message);
  605. Dispatcher.Invoke(section.Action);
  606. }
  607. }
  608. else
  609. {
  610. SetupScreen();
  611. Progress.ShowModal(sections);
  612. }
  613. }
  614. private void SetupScreen()
  615. {
  616. var button = _ribbon.FindVisualChildren<Fluent.DropDownButton>().FirstOrDefault();
  617. if (button != null)
  618. button.Visibility = Visibility.Collapsed;
  619. if (ClientFactory.UserGuid == Guid.Empty)
  620. _ribbonRow.Height = new GridLength(30, GridUnitType.Pixel);
  621. else
  622. _ribbonRow.Height = new GridLength(1, GridUnitType.Auto);
  623. }
  624. private void SetupMainScreen()
  625. {
  626. //DockManager.SidePanelSize = OutstandingDailyReports(false) ? 0.00F : 30.00F;
  627. // Notifications Area
  628. SetVisibility(SendNotification, Security.CanView<Notification>());
  629. SetVisibility(Notifications, Security.CanView<Notification>());
  630. SetVisibility(TaskTracking, Security.IsAllowed<CanTrackTasksInDailyReport>());
  631. UserID.Content = ClientFactory.UserID;
  632. if (ClientFactory.PasswordExpiration != DateTime.MinValue)
  633. {
  634. var timeUntilExpiration = ClientFactory.PasswordExpiration - DateTime.Now;
  635. if (timeUntilExpiration.Days < 14)
  636. {
  637. PasswordExpiryNotice.Content = $"Password will expire in {timeUntilExpiration.Days} days!";
  638. PasswordExpiryNotice.Visibility = Visibility.Visible;
  639. }
  640. else
  641. {
  642. PasswordExpiryNotice.Visibility = Visibility.Collapsed;
  643. }
  644. }
  645. }
  646. private void SetupSystemModules()
  647. {
  648. SetVisibility(CompanyInformation, Security.CanView<CompanyInformation>());
  649. SetVisibleIfAny(BackstageSeparator0, CompanyInformation);
  650. SetVisibility(SecurityDefaultsButton,
  651. ClientFactory.IsSupported<GlobalSecurityToken>() && Security.IsAllowed<CanCustomiseSecurityDefaults>());
  652. SetVisibleIfAny(BackstageSeparator1, SecurityDefaultsButton);
  653. BackstageSeparator1a.Visibility = Visibility.Visible;
  654. SystemLogsButton.Visibility = Visibility.Visible;
  655. SetVisibility(DocumentTypeList, ClientFactory.IsSupported<DocumentType>() && Security.IsAllowed<CanViewDocumentTypes>());
  656. SetVisibleIfAny(BackstageSeparator2, DocumentTypeList);
  657. SetVisibility(VideoRecordingButton, Security.IsAllowed<CanRecordScreen>());
  658. LogoutButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  659. LoginButton.Visibility = ClientFactory.UserGuid != Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  660. EditDetailsButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  661. SetupDock<CanViewContactsDock>(ContactDock, Contacts);
  662. SetupDock<CanViewJobDock>(JobDock, Jobs);
  663. SetupDock<CanViewConsignmentDock>(ConsignmentDock, Consignments);
  664. SetupDock<CanViewDeliveryDock>(DeliveryDock, Deliveries);
  665. SetupDock<CanViewProductDock>(ProductLookupDock, ProductLookup);
  666. SetupDock<CanViewDigitalFormsDock>(DigitalFormsDock, DigitalForms);
  667. SetupDock<CanViewRequisitionsDock>(RequisitionsDock, Requisitions);
  668. _ribbon.InvalidateArrange();
  669. }
  670. private void SetupDashboardsTab(bool bMaps)
  671. {
  672. if (!Security.IsAllowed<ViewDesktopDashboardsTab>())
  673. return;
  674. SetVisibility(DashboardsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  675. SetVisibility(DashboardMessagesButton, Security.CanView<Notification>());
  676. SetVisibility(DashboardsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  677. SetVisibility(DashboardsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  678. SetVisibility(DashboardsMapButton, bMaps);
  679. SetVisibility(DashboardsDailyReportButton,
  680. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  681. SetVisibility(FactoryProductivityButton,
  682. ClientFactory.IsSupported<ManufacturingHistory>()
  683. && Security.IsAllowed<CanViewFactoryKPIs>()
  684. && Security.IsAllowed<ViewDesktopFactoryKPIsDashboard>());
  685. SetVisibility(TemplateAnalysisButton,
  686. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>()
  687. && Security.IsAllowed<CanViewTemplateAnalysis>()
  688. && Security.IsAllowed<ViewDesktopTemplateAnalysisDashboard>());
  689. SetVisibility(FactoryAnalysisButton,
  690. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>()
  691. && Security.IsAllowed<CanViewFactoryAnalysis>()
  692. && Security.IsAllowed<ViewDesktopFactoryAnalysisDashboard>());
  693. SetVisibility(DatabaseActivityButton,
  694. ClientFactory.IsSupported<UserTracking>()
  695. && Security.IsAllowed<CanViewDatabaseActivity>()
  696. && Security.IsAllowed<ViewDesktopDatabaseActivityDashboard>());
  697. SetVisibility(UserActivityButton, ClientFactory.IsSupported<ModuleTracking>()
  698. && Security.IsAllowed<CanViewUserActivity>()
  699. && Security.IsAllowed<ViewDesktopUserActivityDashboard>());
  700. SetVisibility(QuickStatusButton, Security.IsAllowed<CanViewQuickStatus>() && Security.IsAllowed<ViewDesktopQuickStatusDashboard>());
  701. SetVisibleIfEither(DashboardsTaskSeparator,
  702. new FrameworkElement[]
  703. {
  704. DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton, DashboardsAttendanceButton,
  705. DashboardsMapButton,
  706. DashboardsDailyReportButton
  707. },
  708. new FrameworkElement[]
  709. {
  710. FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton, QuickStatusButton
  711. });
  712. SetVisibleIfAny(DashboardsActions, DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton,
  713. DashboardsAttendanceButton, DashboardsDailyReportButton, FactoryProductivityButton, TemplateAnalysisButton,
  714. FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton, QuickStatusButton);
  715. //DashboardsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  716. //DashboardsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  717. SetVisibleIfAny(DashboardsTab, FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton,
  718. DatabaseActivityButton,
  719. UserActivityButton, QuickStatusButton);
  720. }
  721. private void SetupDigitalFormsTab(bool bMaps)
  722. {
  723. if (!Security.IsAllowed<ViewDesktopDigitalFormsTab>())
  724. return;
  725. SetVisibility(DigitalFormsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  726. SetVisibility(DigitalFormsMessagesButton, Security.CanView<Notification>());
  727. SetVisibility(DigitalFormsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  728. SetVisibility(DigitalFormsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  729. SetVisibility(DigitalFormsMapButton, bMaps);
  730. SetVisibility(DigitalFormsDailyReportButton,
  731. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  732. SetVisibility(DigitalFormsFormsLibraryButton, ClientFactory.IsSupported<DigitalForm>()
  733. && Security.CanView<DigitalForm>()
  734. && Security.IsAllowed<CanAdministerDigitalFormsLibrary>());
  735. SetVisibility(DigitalFormsCompletedFormsButton, Security.IsAllowed<CanViewDigitalFormsDashbaord>() && Security.IsAllowed<ViewDesktopDigitalFormsDashboard>());
  736. SetVisibleIfEither(DigitalFormsTaskSeparator,
  737. new FrameworkElement[]
  738. {
  739. DigitalFormsDashboardButton, DigitalFormsMessagesButton, DigitalFormsTaskButton, DigitalFormsAttendanceButton, DigitalFormsMapButton,
  740. DigitalFormsDailyReportButton
  741. }, new FrameworkElement[] { DigitalFormsFormsLibraryButton, DigitalFormsCompletedFormsButton });
  742. SetVisibleIfAny(DigitalFormsActions, DigitalFormsDashboardButton, DigitalFormsMessagesButton, DigitalFormsTaskButton,
  743. DigitalFormsAttendanceButton, DigitalFormsDailyReportButton, DigitalFormsFormsLibraryButton, DigitalFormsCompletedFormsButton);
  744. SetTabVisibleIfAny(DigitalFormsTab, DigitalFormsFormsLibraryButton, DigitalFormsCompletedFormsButton);
  745. }
  746. private void SetupEquipmentTab(bool bMaps)
  747. {
  748. if (!Security.IsAllowed<ViewDesktopEquipmentTab>())
  749. return;
  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>()
  758. && Security.CanView<Equipment>()
  759. && Security.IsAllowed<ViewDesktopEquipmentListScreen>());
  760. SetVisibility(EquipmentPlannerButton,
  761. ClientFactory.IsSupported<Equipment>()
  762. && Security.CanView<Equipment>()
  763. && ClientFactory.IsSupported<Assignment>()
  764. && Security.CanView<Assignment>()
  765. && Security.IsAllowed<ViewDesktopEquipmentPlannerScreen>());
  766. SetVisibleIfEither(EquipmentTaskSeparator,
  767. new FrameworkElement[]
  768. {
  769. EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton, EquipmentAttendanceButton, EquipmentMapButton,
  770. EquipmentDailyReportButton
  771. }, new FrameworkElement[] { EquipmentButton, EquipmentPlannerButton });
  772. SetVisibleIfAny(EquipmentActions, EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton,
  773. EquipmentAttendanceButton, EquipmentDailyReportButton, EquipmentButton, EquipmentPlannerButton);
  774. SetVisibility(TrackersMasterList, Security.CanView<GPSTracker>() && Security.IsAllowed<ViewDesktopGPSTrackersScreen>());
  775. SetTabVisibleIfAny(EquipmentTab, EquipmentButton, TrackersMasterList);
  776. }
  777. private void SetupAccountsTab(bool bMaps)
  778. {
  779. if (!Security.IsAllowed<ViewDesktopAccountsTab>())
  780. return;
  781. SetVisibility(AccountsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  782. SetVisibility(AccountsMessagesButton, Security.CanView<Notification>());
  783. SetVisibility(AccountsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  784. SetVisibility(AccountsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  785. SetVisibility(AccountsMapButton, bMaps);
  786. SetVisibility(AccountsDailyReportButton,
  787. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  788. SetVisibility(CustomerList, ClientFactory.IsSupported<Customer>()
  789. && Security.CanView<Customer>()
  790. && Security.IsAllowed<ViewDesktopCustomersScreen>());
  791. SetVisibility(InvoiceList, ClientFactory.IsSupported<Invoice>()
  792. && Security.CanView<Invoice>()
  793. && Security.IsAllowed<ViewDesktopInvoicesScreen>());
  794. SetVisibility(ReceiptList, ClientFactory.IsSupported<Receipt>()
  795. && Security.CanView<Receipt>()
  796. && Security.IsAllowed<ViewDesktopReceiptsScreen>());
  797. SetVisibility(SupplierList, ClientFactory.IsSupported<Supplier>()
  798. && Security.CanView<Supplier>()
  799. && Security.IsAllowed<ViewDesktopSuppliersScreen>());
  800. SetVisibility(AccountsDataButton, Security.IsAllowed<CanViewDataEntryPanel>());
  801. SetVisibility(PurchasesList, ClientFactory.IsSupported<PurchaseOrder>()
  802. && Security.CanView<PurchaseOrder>()
  803. && Security.IsAllowed<ViewDesktopPurchaseOrdersScreen>());
  804. SetVisibility(BillsList, ClientFactory.IsSupported<Bill>()
  805. && Security.CanView<Bill>()
  806. && Security.IsAllowed<ViewDesktopBillsScreen>());
  807. SetVisibility(PaymentsList, ClientFactory.IsSupported<Payment>()
  808. && Security.CanView<Payment>()
  809. && Security.IsAllowed<ViewDesktopPaymentsScreen>());
  810. SetVisibleIfEither(AccountsTaskSeparator1,
  811. new FrameworkElement[]
  812. {
  813. AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton, AccountsAttendanceButton, AccountsMapButton,
  814. AccountsDailyReportButton
  815. }, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList });
  816. SetVisibleIfEither(AccountsTaskSeparator2, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList },
  817. new FrameworkElement[] { SupplierList, AccountsDataButton, PurchasesList, BillsList, PaymentsList });
  818. SetVisibleIfAny(AccountsActions, AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton,
  819. AccountsAttendanceButton,
  820. AccountsDailyReportButton, CustomerList, InvoiceList, ReceiptList, SupplierList, PurchasesList, BillsList, PaymentsList);
  821. SetTabVisibleIfAny(AccountsTab, CustomerList, InvoiceList, ReceiptList, SupplierList, AccountsDataButton, PurchasesList, BillsList, PaymentsList);
  822. }
  823. private void SetupHumanResourcesTab(bool bMaps)
  824. {
  825. if (!Security.IsAllowed<ViewDesktopHumanResourcesTab>())
  826. return;
  827. SetVisibility(HumanResourcesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  828. SetVisibility(HumanResourcesMessagesButton, Security.CanView<Notification>());
  829. SetVisibility(HumanResourcesTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  830. SetVisibility(HumanResourcesAttendanceButton,
  831. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  832. SetVisibility(HumanResourcesMapButton, bMaps);
  833. SetVisibility(HumanResourcesDailyReportButton,
  834. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  835. SetVisibility(CalendarButton, Security.CanView<Assignment>() && Security.IsAllowed<ViewDesktopCalendarScreen>());
  836. SetVisibility(EmployeePlannerButton, Security.CanView<Assignment>() && Security.IsAllowed<ViewDesktopEmployeePlannerScreen>());
  837. SetVisibility(TimesheetsButton, Security.CanView<TimeSheet>() && Security.IsAllowed<ViewDesktopStaffTimeSheetsScreen>());
  838. SetVisibility(LeaveRequestsButton, Security.CanView<LeaveRequest>() && Security.IsAllowed<ViewDesktopLeaveRequestsScreen>());
  839. SetVisibility(OrgChartButton,
  840. ClientFactory.IsSupported<Employee>()
  841. &&
  842. Security.IsAllowed<ViewDesktopOrgChartScreen>()
  843. );
  844. SetVisibility(MeetingsButton, Security.IsAllowed<ViewDesktopMeetingsScreen>());
  845. SetVisibleIfEither(HumanResourcesTaskSeparator,
  846. new FrameworkElement[]
  847. {
  848. HumanResourcesDashboardButton, HumanResourcesMessagesButton, HumanResourcesTaskButton, HumanResourcesAttendanceButton,
  849. HumanResourcesMapButton, HumanResourcesDailyReportButton
  850. }, new FrameworkElement[] { CalendarButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton });
  851. SetVisibleIfAny(HumanResourcesActions, HumanResourcesDashboardButton, HumanResourcesTaskButton,
  852. HumanResourcesAttendanceButton,
  853. HumanResourcesDailyReportButton, CalendarButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton);
  854. SetVisibility(UsersButton, Security.CanView<User>() && Security.IsAllowed<ViewDesktopUserAccountsScreen>());
  855. SetVisibility(EmployeesButton, Security.CanView<Employee>() && Security.IsAllowed<ViewDesktopEmployeeListScreen>());
  856. SetVisibleIfEither(HumanResourcesSetupSeparator1,
  857. new FrameworkElement[] { CalendarButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton },
  858. new FrameworkElement[] { UsersButton, EmployeesButton });
  859. SetTabVisibleIfAny(HumanResourcesTab, CalendarButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton, UsersButton, EmployeesButton);
  860. }
  861. private void SetupProductsTab(bool bMaps)
  862. {
  863. if (!Security.IsAllowed<ViewDesktopProductManagementTab>())
  864. return;
  865. SetVisibility(ProductsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  866. SetVisibility(ProductsMessagesButton, Security.CanView<Notification>());
  867. SetVisibility(ProductsTaskButton, Security.CanView<Kanban>());
  868. SetVisibility(ProductsAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  869. SetVisibility(ProductsMapButton, bMaps);
  870. SetVisibility(ProductsDailyReportButton,
  871. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  872. SetVisibility(ProductsMasterList, Security.CanView<Product>() && Security.IsAllowed<ViewDesktopProductListScreen>());
  873. SetVisibility(StockLocationList, Security.CanView<StockLocation>() && Security.IsAllowed<ViewDesktopStockLocationsScreen>());
  874. SetVisibility(StockMovementList, Security.CanView<StockMovement>() && Security.IsAllowed<ViewDesktopStockMovementsScreen>());
  875. SetVisibility(StockForecastButton, Security.CanView<Product>()
  876. && Security.CanView<JobMaterial>()
  877. && Security.IsAllowed<ViewDesktopStockForecastScreen>());
  878. SetVisibility(ReservationManagementButton, Security.IsAllowed<ViewDesktopReservationManagementScreen>());
  879. SetVisibleIfEither(ProductsTaskSeparator,
  880. new FrameworkElement[]
  881. {
  882. ProductsDashboardButton, ProductsMessagesButton, ProductsTaskButton, ProductsAttendanceButton, ProductsMapButton,
  883. ProductsDailyReportButton
  884. }, new FrameworkElement[] { ProductsMasterList, StockLocationList, StockMovementList, StockForecastButton });
  885. SetVisibleIfAny(ProductActions, ProductsMasterList, StockLocationList, StockMovementList, StockForecastButton);
  886. SetTabVisibleIfAny(ProductTab, ProductActions);
  887. }
  888. private void SetupLogisticsTab(bool bMaps)
  889. {
  890. if (!Security.IsAllowed<ViewDesktopLogisticsTab>())
  891. return;
  892. SetVisibility(LogisticsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  893. SetVisibility(LogisticsMessagesButton, Security.CanView<Notification>());
  894. SetVisibility(LogisticsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  895. SetVisibility(LogisticsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  896. SetVisibility(LogisticsMapButton, bMaps);
  897. SetVisibility(LogisticsDailyReportButton,
  898. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  899. SetVisibility(ReadyToGoItemsButton,
  900. ClientFactory.IsSupported<DeliveryItem>()
  901. && Security.IsAllowed<CanViewLogisticsReadyToGo>()
  902. && Security.IsAllowed<ViewDesktopReadyToGoScreen>());
  903. SetVisibility(DispatchButton, Security.CanView<Shipment>()
  904. && Security.CanView<DeliveryItem>()
  905. && Security.IsAllowed<ViewDesktopRackListScreen>());
  906. SetVisibility(RequisitionsButton, Security.CanView<Requisition>() && Security.IsAllowed<ViewDesktopSiteRequisitionsScreen>());
  907. SetVisibility(DeliveriesButton, Security.IsAllowed<CanViewDeliveriesModule>() && Security.IsAllowed<ViewDesktopDeliveriesScren>());
  908. SetVisibility(DeliveredItemsButton,
  909. ClientFactory.IsSupported<DeliveryItem>()
  910. && Security.IsAllowed<CanViewDeliveredOnSite>()
  911. && Security.IsAllowed<ViewDesktopDeliveredOnSiteScreen>());
  912. SetVisibility(ConsignmentButton, Security.CanView<Consignment>() && Security.IsAllowed<ViewDesktopIncomingConsignmentsScreen>());
  913. SetVisibleIfEither(LogisticsTaskSeparator1,
  914. new FrameworkElement[]
  915. {
  916. LogisticsDashboardButton, LogisticsMessagesButton, LogisticsTaskButton, LogisticsAttendanceButton, LogisticsMapButton,
  917. LogisticsDailyReportButton
  918. },
  919. new FrameworkElement[]
  920. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton });
  921. SetVisibleIfEither(LogisticsTaskSeparator2,
  922. new FrameworkElement[]
  923. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton },
  924. new FrameworkElement[] { ConsignmentButton });
  925. SetTabVisibleIfAny(LogisticsTab, DispatchButton, RequisitionsButton, DeliveriesButton, ReadyToGoItemsButton,
  926. DeliveredItemsButton,
  927. ConsignmentButton);
  928. }
  929. private void SetupManufacturingTab(bool bMaps)
  930. {
  931. if (!Security.IsAllowed<ViewDesktopManufacturingTab>())
  932. return;
  933. SetVisibility(ManufacturingDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  934. SetVisibility(ManufacturingMessagesButton, Security.CanView<Notification>());
  935. SetVisibility(ManufacturingTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  936. SetVisibility(ManufacturingAttendanceButton,
  937. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  938. SetVisibility(ManufacturingMapButton, bMaps);
  939. SetVisibility(ManufacturingDailyReportButton,
  940. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  941. SetVisibleIfAny(ManufacturingTaskSeparator,
  942. new FrameworkElement[]
  943. {
  944. ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton, ManufacturingAttendanceButton,
  945. ManufacturingMapButton, ManufacturingDailyReportButton
  946. });
  947. SetVisibility(DesignManagementButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopDesignManagementScreen>());
  948. SetVisibility(ManufacturingDesignSeparator, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopDesignManagementScreen>());
  949. SetVisibility(FactoryStatusButton,
  950. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket>()
  951. && Security.IsAllowed<CanViewFactoryStatus>()
  952. && Security.IsAllowed<ViewDesktopManufacturingStatusScreen>());
  953. SetVisibility(FactoryAllocationButton,
  954. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket, ManufacturingPacketStage>()
  955. && Security.IsAllowed<CanViewFactoryAllocation>()
  956. && Security.IsAllowed<ViewDesktopFactoryAllocationScreen>());
  957. //SetVisibility(FactoryScheduleButton, ClientFactory.IsSupported<Booking>() && ClientFactory.IsEnabled<>());
  958. SetVisibility(FactoryFloorButton,
  959. ClientFactory.IsSupported<ManufacturingPacket>()
  960. && Security.IsAllowed<CanViewFactoryFloor>()
  961. && Security.IsAllowed<ViewDesktopFactoryFloorScreen>());
  962. //SetVisibility(FactoryReadyButton, ClientFactory.IsSupported<ManufacturingPacket>() && Security.IsAllowed<CanViewFactoryReadyToGo>());
  963. SetVisibleIfAny(ManufacturingActionSeparator,
  964. new FrameworkElement[]
  965. {
  966. FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton
  967. });
  968. SetVisibleIfAny(ManufacturingActions, ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton,
  969. ManufacturingAttendanceButton, ManufacturingDailyReportButton, FactoryStatusButton, FactoryAllocationButton,
  970. FactoryFloorButton);
  971. SetTabVisibleIfAny(ManufacturingTab, FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton);
  972. }
  973. private void SetupProjectsTab(bool bMaps)
  974. {
  975. if (!Security.IsAllowed<ViewDesktopProjectsTab>())
  976. return;
  977. SetVisibility(ProjectsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  978. SetVisibility(ProjectMessagesButton, Security.CanView<Notification>());
  979. SetVisibility(ProjectTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  980. SetVisibility(ProjectAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  981. SetVisibility(ProjectsMapButton, bMaps);
  982. SetVisibility(ProjectDailyReportButton,
  983. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  984. SetVisibility(ProjectsButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopProjectsScreen>());
  985. SetVisibility(ServiceButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopServiceScreen>());
  986. SetVisibility(ProjectPlannerButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopProjectPlannerScreen>());
  987. SetVisibleIfEither(ProjectTaskSeparator,
  988. new FrameworkElement[]
  989. {
  990. ProjectsDashboardButton, ProjectMessagesButton, ProjectTaskButton, ProjectAttendanceButton, ProjectsMapButton,
  991. ProjectDailyReportButton
  992. }, new FrameworkElement[] { QuotesButton, ProjectsButton, ServiceButton, ProjectPlannerButton });
  993. //ProjectsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  994. //ProjectReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  995. SetTabVisibleIfAny(ProjectsTab, ProjectsButton, ServiceButton, ProjectPlannerButton);
  996. }
  997. private void SetupQuotesTab(bool bMaps)
  998. {
  999. if (!Security.IsAllowed<ViewDesktopQuotesTab>())
  1000. return;
  1001. SetVisibility(QuotesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  1002. SetVisibility(QuotesMessagesButton, Security.CanView<Notification>());
  1003. SetVisibility(QuotesTaskButton, Security.IsAllowed<CanViewTasks>());
  1004. SetVisibility(QuotesAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  1005. SetVisibility(QuotesMapButton, bMaps);
  1006. SetVisibility(QuotesDailyReportButton,
  1007. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  1008. SetVisibility(QuotesButton, Security.CanView<Quote>() && Security.IsAllowed<ViewDesktopQuotesScreen>());
  1009. SetVisibility(KitsMasterList, Security.CanView<Kit>() && Security.IsAllowed<ViewDesktopProductKitsScreen>());
  1010. SetVisibility(CostSheetsMasterList, Security.CanView<CostSheet>() && Security.IsAllowed<ViewDesktopCostSheetsScreen>());
  1011. SetVisibleIfEither(QuotesTaskSeparator,
  1012. new FrameworkElement[]
  1013. {
  1014. QuotesDashboardButton, QuotesMessagesButton, QuotesTaskButton, QuotesAttendanceButton, QuotesMapButton,
  1015. QuotesDailyReportButton
  1016. }, new FrameworkElement[] { QuotesButton });
  1017. SetVisibleIfEither(QuotesActionSeparator, new FrameworkElement[] { QuotesButton },
  1018. new FrameworkElement[] { KitsMasterList, CostSheetsMasterList });
  1019. SetVisibleIfAny(QuotesActions, QuotesButton, KitsMasterList, CostSheetsMasterList);
  1020. SetTabVisibleIfAny(QuotesTab, QuotesActions);
  1021. }
  1022. private void SetupDock<TSecurityDescriptor>(LayoutAnchorable layout, IDockPanel dock)
  1023. where TSecurityDescriptor : ISecurityDescriptor, new()
  1024. {
  1025. if (Security.IsAllowed<TSecurityDescriptor>())
  1026. {
  1027. if (!DockGroup.Children.Any(x => x == layout))
  1028. {
  1029. DockGroup.Children.Add(layout);
  1030. }
  1031. if (layout.IsVisible && (ClientFactory.UserGuid != Guid.Empty))
  1032. dock.Setup();
  1033. }
  1034. else
  1035. {
  1036. DockGroup.RemoveChild(layout);
  1037. }
  1038. }
  1039. private void LoadApplicationState()
  1040. {
  1041. if (ClientFactory.UserGuid != Guid.Empty)
  1042. {
  1043. _ribbon.IsCollapsed = false;
  1044. if (OutstandingDailyReports(false))
  1045. {
  1046. MessageWindow.ShowMessage("There are outstanding Daily Reports that must be filled out before continuing!"
  1047. + "\n\nAccess to PRS is restricted until this is corrected.",
  1048. "Outstanding Reports");
  1049. var dailyReportPanel = LoadWindow<DailyReport>(ProjectDailyReportButton);
  1050. if(dailyReportPanel is not null)
  1051. {
  1052. dailyReportPanel.OnTimeSheetConfirmed += e =>
  1053. {
  1054. if (!OutstandingDailyReports(true))
  1055. {
  1056. ConfigureMainScreen(null);
  1057. LoadApplicationState();
  1058. }
  1059. };
  1060. }
  1061. return;
  1062. }
  1063. using (new WaitCursor())
  1064. {
  1065. _ribbon.IsCollapsed = false;
  1066. LoadInitialWindow();
  1067. }
  1068. }
  1069. }
  1070. private void LoadInitialWindow()
  1071. {
  1072. var app = new LocalConfiguration<AppSettings>().Load();
  1073. if (app.Settings.ContainsKey("CurrentPanel"))
  1074. {
  1075. try
  1076. {
  1077. var bFound = false;
  1078. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1079. if (module.Length == 2)
  1080. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1081. {
  1082. if (String.Equals(tab.Header, module.First()))
  1083. {
  1084. _ribbon.SelectedTabItem = tab;
  1085. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1086. {
  1087. foreach (var item in bar.Items)
  1088. {
  1089. var button = item as Fluent.Button;
  1090. if (button != null && String.Equals(button.Header, module.Last()))
  1091. {
  1092. bFound = true;
  1093. button.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
  1094. break;
  1095. }
  1096. }
  1097. if (bFound)
  1098. break;
  1099. }
  1100. }
  1101. if (bFound)
  1102. break;
  1103. }
  1104. }
  1105. catch (Exception e)
  1106. {
  1107. MessageWindow.ShowError($"Unable to load {app.Settings["CurrentPanel"]}", e);
  1108. }
  1109. }
  1110. }
  1111. private void _ribbon_OnLoaded(object sender, RoutedEventArgs e)
  1112. {
  1113. _ribbon.SelectedTabItem = CurrentTab;
  1114. }
  1115. private void LoadSecondaryWindows()
  1116. {
  1117. if (ClientFactory.UserGuid != Guid.Empty)
  1118. {
  1119. var windows = App.DatabaseSettings.SecondaryWindows;
  1120. foreach (var key in windows.Keys.ToArray())
  1121. {
  1122. SecondaryWindows[key] = new SecondaryWindow(
  1123. key,
  1124. windows[key].Item1,
  1125. windows[key].Item2,
  1126. windows[key].Item3,
  1127. windows[key].Item4,
  1128. windows[key].Item5,
  1129. windows[key].Item6
  1130. );
  1131. SecondaryWindows[key].Closed += (o, e) => { SecondaryWindows.Remove(key); };
  1132. SecondaryWindows[key].Show();
  1133. }
  1134. }
  1135. else
  1136. {
  1137. foreach (var key in SecondaryWindows.Keys.ToArray())
  1138. {
  1139. App.IsClosing = true;
  1140. SecondaryWindows[key].Close();
  1141. App.IsClosing = false;
  1142. }
  1143. }
  1144. }
  1145. private Fluent.RibbonTabItem GetTabItem(FrameworkElement? sender)
  1146. {
  1147. if (sender == null)
  1148. throw new Exception("No Tab Found!");
  1149. if (sender is Fluent.RibbonTabItem)
  1150. return (Fluent.RibbonTabItem)sender;
  1151. return GetTabItem(sender.Parent as FrameworkElement);
  1152. }
  1153. private IEnumerable<IBasePanel> Panels
  1154. {
  1155. get
  1156. {
  1157. if(PanelHost.CurrentPanel is not null)
  1158. {
  1159. yield return PanelHost.CurrentPanel;
  1160. }
  1161. foreach(var window in SecondaryWindows.Values)
  1162. {
  1163. yield return window.Panel;
  1164. }
  1165. }
  1166. }
  1167. private T? LoadWindow<T>(Fluent.Button sender) where T : class, IBasePanel, new()
  1168. {
  1169. return LoadWindow<T>(sender, new CancelEventArgs());
  1170. }
  1171. private T? LoadWindow<T>(Fluent.Button sender, CancelEventArgs cancel) where T : class, IBasePanel, new()
  1172. {
  1173. using (new WaitCursor())
  1174. {
  1175. UnloadWindow(cancel);
  1176. if (cancel.Cancel)
  1177. {
  1178. return null;
  1179. }
  1180. CurrentTab = GetTabItem(sender);
  1181. CurrentButton = sender;
  1182. //CurrentButton.IsSelected = true;
  1183. UpdateRibbonColors();
  1184. var moduleName = sender.Header?.ToString() ?? "";
  1185. var panel = PanelHost.LoadPanel<T>(moduleName);
  1186. ContentControl.Content = panel;
  1187. Title =
  1188. $"{moduleName} - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1189. PanelHost.Refresh();
  1190. if (panel is NotificationPanel)
  1191. {
  1192. Logger.Send(LogType.Information, ClientFactory.UserID, "Disabling Heartbeat");
  1193. NotificationsWatchDog.IsEnabled = false;
  1194. Notifications.Visibility = Visibility.Collapsed;
  1195. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  1196. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  1197. }
  1198. else
  1199. {
  1200. ReloadNotifications();
  1201. }
  1202. if (sender != null)
  1203. {
  1204. var settings = new LocalConfiguration<AppSettings>().Load();
  1205. var module = string.Format("{0} / {1}", CurrentTab?.Header, sender.Header);
  1206. if (!settings.Settings.ContainsKey("CurrentPanel") || module != settings.Settings["CurrentPanel"])
  1207. {
  1208. settings.Settings["CurrentPanel"] = module;
  1209. try
  1210. {
  1211. new LocalConfiguration<AppSettings>().Save(settings);
  1212. }
  1213. catch (Exception e)
  1214. {
  1215. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1216. }
  1217. }
  1218. }
  1219. return panel;
  1220. }
  1221. }
  1222. private void UpdateRibbonColors()
  1223. {
  1224. foreach (var tab in _ribbon.Tabs)
  1225. {
  1226. bool bFound = false;
  1227. foreach (var grp in tab.Groups)
  1228. {
  1229. foreach (var btn in grp.Items)
  1230. {
  1231. if (btn is Fluent.Button fluentbutton)
  1232. {
  1233. bFound = bFound || (btn == CurrentButton);
  1234. fluentbutton.Background = (btn == CurrentButton) ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1235. fluentbutton.Foreground = (btn == CurrentButton) ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1236. }
  1237. }
  1238. tab.Background = bFound ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1239. tab.Foreground = bFound ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1240. }
  1241. }
  1242. }
  1243. private static void StartLocalDatabase(IProgress<string> progress)
  1244. {
  1245. var dirName = Path.GetDirectoryName(App.DatabaseSettings.FileName);
  1246. if (!Directory.Exists(dirName) && dirName != null)
  1247. Directory.CreateDirectory(dirName);
  1248. var FileName = App.DatabaseSettings.FileName;
  1249. var Exists = File.Exists(FileName);
  1250. progress.Report("Configuring Stores");
  1251. DbFactory.Stores = CoreUtils.TypeList(
  1252. new[]
  1253. {
  1254. typeof(Store<>).Assembly,
  1255. typeof(EquipmentStore).Assembly
  1256. },
  1257. myType =>
  1258. myType.IsClass
  1259. && !myType.IsAbstract
  1260. && !myType.IsGenericType
  1261. && myType.GetInterfaces().Contains(typeof(IStore))
  1262. ).ToArray();
  1263. DbFactory.ProviderFactory = new SQLiteProviderFactory(App.DatabaseSettings.FileName);
  1264. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  1265. DbFactory.Logo = App.DatabaseSettings.Logo;
  1266. progress.Report("Starting Local Database");
  1267. DbFactory.Start();
  1268. ClientFactory.DatabaseID = DbFactory.ID;
  1269. progress.Report("Checking Database");
  1270. var users = DbFactory.NewProvider(Logger.Main).Load<User>();
  1271. if (!users.Any())
  1272. {
  1273. var user = new User { UserID = "ADMIN", Password = "admin" };
  1274. DbFactory.NewProvider(Logger.Main).Save(user);
  1275. var employee = DbFactory.NewProvider(Logger.Main).Load(new Filter<Employee>(x => x.Code).IsEqualTo("ADMIN")).FirstOrDefault();
  1276. employee ??= new Employee { Code = "ADMIN", Name = "Administrator Account" };
  1277. employee.UserLink.ID = user.ID;
  1278. DbFactory.NewProvider(Logger.Main).Save(employee);
  1279. }
  1280. StoreUtils.GoogleAPIKey = App.DatabaseSettings.GoogleAPIKey;
  1281. Job.JobNumberPrefix = App.DatabaseSettings.JobPrefix;
  1282. PurchaseOrder.PONumberPrefix = App.DatabaseSettings.PurchaseOrderPrefix;
  1283. }
  1284. #endregion
  1285. #region Login Management
  1286. private ValidationStatus? TryAutoLogin()
  1287. {
  1288. ValidationStatus? result = null;
  1289. if (App.DatabaseSettings.LoginType == LoginType.UserID)
  1290. {
  1291. try
  1292. {
  1293. result = ClientFactory.Validate(App.DatabaseSettings.UserID, App.DatabaseSettings.Password);
  1294. }
  1295. catch (Exception e)
  1296. {
  1297. MessageWindow.ShowError("Error connecting to server.\nPlease check the server URL and port number.", e);
  1298. result = null;
  1299. }
  1300. if (result == ValidationStatus.INVALID)
  1301. {
  1302. MessageWindow.ShowMessage("Unable to Login with User ID: " + App.DatabaseSettings.UserID, "Login failed");
  1303. }
  1304. }
  1305. return result;
  1306. }
  1307. private ValidationStatus? DoLogin()
  1308. {
  1309. ValidationStatus? result = null;
  1310. if (result != ValidationStatus.VALID)
  1311. {
  1312. var login = new PinLogin(CoreUtils.GetVersion(), result ?? ValidationStatus.INVALID);
  1313. if (login.ShowDialog() == true)
  1314. {
  1315. result = ValidationStatus.VALID;
  1316. }
  1317. }
  1318. return result ?? ValidationStatus.INVALID;
  1319. }
  1320. /// <summary>
  1321. /// To be called after <see cref="DoLogin(bool)"/> and if a valid login session exists. Configures the main screen and loads the windows.
  1322. /// </summary>
  1323. /// <param name="progress">If not <see langword="null"/>, then rather than opening a new progress window, just uses that.</param>
  1324. private void AfterLogin(IProgress<string>? progress)
  1325. {
  1326. Logger.Send(LogType.Information, "", "Loading employee");
  1327. LoadCurrentEmployee();
  1328. if (CheckTimesheetBypass(true))
  1329. {
  1330. UpdateCurrentLogin();
  1331. }
  1332. else
  1333. {
  1334. MessageWindow.ShowMessage("You must clock on before logging in to PRS!", "Not clocked in.");
  1335. ClientFactory.InvalidateUser();
  1336. App.EmployeeID = Guid.Empty;
  1337. App.EmployeeName = "";
  1338. App.EmployeeCode = "";
  1339. App.EmployeeEmail = "";
  1340. }
  1341. Logger.Send(LogType.Information, "", "Setting colours");
  1342. if(progress is null)
  1343. {
  1344. ApplyColorScheme();
  1345. }
  1346. else
  1347. {
  1348. Dispatcher.Invoke(ApplyColorScheme);
  1349. }
  1350. Logger.Send(LogType.Information, "", "Configuring main window");
  1351. ConfigureMainScreen(progress);
  1352. Logger.Send(LogType.Information, "", "Loading current window");
  1353. if(progress is null)
  1354. {
  1355. LoadApplicationState();
  1356. }
  1357. else
  1358. {
  1359. Dispatcher.Invoke(LoadApplicationState);
  1360. }
  1361. Logger.Send(LogType.Information, "", "Loading secondary window");
  1362. if(progress is null)
  1363. {
  1364. LoadSecondaryWindows();
  1365. }
  1366. else
  1367. {
  1368. Dispatcher.Invoke(LoadSecondaryWindows);
  1369. }
  1370. //if (_ribbon.Menu.IsVisible)
  1371. //{
  1372. // _ribbon.;
  1373. //}
  1374. }
  1375. /// <summary>
  1376. /// 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.
  1377. /// </summary>
  1378. private void UpdateCurrentLogin()
  1379. {
  1380. if (CoreUtils.GetVersion().Equals("???"))
  1381. return;
  1382. // Register this station with the Server
  1383. // Later on, the heartbeat will check to make sure
  1384. // that the StationID hasn't changed. If it has,
  1385. // then we've logged in somewhere else and we'll
  1386. // drop out of this station
  1387. var curr = new Client<Login>().Query(
  1388. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  1389. null
  1390. ).Rows.FirstOrDefault();
  1391. if (curr != null)
  1392. {
  1393. var c = curr.ToObject<Login>();
  1394. c.StationID = station.StationID;
  1395. station = c;
  1396. }
  1397. else
  1398. {
  1399. station.User.ID = ClientFactory.UserGuid;
  1400. station.TimeStamp = DateTime.Now;
  1401. }
  1402. new Client<Login>().Save(station, "", (o, e) => { });
  1403. }
  1404. private void LoadCurrentEmployee()
  1405. {
  1406. var me = new Client<Employee>().Query(
  1407. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid),
  1408. Columns.None<Employee>().Add(x => x.ID).Add(x => x.Email).Add(x => x.Name)
  1409. );
  1410. App.EmployeeID = me.Rows.FirstOrDefault()?.Get<Employee, Guid>(x => x.ID) ?? Guid.Empty;
  1411. App.EmployeeName = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Name) ?? "";
  1412. App.EmployeeCode = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Code) ?? "";
  1413. App.EmployeeEmail = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Email) ?? "";
  1414. }
  1415. private void ExecuteLogout()
  1416. {
  1417. new Client<Login>().Delete(station, "");
  1418. station.ID = Guid.Empty;
  1419. App.EmployeeID = Guid.Empty;
  1420. App.EmployeeName = "";
  1421. App.EmployeeEmail = "";
  1422. }
  1423. /// <summary>
  1424. /// Logs the user out and unloads windows
  1425. /// </summary>
  1426. /// <param name="message">A message to display as the reason for logging out, or <c>null</c> for no message.</param>
  1427. private bool Logout(string? message = null, bool force = false)
  1428. {
  1429. // I really don't like all these try-catch blocks; unfortunately, if we are trying to log out and invalidate due to an unauthenticated user,
  1430. // all the queries that get called here will throw exceptions and thus break our system, failing to log out.
  1431. try
  1432. {
  1433. FinalizeAutoTimesheet();
  1434. }
  1435. catch
  1436. {
  1437. if (!force) throw;
  1438. }
  1439. // Try to unload the window;
  1440. try
  1441. {
  1442. UnloadWindow(null);
  1443. if (DatabaseType == DatabaseType.Standalone && !CoreUtils.GetVersion().Equals("???"))
  1444. scheduler.Stop();
  1445. }
  1446. catch
  1447. {
  1448. if (!force) throw;
  1449. }
  1450. // Next, try to set things to being empty
  1451. try
  1452. {
  1453. if (!CoreUtils.GetVersion().Equals("???"))
  1454. if (station.ID != Guid.Empty)
  1455. {
  1456. ExecuteLogout();
  1457. }
  1458. ClearTrackingKanban();
  1459. }
  1460. catch
  1461. {
  1462. if (!force) throw;
  1463. }
  1464. ClientFactory.InvalidateUser();
  1465. ConfigureMainScreen(null);
  1466. LoadSecondaryWindows();
  1467. if (message != null)
  1468. {
  1469. MessageWindow.ShowMessage(message, "Logged out");
  1470. }
  1471. if (DoLogin() == ValidationStatus.VALID)
  1472. {
  1473. AfterLogin(null);
  1474. }
  1475. return true;
  1476. }
  1477. #endregion
  1478. #region Timesheets
  1479. private void RefreshTimeSheets()
  1480. {
  1481. if (App.EmployeeID == Guid.Empty)
  1482. return;
  1483. var filter = new Filter<TimeSheet>(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID);
  1484. filter = filter.And(new Filter<TimeSheet>(x => x.Confirmed).IsEqualTo(DateTime.MinValue).Or(x => x.Date).IsEqualTo(DateTime.Today));
  1485. _timesheets = new Client<TimeSheet>().Query(
  1486. filter,
  1487. Columns.None<TimeSheet>().Add(
  1488. x => x.ID,
  1489. x => x.Date,
  1490. x => x.Finish
  1491. )
  1492. );
  1493. }
  1494. private CoreTable GetTimesheet()
  1495. {
  1496. return new Client<TimeSheet>().Query(
  1497. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today)
  1498. .And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID)
  1499. .And(x => x.Finish).IsEqualTo(TimeSpan.Zero)
  1500. );
  1501. }
  1502. private bool CheckTimesheetBypass(bool message)
  1503. {
  1504. if (!ClientFactory.IsSupported<TimeSheet>())
  1505. return true;
  1506. var isClockedOn = IsClockedOn();
  1507. if (!Security.IsAllowed<CanBypassTimeBench>())
  1508. {
  1509. if (!isClockedOn)
  1510. {
  1511. if (message)
  1512. MessageBox.Show("You must clock on before opening this screen");
  1513. return false;
  1514. }
  1515. return true;
  1516. }
  1517. if (Security.IsAllowed<AutoGenerateTimesheet>())
  1518. if (!isClockedOn)
  1519. {
  1520. var ts = new TimeSheet();
  1521. ts.Date = DateTime.Today;
  1522. ts.Start = DateTime.Now.TimeOfDay;
  1523. ts.EmployeeLink.ID = App.EmployeeID;
  1524. ts.Notes = "Automatic Login from PRS Desktop";
  1525. new Client<TimeSheet>().Save(ts, "AutoLogon because Timebench Bypass is enabled", (o, e) => { });
  1526. }
  1527. return true;
  1528. }
  1529. private bool IsClockedOn()
  1530. {
  1531. RefreshTimeSheets();
  1532. if (_timesheets == null)
  1533. return false;
  1534. return _timesheets.Rows.Any(r =>
  1535. r.Get<TimeSheet, DateTime>(c => c.Date).Date == DateTime.Today && r.Get<TimeSheet, TimeSpan>(c => c.Finish) == new TimeSpan());
  1536. }
  1537. private void FinalizeAutoTimesheet()
  1538. {
  1539. if (Security.IsAllowed<AutoGenerateTimesheet>())
  1540. {
  1541. var check = new Client<TimeSheet>().Query(
  1542. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today).And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID).And(x => x.Finish)
  1543. .IsEqualTo(TimeSpan.Zero)
  1544. );
  1545. if (check.Rows.Any())
  1546. {
  1547. var ts = check.Rows.First().ToObject<TimeSheet>();
  1548. if (DateTime.Now.TimeOfDay < ts.Start.Add(new TimeSpan(0, 2, 0)))
  1549. {
  1550. new Client<TimeSheet>().Delete(ts, "Deleting Auto TimeSheet because TimeBench Bypass is enabled", (o, ex) => { });
  1551. }
  1552. else
  1553. {
  1554. ts.Finish = DateTime.Now.TimeOfDay;
  1555. new Client<TimeSheet>().Save(ts, "Clocking off Auto Timesheet because Timesheet Bypass is enabled", (o, ex) => { });
  1556. }
  1557. }
  1558. }
  1559. }
  1560. #endregion
  1561. private string CurrentPanelSlug()
  1562. {
  1563. var app = new LocalConfiguration<AppSettings>().Load();
  1564. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1565. return module.LastOrDefault()?.Replace(" ", "_").Replace("/", "") ?? "";
  1566. }
  1567. private bool ShowHelp()
  1568. {
  1569. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + CurrentPanelSlug()) { UseShellExecute = true });
  1570. return true;
  1571. }
  1572. private void Wiki_Click(object sender, RoutedEventArgs e)
  1573. {
  1574. ShowHelp();
  1575. }
  1576. private void Window_Loaded(object sender, RoutedEventArgs e)
  1577. {
  1578. }
  1579. private void UnloadWindow(CancelEventArgs? cancel)
  1580. {
  1581. PanelHost.UnloadPanel(cancel);
  1582. if (cancel?.Cancel == true)
  1583. {
  1584. return;
  1585. }
  1586. Title =
  1587. $" - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1588. if (CurrentTab is not null)
  1589. {
  1590. var border = VisualUtils.EnumChildrenOfType(CurrentTab, typeof(Border)).LastOrDefault();
  1591. if (border != null)
  1592. {
  1593. ((Border)border).Background = new SolidColorBrush(Colors.Transparent);
  1594. ((Border)border).BorderBrush = new SolidColorBrush(Colors.Transparent);
  1595. }
  1596. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  1597. if (ReportsBar is not null)
  1598. {
  1599. ReportsBar.Items.Clear();
  1600. ReportsBar.Visibility = Visibility.Collapsed;
  1601. ReportsBar.IsLauncherVisible = false;
  1602. }
  1603. var ActionBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  1604. if (ActionBar is not null)
  1605. {
  1606. ActionBar.IsLauncherVisible = false;
  1607. foreach (var module in CurrentModules)
  1608. ActionBar.Items.Remove(module);
  1609. }
  1610. }
  1611. CurrentTab = null;
  1612. CurrentButton = null;
  1613. ContentControl.Content = null;
  1614. }
  1615. private void SecondaryWindow_Click(object sender, RoutedEventArgs e)
  1616. {
  1617. var panel = PanelHost.CurrentPanel;
  1618. if (panel is null) return;
  1619. var id = Guid.NewGuid();
  1620. var window = new Tuple<string, string, double, double, double, double>(
  1621. panel.GetType().EntityName(),
  1622. PanelHost.CurrentModuleName,
  1623. Left + 100,
  1624. Top + 100,
  1625. Width - 200,
  1626. Height - 200
  1627. );
  1628. App.DatabaseSettings.SecondaryWindows[id] = window;
  1629. new LocalConfiguration<DatabaseSettings>(App.Profile).Save(App.DatabaseSettings);
  1630. SecondaryWindows[id] = new SecondaryWindow(
  1631. id,
  1632. window.Item1,
  1633. window.Item2,
  1634. window.Item3,
  1635. window.Item4,
  1636. window.Item5,
  1637. window.Item6
  1638. );
  1639. SecondaryWindows[id].Show();
  1640. }
  1641. private void RibbonWindow_Activated(object sender, EventArgs e)
  1642. {
  1643. }
  1644. private void RegisterModules(IProgress<string> progress)
  1645. {
  1646. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1647. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1648. foreach (var item in bar.Items)
  1649. Dispatcher.Invoke(() =>
  1650. {
  1651. var button = item as RibbonButton;
  1652. if (button != null && button.Label != "Refresh")
  1653. if (bar.Header.Equals("Actions"))
  1654. Modules.Register(button.Label);
  1655. });
  1656. }
  1657. #region Visibility
  1658. private void SetVisibility(FrameworkElement button, bool visible)
  1659. {
  1660. var vResult = true;
  1661. var eResult = ClientFactory.UserGuid != Guid.Empty && visible;
  1662. button.Visibility = vResult && eResult ? Visibility.Visible : Visibility.Collapsed;
  1663. if (button is RibbonButton rb)
  1664. {
  1665. CustomModules.Register(rb.Label);
  1666. rb.IsEnabled = !OutstandingDailyReports(false);
  1667. }
  1668. }
  1669. private static void SetVisibleIfEither(FrameworkElement separator, FrameworkElement[] left, FrameworkElement[] right)
  1670. {
  1671. var bLeft = false;
  1672. foreach (var button in left)
  1673. bLeft = bLeft || button.Visibility == Visibility.Visible;
  1674. var bRight = false;
  1675. foreach (var button in right)
  1676. bRight = bRight || button.Visibility == Visibility.Visible;
  1677. separator.Visibility = bLeft && bRight ? Visibility.Visible : Visibility.Collapsed;
  1678. }
  1679. private static void SetVisibleIfAny(FrameworkElement separator, params FrameworkElement[] buttons)
  1680. {
  1681. var bVisible = false;
  1682. foreach (var button in buttons)
  1683. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1684. separator.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1685. }
  1686. private static void SetTabVisibleIfAny(Fluent.RibbonTabItem tab, params FrameworkElement[] buttons)
  1687. {
  1688. var bVisible = false;
  1689. foreach (var button in buttons)
  1690. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1691. tab.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1692. }
  1693. #endregion
  1694. private static Fluent.RibbonGroupBox? FindRibbonBar(Fluent.RibbonTabItem tab, Func<Fluent.RibbonGroupBox, bool> predicate)
  1695. {
  1696. foreach (var group in tab.Groups)
  1697. {
  1698. if (group != null)
  1699. if (predicate.Invoke(group))
  1700. return group;
  1701. }
  1702. return null;
  1703. }
  1704. #region Button Event Handlers
  1705. #region Common
  1706. private void Tasks_Checked(object sender, RoutedEventArgs e)
  1707. {
  1708. //LoadWindow<KanbanPanel>((RibbonButton)sender);
  1709. LoadWindow<TaskPanel>((Fluent.Button)sender);
  1710. }
  1711. private void DataEntry_Click(object sender, RoutedEventArgs e)
  1712. {
  1713. LoadWindow<DataEntryPanel>((Fluent.Button)sender);
  1714. }
  1715. private void Attendance_Checked(object sender, RoutedEventArgs e)
  1716. {
  1717. LoadWindow<AttendancePanel>((Fluent.Button)sender);
  1718. }
  1719. #endregion
  1720. #region Quotes
  1721. private void Quotes_Checked(object sender, RoutedEventArgs e)
  1722. {
  1723. LoadWindow<QuotePanel>((Fluent.Button)sender);
  1724. }
  1725. #endregion
  1726. #region Projects
  1727. private void Jobs_Checked(object sender, RoutedEventArgs e)
  1728. {
  1729. LoadWindow<ProjectsPanel>((Fluent.Button)sender);
  1730. }
  1731. private void ProjectPlanner_Checked(object sender, RoutedEventArgs e)
  1732. {
  1733. LoadWindow<JobResourcePlannerPanel>((Fluent.Button)sender);
  1734. }
  1735. private void DesignManagement_Checked(object sender, RoutedEventArgs e)
  1736. {
  1737. LoadWindow<StagingPanel>((Fluent.Button)sender);
  1738. }
  1739. private void Service_Checked(object sender, RoutedEventArgs e)
  1740. {
  1741. LoadWindow<ServicePanel>((Fluent.Button)sender);
  1742. }
  1743. #endregion
  1744. #region Manufacturing
  1745. private void ManufacturingMenu_Checked(object sender, RoutedEventArgs e)
  1746. {
  1747. LoadWindow<ManufacturingPanel>((Fluent.Button)sender);
  1748. }
  1749. private void FactoryFloorButton_Click(object sender, RoutedEventArgs e)
  1750. {
  1751. LoadWindow<FactoryPanel>((Fluent.Button)sender);
  1752. }
  1753. #endregion
  1754. #region Logistics
  1755. private void ReadyToGoMenu_Checked(object sender, RoutedEventArgs e)
  1756. {
  1757. LoadWindow<ReadyToGoPanel>((Fluent.Button)sender);
  1758. }
  1759. private void DispatchMenu_Checked(object sender, RoutedEventArgs e)
  1760. {
  1761. LoadWindow<DispatchPanel>((Fluent.Button)sender);
  1762. }
  1763. private void Requisitions_Checked(object sender, RoutedEventArgs e)
  1764. {
  1765. LoadWindow<RequisitionPanel>((Fluent.Button)sender);
  1766. }
  1767. #endregion
  1768. #region Products
  1769. #endregion
  1770. #region Human Resources
  1771. private void Timesheets_Checked(object sender, RoutedEventArgs e)
  1772. {
  1773. LoadWindow<TimesheetPanel>((Fluent.Button)sender);
  1774. }
  1775. #endregion
  1776. #region Accounts
  1777. #endregion
  1778. #region Equipment
  1779. private void Equipment_Checked(object sender, RoutedEventArgs e)
  1780. {
  1781. LoadWindow<EquipmentPanel>((Fluent.Button)sender);
  1782. }
  1783. #endregion
  1784. #region Dashboards
  1785. #endregion
  1786. private void Console_Click(object sender, RoutedEventArgs a)
  1787. {
  1788. if (_console is null)
  1789. {
  1790. _console = new DesktopConsole("Console");
  1791. _console.Closing += (o, args) => _console = null;
  1792. }
  1793. _console.Show();
  1794. }
  1795. //private void Purchases_Checked(object sender, RoutedEventArgs e)
  1796. //{
  1797. // LoadWindow(PurchasesMenu, new PurchasesPanel());
  1798. //}
  1799. private void Maps_Checked(object sender, RoutedEventArgs e)
  1800. {
  1801. LoadWindow<MapsPanel>((Fluent.Button)sender);
  1802. }
  1803. private void RefreshMenu_Click(object sender, RoutedEventArgs e)
  1804. {
  1805. PanelHost.Refresh();
  1806. }
  1807. private void UserSetup_Click(object sender, RoutedEventArgs e)
  1808. {
  1809. LoadWindow<UserPanel>((Fluent.Button)sender);
  1810. }
  1811. private void Employees_Click(object sender, RoutedEventArgs e)
  1812. {
  1813. LoadWindow<EmployeePanel>((Fluent.Button)sender);
  1814. }
  1815. private void Trackers_Click(object sender, RoutedEventArgs e)
  1816. {
  1817. LoadWindow<GPSTrackers>((Fluent.Button)sender);
  1818. }
  1819. private void DeliveredOnSiteMenu_Checked(object sender, RoutedEventArgs e)
  1820. {
  1821. LoadWindow<DeliveredOnSitePanel>((Fluent.Button)sender);
  1822. }
  1823. private void Products_Checked(object sender, RoutedEventArgs e)
  1824. {
  1825. LoadWindow<ProductsPanel>((Fluent.Button)sender);
  1826. }
  1827. private void StockLocations_Checked(object sender, RoutedEventArgs e)
  1828. {
  1829. LoadWindow<StockLocationPanel>((Fluent.Button)sender);
  1830. }
  1831. private void StockMovements_Checked(object sender, RoutedEventArgs e)
  1832. {
  1833. LoadWindow<StockMovementPanel>((Fluent.Button)sender);
  1834. }
  1835. private void StockForecastButton_Clicked(object sender, RoutedEventArgs e)
  1836. {
  1837. LoadWindow<StockForecastPanel>((Fluent.Button)sender);
  1838. }
  1839. private void ReservationManagementButton_Clicked(object sender, RoutedEventArgs e)
  1840. {
  1841. LoadWindow<ReservationManagementPanel>((Fluent.Button)sender);
  1842. }
  1843. private void KitsMasterList_Click(object sender, RoutedEventArgs e)
  1844. {
  1845. LoadWindow<KitPanel>((Fluent.Button)sender);
  1846. }
  1847. private void CostSheetsMasterList_Click(object sender, RoutedEventArgs e)
  1848. {
  1849. LoadWindow<CostSheetPanel>((Fluent.Button)sender);
  1850. }
  1851. private void LeaveRequestsButton_Click(object sender, RoutedEventArgs e)
  1852. {
  1853. LoadWindow<LeaveRequestPanel>((Fluent.Button)sender);
  1854. }
  1855. private void MeetingsButton_Click(object sender, RoutedEventArgs e)
  1856. {
  1857. LoadWindow<MeetingPanel>((Fluent.Button)sender);
  1858. }
  1859. private void OrgChartButton_Click(object sender, RoutedEventArgs e)
  1860. {
  1861. LoadWindow<OrgChartPanel>((Fluent.Button)sender);
  1862. }
  1863. private void SupplierList_Click(object sender, RoutedEventArgs e)
  1864. {
  1865. LoadWindow<SupplierPanel>((Fluent.Button)sender);
  1866. }
  1867. private void CustomerList_Click(object sender, RoutedEventArgs e)
  1868. {
  1869. LoadWindow<CustomerPanel>((Fluent.Button)sender);
  1870. }
  1871. private void CalendarButton_Click(object sender, RoutedEventArgs e)
  1872. {
  1873. LoadWindow<CalendarPanel>((Fluent.Button)sender);
  1874. }
  1875. private void EmployeePlannerButton_Click(object sender, RoutedEventArgs e)
  1876. {
  1877. LoadWindow<EmployeeResourcePlannerPanel>((Fluent.Button)sender);
  1878. }
  1879. private void EquipmentPlannerButton_Click(object sender, RoutedEventArgs e)
  1880. {
  1881. LoadWindow<EquipmentPlannerPanel>((Fluent.Button)sender);
  1882. }
  1883. private void InvoiceList_Click(object sender, RoutedEventArgs e)
  1884. {
  1885. LoadWindow<InvoicePanel>((Fluent.Button)sender);
  1886. }
  1887. private void ReceiptList_Click(object sender, RoutedEventArgs e)
  1888. {
  1889. LoadWindow<CustomerReceipts>((Fluent.Button)sender);
  1890. }
  1891. private void PaymentsList_Click(object sender, RoutedEventArgs e)
  1892. {
  1893. LoadWindow<SupplierPayments>((Fluent.Button)sender);
  1894. }
  1895. private void BillsList_Click(object sender, RoutedEventArgs e)
  1896. {
  1897. LoadWindow<SupplierBillPanel>((Fluent.Button)sender);
  1898. }
  1899. private void PurchasesList_Click(object sender, RoutedEventArgs e)
  1900. {
  1901. LoadWindow<SupplierPurchaseOrderPanel>((Fluent.Button)sender);
  1902. }
  1903. private void DeliveriesButton_Click(object sender, RoutedEventArgs e)
  1904. {
  1905. LoadWindow<DeliveryPanel>((Fluent.Button)sender);
  1906. }
  1907. private void FactoryAllocationButton_Click(object sender, RoutedEventArgs e)
  1908. {
  1909. LoadWindow<ManufacturingAllocationPanel>((Fluent.Button)sender);
  1910. }
  1911. private void Messages_Checked(object sender, RoutedEventArgs e)
  1912. {
  1913. LoadWindow<NotificationPanel>((Fluent.Button)sender);
  1914. }
  1915. private void DatabaseActivityButton_Click(object sender, RoutedEventArgs e)
  1916. {
  1917. LoadWindow<DatabaseActivityDashboard>((Fluent.Button)sender);
  1918. }
  1919. private void FactoryProductivityButton_Click(object sender, RoutedEventArgs e)
  1920. {
  1921. LoadWindow<FactoryProductivityDashboard>((Fluent.Button)sender);
  1922. }
  1923. private void TemplateAnalysisButton_Click(object sender, RoutedEventArgs e)
  1924. {
  1925. LoadWindow<ManufacturingTemplateAnalysis>((Fluent.Button)sender);
  1926. }
  1927. private void FactoryAnalysisButton_Click(object sender, RoutedEventArgs e)
  1928. {
  1929. LoadWindow<FactoryFloorAnalysis>((Fluent.Button)sender);
  1930. }
  1931. private void UserActivityButton_Click(object sender, RoutedEventArgs e)
  1932. {
  1933. LoadWindow<UserActivity>((Fluent.Button)sender);
  1934. }
  1935. private void QuickStatus_Click(object sender, RoutedEventArgs e)
  1936. {
  1937. LoadWindow<WidgetDashboard>((Fluent.Button)sender);
  1938. }
  1939. private void ConsignmentButton_Click(object sender, RoutedEventArgs e)
  1940. {
  1941. LoadWindow<ConsignmentsPanel>((Fluent.Button)sender);
  1942. }
  1943. //private void NotificationsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
  1944. //{
  1945. // if (NotificationsList.SelectedIndex < 0)
  1946. // return;
  1947. // var editors = NotificationsList.FindVisualChildren<InABox.DynamicGrid.ExtendedRichTextEditor>().ToArray();
  1948. // var selected = editors[NotificationsList.SelectedIndex];
  1949. // selected.Text = (String)selected.Tag; //NotificationsList.SelectedIndex.ToString();
  1950. //}
  1951. //private void ViewNotification_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
  1952. //{
  1953. // Notification notification = (sender as Label).Tag as Notification;
  1954. // NotificationDetails details = new NotificationDetails(notification);
  1955. // details.ShowDialog();
  1956. // ReloadNotifications();
  1957. //}
  1958. private void DailyReport_Checked(object sender, RoutedEventArgs e)
  1959. {
  1960. LoadWindow<DailyReport>((Fluent.Button)sender);
  1961. }
  1962. private void Library_Click(object sender, RoutedEventArgs e)
  1963. {
  1964. Process.Start(
  1965. new ProcessStartInfo
  1966. {
  1967. FileName = App.DatabaseSettings.LibraryLocation,
  1968. UseShellExecute = true,
  1969. Verb = "open"
  1970. }
  1971. );
  1972. }
  1973. private void SendNotificationClick(object sender, RoutedEventArgs e)
  1974. {
  1975. var form = new NotificationForm { Description = "" };
  1976. if (form.ShowDialog() == true)
  1977. ReloadNotifications();
  1978. }
  1979. private void CompanyInformation_Click(object sender, RoutedEventArgs e)
  1980. {
  1981. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  1982. if (info == null)
  1983. info = new CompanyInformation();
  1984. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  1985. }
  1986. #region Digital Forms
  1987. private void DigitalFormsFormsLibraryButton_Click(object sender, RoutedEventArgs e)
  1988. {
  1989. LoadWindow<DigitalFormsLibrary>((Fluent.Button)sender);
  1990. }
  1991. private void DigitalFormsCompletedFormsButton_Click(object sender, RoutedEventArgs e)
  1992. {
  1993. LoadWindow<CompletedFormsPanel>((Fluent.Button)sender);
  1994. }
  1995. #endregion
  1996. private void Dashboards_Checked(object sender, RoutedEventArgs e)
  1997. {
  1998. LoadWindow<UtilityDashboard>((Fluent.Button)sender);
  1999. }
  2000. private void Setup_Click(object sender, RoutedEventArgs e)
  2001. {
  2002. var tab = _ribbon.SelectedTabItem;
  2003. if (tab is null)
  2004. return;
  2005. var menu = new ContextMenu();
  2006. PanelHost.InitialiseSetupMenu(menu);
  2007. menu.IsOpen = true;
  2008. }
  2009. private void StartForm<TEntityForm, TEntity, TEntityLink>(DigitalForm form)
  2010. where TEntityForm : EntityForm<TEntity, TEntityLink, TEntityForm>, new()
  2011. where TEntity : Entity, new()
  2012. where TEntityLink : EntityLink<TEntity>, new()
  2013. {
  2014. var entityForm = new TEntityForm();
  2015. entityForm.Form.ID = form.ID;
  2016. entityForm.Description = form.Description;
  2017. var entity = DFUtils.NewEntity<TEntityForm, TEntity, TEntityLink>(form);
  2018. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel, entity))
  2019. {
  2020. dataModel.Update(null);
  2021. }
  2022. }
  2023. private void Forms_Click(object sender, RoutedEventArgs e)
  2024. {
  2025. var select = new MultiSelectDialog<DigitalForm>(
  2026. Filter<DigitalForm>.And(
  2027. LookupFactory.DefineChildFilter<KanbanForm, DigitalForm>(Array.Empty<KanbanForm>()),
  2028. new Filter<DigitalForm>(x => x.ID).InQuery(
  2029. new Filter<EmployeeDigitalForm>(x => x.Employee.ID).IsEqualTo(App.EmployeeID),
  2030. x => x.Form.ID)),
  2031. LookupFactory.DefineChildColumns<KanbanForm, DigitalForm>()
  2032. .Add(x => x.Description),
  2033. false);
  2034. if (select.ShowDialog() == true)
  2035. {
  2036. var digitalForm = select.Data().Rows.FirstOrDefault()?.ToObject<DigitalForm>();
  2037. if (digitalForm is not null)
  2038. {
  2039. StartForm<KanbanForm, Kanban, KanbanLink>(digitalForm);
  2040. }
  2041. };
  2042. }
  2043. #endregion
  2044. private bool OutstandingDailyReports(bool refresh)
  2045. {
  2046. if (!Security.IsAllowed<CanViewDailyReports>() || Security.IsAllowed<BypassOutstandingDailyReports>())
  2047. return false;
  2048. if (refresh)
  2049. RefreshTimeSheets();
  2050. if (_timesheets == null)
  2051. return false;
  2052. return _timesheets.Rows.Any(r => r.Get<TimeSheet, DateTime>(c => c.Date).Date < DateTime.Today);
  2053. }
  2054. private void ShutDownTransport()
  2055. {
  2056. if (_transport != null)
  2057. {
  2058. _transport.OnClose -= TransportConnectionLost;
  2059. if (_transport.IsConnected())
  2060. _transport.Disconnect();
  2061. _transport = null;
  2062. }
  2063. }
  2064. private void Window_Unloaded(object sender, RoutedEventArgs e)
  2065. {
  2066. ShutDownTransport();
  2067. }
  2068. private void RibbonWindow_Closed(object sender, EventArgs e)
  2069. {
  2070. ShutDownTransport();
  2071. DisconnectRecorderNotes();
  2072. Application.Current.Shutdown();
  2073. }
  2074. //private bool _closingFromSystemMenu = false;
  2075. private void Window_Closing(object sender, CancelEventArgs e)
  2076. {
  2077. /*if (!_closingFromSystemMenu && !CoreUtils.GetVersion().Equals("???"))
  2078. {
  2079. WindowState = WindowState.Minimized;
  2080. e.Cancel = true;
  2081. return;
  2082. }*/
  2083. PanelHost.UnloadPanel(e);
  2084. if (e.Cancel)
  2085. {
  2086. return;
  2087. }
  2088. App.IsClosing = true;
  2089. FinalizeAutoTimesheet();
  2090. if (!CoreUtils.GetVersion().Equals("???"))
  2091. scheduler.Stop();
  2092. CurrentTab = null;
  2093. UpdateRibbonColors();
  2094. if (!CoreUtils.GetVersion().Equals("???"))
  2095. if (station.ID != Guid.Empty)
  2096. ExecuteLogout();
  2097. ShutDownTransport();
  2098. }
  2099. #region Notifications + Heartbeat
  2100. private void ReceiveNotification(Notification notification)
  2101. {
  2102. if (Security.CanView<Notification>())
  2103. {
  2104. Notifications.AddNotification(notification);
  2105. }
  2106. foreach(var panel in Panels.OfType<NotificationPanel>())
  2107. {
  2108. panel.AddNotification(notification);
  2109. }
  2110. }
  2111. private void Notifications_Tick(object? sender, EventArgs e)
  2112. {
  2113. if (ClientFactory.UserGuid != Guid.Empty)
  2114. {
  2115. try
  2116. {
  2117. ReloadNotifications();
  2118. }
  2119. catch (Exception err)
  2120. {
  2121. Logger.Send(LogType.Error, ClientFactory.UserID,
  2122. string.Format("Exception in Notifications_Tick:ReloadNotifications() {0}\n{1}", err.Message, err.StackTrace));
  2123. }
  2124. Heartbeat();
  2125. try
  2126. {
  2127. CheckIsLoggedOn();
  2128. }
  2129. catch (Exception err2)
  2130. {
  2131. Logger.Send(LogType.Error, ClientFactory.UserID,
  2132. string.Format("Exception in Notifications_Tick:CheckIsLoggedOn() {0}\n{1}", err2.Message, err2.StackTrace));
  2133. }
  2134. }
  2135. //else
  2136. //{
  2137. // Logger.Send(LogType.Information, ClientFactory.UserID, "Notifications_Tick: ClientFactory.UserGuid is empty");
  2138. //}
  2139. }
  2140. private void CheckIsLoggedOn()
  2141. {
  2142. if (CoreUtils.GetVersion().Equals("???"))
  2143. return;
  2144. var bLogout = false;
  2145. if (!Security.IsAllowed<CanBypassTimeBench>())
  2146. if (!IsClockedOn())
  2147. {
  2148. Logger.Send(LogType.Information, ClientFactory.UserID, "User is no longer clocked in!");
  2149. bLogout = true;
  2150. Dispatcher.Invoke(() => { Logout(); });
  2151. }
  2152. if (!bLogout)
  2153. new Client<Login>().Query(
  2154. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  2155. Columns.None<Login>().Add(x => x.StationID),
  2156. null,
  2157. CoreRange.All,
  2158. (o, e) =>
  2159. {
  2160. if (e is RemoteException remote)
  2161. {
  2162. if (remote.Status == StatusCode.Unauthenticated)
  2163. {
  2164. Logger.Send(LogType.Information, ClientFactory.UserID, "User has been logged out");
  2165. Dispatcher.Invoke(() =>
  2166. {
  2167. Logout("You have been logged out due to inactivity");
  2168. });
  2169. }
  2170. else
  2171. {
  2172. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error in CheckIsLoggedOn(): {CoreUtils.FormatException(remote)}");
  2173. }
  2174. }
  2175. else if (e is not null)
  2176. {
  2177. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error in CheckIsLoggedOn(): {CoreUtils.FormatException(e)}");
  2178. }
  2179. else if (o is not null)
  2180. {
  2181. var row = o.Rows.FirstOrDefault();
  2182. if (row == null)
  2183. {
  2184. station.ID = Guid.Empty;
  2185. new Client<Login>().Save(station, "", (o1, e1) => { });
  2186. }
  2187. else if (!row.Get<Login, string>(c => c.StationID).Equals(station.StationID))
  2188. {
  2189. Logger.Send(LogType.Information, ClientFactory.UserID, "User logged in somewhere else!");
  2190. bLogout = true;
  2191. Dispatcher.Invoke(() => { Logout(); });
  2192. }
  2193. }
  2194. }
  2195. );
  2196. }
  2197. private void Heartbeat()
  2198. {
  2199. //Task.Run(() =>
  2200. //{
  2201. try
  2202. {
  2203. bool IsClockedOn = this.IsClockedOn();
  2204. if (IsClockedOn)
  2205. {
  2206. if ((_kanbantrackingassignment != null) && (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay))
  2207. {
  2208. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2209. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2210. }
  2211. if (Security.IsAllowed<MonitorApplicationWindows>())
  2212. {
  2213. if (ActivityHistory == null)
  2214. ActivityHistory = new LocalConfiguration<DailyActivityHistory>().Load();
  2215. var appname = OpenWindowGetter.GetActiveWindowProcess();
  2216. var title = OpenWindowGetter.GetActiveWindowTitle();
  2217. ActivityHistory.Activities[DateTime.Now] = (!string.IsNullOrWhiteSpace(appname) ? appname.Trim() + " - " : "") + title;
  2218. new LocalConfiguration<DailyActivityHistory>().Save(ActivityHistory);
  2219. }
  2220. }
  2221. PanelHost.Heartbeat();
  2222. foreach(var window in SecondaryWindows.Values)
  2223. {
  2224. window.Heartbeat();
  2225. }
  2226. }
  2227. catch (Exception err)
  2228. {
  2229. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Exception in Heartbeat: {0}\n{1}", err.Message, err.StackTrace));
  2230. }
  2231. //});
  2232. }
  2233. private void Notifications_Changed(object sender)
  2234. {
  2235. if (Notifications.IsActive)
  2236. {
  2237. Notifications.Visibility = Visibility.Visible;
  2238. DockingGrid.ColumnDefinitions[1].Width = new GridLength(4, GridUnitType.Pixel);
  2239. DockingGrid.ColumnDefinitions[2].Width = Equals(0.0, DockingGrid.ColumnDefinitions[2].Width.Value)
  2240. ? new GridLength(300, GridUnitType.Pixel)
  2241. : DockingGrid.ColumnDefinitions[2].Width;
  2242. }
  2243. else
  2244. {
  2245. Notifications.Visibility = Visibility.Collapsed;
  2246. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  2247. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  2248. }
  2249. }
  2250. private void ReloadNotifications()
  2251. {
  2252. if (Security.CanView<Notification>())
  2253. Notifications.Refresh();
  2254. if (!NotificationsWatchDog.IsEnabled)
  2255. {
  2256. //Logger.Send(LogType.Information, ClientFactory.UserID, "Enabling Heartbeat");
  2257. NotificationsWatchDog.IsEnabled = true;
  2258. }
  2259. }
  2260. #endregion
  2261. private void RibbonWindow_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  2262. {
  2263. PanelHost.IncrementTrackingModuleClick();
  2264. }
  2265. private void RibbonWindow_PreviewKeyUp(object sender, KeyEventArgs e)
  2266. {
  2267. PanelHost.IncrementTrackingModuleKey();
  2268. }
  2269. #region Recording
  2270. //private IntPtr myHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  2271. //{
  2272. // switch (msg)
  2273. // {
  2274. // case 0x100:
  2275. // if (_subject != null)
  2276. // {
  2277. // _recorder.Stop();
  2278. // pausestarted = DateTime.Now;
  2279. // _subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2280. // }
  2281. // break;
  2282. // default:
  2283. // messages.TryGetValue(msg, out int value);
  2284. // messages[msg] = value + 1;
  2285. // break;
  2286. // }
  2287. // return IntPtr.Zero;
  2288. //}
  2289. private void RecordScreenButton_Click(object sender, RoutedEventArgs e)
  2290. {
  2291. ToggleRecording();
  2292. }
  2293. private bool ToggleRecording()
  2294. {
  2295. if (!Security.IsAllowed<CanRecordScreen>())
  2296. return true;
  2297. if (_recorder is null)
  2298. {
  2299. var windowInteropHelper = new WindowInteropHelper(this);
  2300. var screen = Screen.FromHandle(windowInteropHelper.Handle);
  2301. _screenleft = screen.WorkingArea.Left;
  2302. _screentop = screen.WorkingArea.Top;
  2303. _screenwidth = screen.WorkingArea.Width;
  2304. _screenheight = screen.WorkingArea.Height;
  2305. //VIDEO_WIDTH = _screenwidth;
  2306. //VIDEO_HEIGHT = _screenheight;
  2307. //SetupJPEGEncoder();
  2308. messages.Clear();
  2309. _bitmaps.Clear();
  2310. ConnectToRecordNotes();
  2311. StartAudio();
  2312. _recorder = new DispatcherTimer();
  2313. _recorder.Tick += (timer, args) => { TakeScreenShot(); };
  2314. _recorder.Interval = TimeSpan.FromMilliseconds(1000 / FRAMES_PER_SECOND);
  2315. _recorder.Start();
  2316. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsBitmapImage();
  2317. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2318. RecordingNotesButton.Visibility = Visibility.Visible;
  2319. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2320. AudioRecordingButton.Visibility = Visibility.Visible;
  2321. }
  2322. else
  2323. {
  2324. using (new WaitCursor())
  2325. {
  2326. StopRecording();
  2327. _recorder.Stop();
  2328. _recorder = null;
  2329. DisconnectRecorderNotes();
  2330. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  2331. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2332. RecordingNotesButton.Visibility = Visibility.Hidden;
  2333. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2334. AudioRecordingButton.Visibility = Visibility.Hidden;
  2335. var filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos),
  2336. string.Format("PRS Screen Recording {0:yyyy-MM-dd hh-mm-ss-ff}.avi", DateTime.Now));
  2337. ProcessScreenShots(filename);
  2338. }
  2339. }
  2340. return true;
  2341. }
  2342. private void StopRecording()
  2343. {
  2344. try
  2345. {
  2346. _audio?.StopRecording();
  2347. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2348. }
  2349. catch (Exception e)
  2350. {
  2351. Logger.Send(LogType.Error, "", string.Format("Unable to stop Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2352. }
  2353. }
  2354. private void StartAudio()
  2355. {
  2356. _audioMuted = true;
  2357. _audioStream = new MemoryStream();
  2358. _audio = new WaveIn
  2359. {
  2360. DeviceNumber = 0,
  2361. WaveFormat = new WaveFormat(44100, 16, 2)
  2362. };
  2363. _audio.DataAvailable += (o, e) =>
  2364. {
  2365. var buf = _audioMuted ? new byte[e.BytesRecorded] : e.Buffer;
  2366. _audioStream.Write(buf, 0, e.BytesRecorded);
  2367. };
  2368. try
  2369. {
  2370. _audio.StartRecording();
  2371. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2372. }
  2373. catch (Exception e)
  2374. {
  2375. Logger.Send(LogType.Error, "", string.Format("Unable to start Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2376. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2377. }
  2378. }
  2379. private bool ToggleRecordingAudio()
  2380. {
  2381. if (!Security.IsAllowed<CanRecordScreen>())
  2382. return true;
  2383. if (_recorder != null)
  2384. {
  2385. _audioMuted = !_audioMuted;
  2386. AudioRecordingStatus.Source = _audioMuted
  2387. ? PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage()
  2388. : PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2389. }
  2390. return true;
  2391. }
  2392. private void DisconnectRecorderNotes()
  2393. {
  2394. if (_client != null)
  2395. {
  2396. _client.WriteAsync("QUIT");
  2397. _client.StopAsync();
  2398. _client = null;
  2399. }
  2400. }
  2401. private void ConnectToRecordNotes()
  2402. {
  2403. var filename = Debugger.IsAttached
  2404. ? "c:\\development\\comal\\prsrecordingnotes\\bin\\debug\\prsrecordingnotes.exe"
  2405. : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "recordingnotes", "prsrecordingnotes.exe");
  2406. Logger.Send(LogType.Information, "", "Recording Notes: " + filename);
  2407. _recordingnotes = Process.Start(filename);
  2408. //PipeSecurity sec = new System.IO.Pipes.PipeSecurity();
  2409. //sec.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));
  2410. _client = new PipeServer<string>("PRSScreenRecorder", formatter:new BinaryFormatter()); //, sec);
  2411. _client.ClientConnected += (o, args) => args.Connection.WriteAsync("Connected to PRSScreenRecorder");
  2412. _client.MessageReceived += (o, args) =>
  2413. {
  2414. if (string.Equals(args.Message, "RESUME"))
  2415. Dispatcher.Invoke(() =>
  2416. {
  2417. _audio?.StartRecording();
  2418. totalpauses += DateTime.Now - pausestarted;
  2419. _recorder?.Start();
  2420. Activate();
  2421. Focus();
  2422. });
  2423. };
  2424. _client.StartAsync();
  2425. }
  2426. private bool ShowRecordingNotes()
  2427. {
  2428. if (_recorder != null)
  2429. {
  2430. _audio?.StopRecording();
  2431. _recorder.Stop();
  2432. pausestarted = DateTime.Now;
  2433. _client?.WriteAsync("EDIT");
  2434. //_subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2435. }
  2436. return true;
  2437. }
  2438. private void TakeScreenShot()
  2439. {
  2440. using (var bmp = new ScreenCapture().CaptureScreen(_screenleft, _screentop, _screenwidth, _screenheight))
  2441. {
  2442. var cursor = PointToScreen(Mouse.GetPosition(this));
  2443. using (var g = Graphics.FromImage(bmp))
  2444. {
  2445. var brush = new SolidBrush(System.Drawing.Color.FromArgb(128, 255, 255, 0));
  2446. g.FillEllipse(brush, new RectangleF((float)cursor.X - 25F, (float)cursor.Y - 25F, 50F, 50F));
  2447. var pen = new Pen(System.Drawing.Color.Black, 0.75F);
  2448. g.DrawLine(pen, (float)cursor.X - 10F, (float)cursor.Y, (float)cursor.X + 10F, (float)cursor.Y);
  2449. g.DrawLine(pen, (float)cursor.X, (float)cursor.Y - 10F, (float)cursor.X, (float)cursor.Y + 10F);
  2450. }
  2451. var key = DateTime.Now - totalpauses;
  2452. using (var reduced = ReduceBitmap(bmp, VIDEO_WIDTH, VIDEO_HEIGHT))
  2453. {
  2454. var ms = new MemoryStream();
  2455. reduced.Save(ms, ImageFormat.Png);
  2456. ms.Position = 0;
  2457. _bitmaps[key] = ms;
  2458. }
  2459. }
  2460. }
  2461. public Bitmap ReduceBitmap(Bitmap original, int reducedWidth, int reducedHeight)
  2462. {
  2463. var reduced = new Bitmap(reducedWidth, reducedHeight);
  2464. using (var dc = Graphics.FromImage(reduced))
  2465. {
  2466. // Figure out the ratio
  2467. var ratioX = (double)reducedWidth / original.Width;
  2468. var ratioY = (double)reducedHeight / original.Height;
  2469. // use whichever multiplier is smaller
  2470. var ratio = ratioX < ratioY ? ratioX : ratioY;
  2471. // now we can get the new height and width
  2472. var newHeight = Convert.ToInt32(original.Height * ratio);
  2473. var newWidth = Convert.ToInt32(original.Width * ratio);
  2474. // Now calculate the X,Y position of the upper-left corner
  2475. // (one of these will always be zero)
  2476. var posX = Convert.ToInt32((reducedWidth - original.Width * ratio) / 2);
  2477. var posY = Convert.ToInt32((reducedHeight - original.Height * ratio) / 2);
  2478. dc.InterpolationMode = InterpolationMode.HighQualityBicubic;
  2479. dc.Clear(System.Drawing.Color.Black); // white padding
  2480. //dc.DrawImage(original, posX, posY, newWidth, newHeight);
  2481. dc.DrawImage(original, new Rectangle(posX, posY, newWidth, newHeight), new Rectangle(0, 0, original.Width, original.Height),
  2482. GraphicsUnit.Pixel);
  2483. }
  2484. return reduced;
  2485. }
  2486. public static byte[] BitmapToByteArray(Bitmap bitmap, int width, int height)
  2487. {
  2488. // and buffer of appropriate size for storing its bits
  2489. var buffer = new byte[width * height * 4];
  2490. var pixelFormat = PixelFormat.Format32bppRgb;
  2491. // Now copy bits from bitmap to buffer
  2492. var bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);
  2493. //Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2494. Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2495. bitmap.UnlockBits(bits);
  2496. return buffer;
  2497. }
  2498. private void ProcessScreenShots(string filename)
  2499. {
  2500. if (!_bitmaps.Any() || _audioStream is null)
  2501. return;
  2502. Progress.Show("Saving Video");
  2503. var framRate = 10;
  2504. using (var writer = new AviWriter(filename))
  2505. {
  2506. writer.FramesPerSecond = framRate;
  2507. writer.EmitIndex1 = true;
  2508. _audioStream.Position = 0;
  2509. var audio = writer.AddAudioStream(2);
  2510. //audio.WriteBlock(_audioStream.GetBuffer(), 0, (int)_audioStream.Length);
  2511. //File.WriteAllBytes(Path.ChangeExtension(filename, "wav"), _audioStream.GetBuffer());
  2512. var audioByteRate = audio.BitsPerSample / 8 * audio.ChannelCount * audio.SamplesPerSecond;
  2513. var audioBlockSize = (int)(audioByteRate / writer.FramesPerSecond);
  2514. var audioBuffer = new byte[audioBlockSize];
  2515. _audioStream.Position = 0;
  2516. var encoder = new MJpegWpfVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT, 50);
  2517. var stream = writer.AddEncodingVideoStream(encoder, true, VIDEO_WIDTH, VIDEO_HEIGHT);
  2518. //var encoder = new SharpAvi.Codecs.UncompressedVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT);
  2519. //var stream = writer.AddEncodingVideoStream(encoder,true,VIDEO_WIDTH, VIDEO_HEIGHT);
  2520. //stream.Codec = CodecIds.Uncompressed;
  2521. //stream.BitsPerPixel = BitsPerPixel.Bpp16;
  2522. IEnumerable<DateTime> keys = _bitmaps.Keys.OrderBy(x => x);
  2523. var start = keys.First();
  2524. var end = keys.Last();
  2525. for (var cur = start; cur <= end; cur = cur + TimeSpan.FromMilliseconds(100))
  2526. {
  2527. Progress.SetMessage(string.Format("Processing ({0:F2} complete)",
  2528. (cur - start).TotalSeconds * 100.0F / (end - start).TotalSeconds));
  2529. var key = keys.LastOrDefault(x => x <= cur);
  2530. if (_bitmaps.ContainsKey(key))
  2531. {
  2532. var frame = (Image.FromStream(_bitmaps[key]) as Bitmap)!;
  2533. //frame.RotateFlip(RotateFlipType.RotateNoneFlipY);
  2534. var buf = BitmapToByteArray(frame, stream.Width, stream.Height);
  2535. stream.WriteFrame(true, buf, 0, buf.Length);
  2536. if (_audioStream.Position < _audioStream.Length)
  2537. {
  2538. var bytes = _audioStream.Read(audioBuffer, 0, audioBlockSize);
  2539. audio.WriteBlock(audioBuffer, 0, bytes);
  2540. }
  2541. }
  2542. }
  2543. writer.Close();
  2544. //foreach (var key in _bitmaps.Keys)
  2545. // File.Delete(_bitmaps[key]);
  2546. }
  2547. Progress.SetMessage("Transcoding");
  2548. //var inputFile = new MediaFile { Filename = filename };
  2549. //var outputFile = new MediaFile { Filename = Path.ChangeExtension(filename, "mp4") };
  2550. //using (var engine = new Engine())
  2551. //{
  2552. // //engine.ConvertProgressEvent += ConvertProgressEvent;
  2553. // engine.Convert(inputFile, outputFile);
  2554. //}
  2555. Progress.Close();
  2556. var dirName = Path.GetDirectoryName(filename);
  2557. if (dirName is not null)
  2558. {
  2559. var startInfo = new ProcessStartInfo(dirName);
  2560. startInfo.Verb = "open";
  2561. startInfo.UseShellExecute = true;
  2562. Process.Start(startInfo);
  2563. //MessageBox.Show("Recording Saved");
  2564. }
  2565. }
  2566. private void VideoRecordingButton_Click(object sender, RoutedEventArgs e)
  2567. {
  2568. ToggleRecording();
  2569. }
  2570. private void AudioRecordingButton_Click(object sender, RoutedEventArgs e)
  2571. {
  2572. ToggleRecordingAudio();
  2573. }
  2574. private void RecordingNotesButton_Click(object sender, RoutedEventArgs e)
  2575. {
  2576. ShowRecordingNotes();
  2577. }
  2578. #endregion
  2579. public static void ActivateWindow(Window window)
  2580. {
  2581. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2582. var threadId1 = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
  2583. var threadId2 = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
  2584. if (threadId1 != threadId2)
  2585. {
  2586. AttachThreadInput(threadId1, threadId2, true);
  2587. SetForegroundWindow(hwnd);
  2588. AttachThreadInput(threadId1, threadId2, false);
  2589. }
  2590. else
  2591. {
  2592. SetForegroundWindow(hwnd);
  2593. }
  2594. }
  2595. private static IntPtr GetForegroundWindow()
  2596. {
  2597. var active = GetActiveWindow();
  2598. var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => new WindowInteropHelper(x).Handle == active);
  2599. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2600. return hwnd;
  2601. }
  2602. [DllImport("user32.dll", SetLastError = true)]
  2603. private static extern IntPtr SetForegroundWindow(IntPtr hWnd);
  2604. [DllImport("user32.dll")]
  2605. private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
  2606. [DllImport("user32.dll")]
  2607. private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
  2608. [DllImport("user32.dll")]
  2609. private static extern IntPtr GetActiveWindow();
  2610. #region Check For Updates
  2611. private string GetUpdateLocation()
  2612. {
  2613. if (App.DatabaseSettings.DatabaseType == DatabaseType.Networked)
  2614. {
  2615. string url = "";
  2616. //var domain = App.DatabaseSettings.URL.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).Last();
  2617. //var port = App.DatabaseSettings.Port;
  2618. var domain = ClientFactory.Parameters?.FirstOrDefault()?.ToString() ?? "";
  2619. domain = domain.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? "";
  2620. if (!String.IsNullOrWhiteSpace(domain))
  2621. {
  2622. try
  2623. {
  2624. var client = new HttpClient { BaseAddress = new Uri($"https://{domain}") };
  2625. client.GetAsync("operations").Wait();
  2626. url = $"https://{domain}";
  2627. }
  2628. catch (Exception)
  2629. {
  2630. url = $"http://{domain}";
  2631. }
  2632. }
  2633. return url;
  2634. }
  2635. else
  2636. return Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update");
  2637. }
  2638. private string GetLatestVersion(string location)
  2639. {
  2640. return Client.Version();
  2641. }
  2642. private string GetReleaseNotes(string location)
  2643. {
  2644. return Client.ReleaseNotes();
  2645. }
  2646. private byte[]? GetInstaller(string location)
  2647. {
  2648. return Client.Installer();
  2649. }
  2650. private void CheckForUpdates()
  2651. {
  2652. Update.CheckForUpdates(
  2653. GetUpdateLocation, GetLatestVersion, GetReleaseNotes, GetInstaller, null, App.AutoUpdateSettings.Elevated, "PRSDesktopSetup.exe");
  2654. }
  2655. #endregion
  2656. #region Modules + Reports
  2657. public void ClearActions()
  2658. {
  2659. foreach (var module in CurrentModules)
  2660. {
  2661. if (module.Parent is Fluent.RibbonGroupBox bar)
  2662. bar.Items.Remove(module);
  2663. }
  2664. CurrentModules.Clear();
  2665. }
  2666. public void ClearReports()
  2667. {
  2668. if (CurrentTab is not null)
  2669. {
  2670. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  2671. if (ReportsBar is not null)
  2672. {
  2673. ReportsBar.Visibility = Security.IsAllowed<CanPrintReports>() ? Visibility.Visible : Visibility.Collapsed;
  2674. ReportsBar.Items.Clear();
  2675. }
  2676. }
  2677. }
  2678. public void CreateReport(PanelAction action)
  2679. {
  2680. if (CurrentTab is null)
  2681. return;
  2682. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  2683. if (ReportsBar is not null)
  2684. {
  2685. var button = new Fluent.Button
  2686. {
  2687. Header = action.Caption,
  2688. LargeIcon = action.Image.AsBitmapImage(),
  2689. MinWidth = 60
  2690. };
  2691. if (action.Menu is not null)
  2692. {
  2693. button.ContextMenu = action.Menu;
  2694. }
  2695. button.Click += (o, e) =>
  2696. {
  2697. action.Execute();
  2698. };
  2699. ReportsBar.Items.Add(button);
  2700. }
  2701. }
  2702. public void CreatePanelAction(PanelAction action)
  2703. {
  2704. if (CurrentTab is null)
  2705. return;
  2706. var Actions = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  2707. if (Actions is not null)
  2708. {
  2709. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  2710. {
  2711. var sep = new RibbonSeparator();
  2712. CurrentModules.Add(sep);
  2713. Actions.Items.Add(sep);
  2714. }
  2715. var button = new Fluent.Button
  2716. {
  2717. Header = action.Caption,
  2718. LargeIcon = action.Image?.AsBitmapImage(),
  2719. MinWidth = 60
  2720. };
  2721. button.Bind<PanelAction, String>(Fluent.Button.HeaderProperty, x=>x.Caption, null);
  2722. button.Bind<PanelAction, Bitmap>(Fluent.Button.LargeIconProperty, x => x.Image, new BitmapToBitmapImageConverter());
  2723. button.Bind<PanelAction, ContextMenu?>(Fluent.Button.ContextMenuProperty, x=>x.Menu);
  2724. button.Bind<PanelAction, bool>(Fluent.Button.IsEnabledProperty, x => x.IsEnabled);
  2725. button.Bind<PanelAction, Visibility>(Fluent.Button.VisibilityProperty, x => x.Visibility);
  2726. button.DataContext = action;
  2727. button.Click += (o, e) => action.Execute();
  2728. Actions.Items.Add(button);
  2729. CurrentModules.Add(button);
  2730. }
  2731. }
  2732. #endregion
  2733. #region Tracking Kanban
  2734. private void SelectTask_Click(object sender, RoutedEventArgs e)
  2735. {
  2736. ContextMenu menu = new ContextMenu();
  2737. MenuItem others = new MenuItem() { Header = "Other Tasks" };
  2738. using (new WaitCursor())
  2739. {
  2740. var kanbans = new Client<KanbanSubscriber>().Query(
  2741. new Filter<KanbanSubscriber>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
  2742. .And(x => x.Kanban.Completed).IsEqualTo(DateTime.MinValue)
  2743. .And(x => x.Kanban.Closed).IsEqualTo(DateTime.MinValue),
  2744. Columns.None<KanbanSubscriber>().Add(x => x.Kanban.ID)
  2745. .Add(x => x.Kanban.Number)
  2746. .Add(x => x.Kanban.Title)
  2747. .Add(x => x.Assignee),
  2748. new SortOrder<KanbanSubscriber>(x => x.Kanban.Number, SortDirection.Ascending)
  2749. );
  2750. foreach (var row in kanbans.Rows)
  2751. {
  2752. CreateTaskMenu(row.Get<KanbanSubscriber, bool>(c => c.Assignee) ? menu.Items : others.Items,
  2753. String.Format("{0} {1}",
  2754. row.Get<KanbanSubscriber, int>(c => c.Kanban.Number),
  2755. row.Get<KanbanSubscriber, String>(c => c.Kanban.Title)),
  2756. row.Get<KanbanSubscriber, Guid>(c => c.Kanban.ID)
  2757. );
  2758. }
  2759. menu.Items.Add(new Separator());
  2760. menu.Items.Add(others);
  2761. menu.Items.Add(new Separator());
  2762. CreateTaskMenu(menu.Items, "(No Task Selected)", Guid.Empty);
  2763. }
  2764. menu.IsOpen = true;
  2765. }
  2766. private Assignment? _kanbantrackingassignment = null;
  2767. private void SetTrackingKanban(Guid kanbanID, string header)
  2768. {
  2769. SelectedTaskName.Content = header;
  2770. var createNewAssignment = false;
  2771. if (_kanbantrackingassignment is not null)
  2772. {
  2773. if (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay)
  2774. {
  2775. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2776. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2777. }
  2778. // Update Existing Kanban
  2779. if (kanbanID == Guid.Empty)
  2780. _kanbantrackingassignment = null;
  2781. else if (_kanbantrackingassignment.Task.ID != kanbanID)
  2782. {
  2783. createNewAssignment = true;
  2784. }
  2785. }
  2786. else if (kanbanID != Guid.Empty)
  2787. {
  2788. createNewAssignment = true;
  2789. }
  2790. if (createNewAssignment)
  2791. {
  2792. _kanbantrackingassignment = new Assignment();
  2793. _kanbantrackingassignment.Task.ID = kanbanID;
  2794. _kanbantrackingassignment.EmployeeLink.ID = App.EmployeeID;
  2795. _kanbantrackingassignment.Title = header;
  2796. _kanbantrackingassignment.Date = DateTime.Today;
  2797. _kanbantrackingassignment.Actual.Start = DateTime.Now.TimeOfDay;
  2798. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay.Add(new TimeSpan(0, 2, 0));
  2799. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2800. }
  2801. }
  2802. private void ClearTrackingKanban()
  2803. => SetTrackingKanban(Guid.Empty, "(No Task Selected)");
  2804. private void CreateTaskMenu(ItemCollection items, String title, Guid id)
  2805. {
  2806. var item = new MenuItem()
  2807. {
  2808. Header = title,
  2809. Tag = id
  2810. };
  2811. item.Click += (o, args) =>
  2812. {
  2813. if (o is not MenuItem menu) return;
  2814. SetTrackingKanban((Guid)item.Tag, (menu.Header as string) ?? "");
  2815. };
  2816. items.Add(item);
  2817. }
  2818. #endregion
  2819. private void DockPanelBorder_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
  2820. {
  2821. if (sender is not Border border || !border.IsVisible)
  2822. return;
  2823. var dock = border.Child is IDockPanel panel ? panel : border.Child?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  2824. if (dock is null)
  2825. return;
  2826. dock.Refresh();
  2827. }
  2828. private void DockPanel_OnIsActiveChanged(object? sender, EventArgs e)
  2829. {
  2830. if (sender is not LayoutAnchorable layout)
  2831. return;
  2832. var content = layout.Content as DependencyObject;
  2833. var dock = content is IDockPanel panel ? panel : content?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  2834. if (dock is null)
  2835. return;
  2836. if (layout.IsActive && layout.IsVisible)
  2837. dock.Refresh();
  2838. }
  2839. private void _ribbon_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  2840. {
  2841. e.Handled = true;
  2842. }
  2843. #region Backstage Functions
  2844. private enum DatabaseConfigurationResult
  2845. {
  2846. RestartRequired,
  2847. RestartNotRequired,
  2848. Cancel
  2849. }
  2850. private DatabaseConfigurationResult ShowDatabaseConfiguration()
  2851. {
  2852. DatabaseConfigurationResult result;
  2853. var config = new DataBaseConfiguration();
  2854. if (config.ShowDialog() == true)
  2855. {
  2856. var newsettings = new LocalConfiguration<DatabaseSettings>(App.Profile).Load();
  2857. if (newsettings.RestartRequired(App.DatabaseSettings))
  2858. {
  2859. result = DatabaseConfigurationResult.RestartRequired;
  2860. }
  2861. else
  2862. {
  2863. result = DatabaseConfigurationResult.RestartNotRequired;
  2864. }
  2865. if ((newsettings.DatabaseType == DatabaseType.Standalone) && (newsettings.ColorScheme != App.DatabaseSettings.ColorScheme))
  2866. {
  2867. App.DatabaseSettings.ColorScheme = newsettings.ColorScheme;
  2868. ApplyColorScheme();
  2869. }
  2870. }
  2871. else
  2872. {
  2873. result = DatabaseConfigurationResult.Cancel;
  2874. }
  2875. return result;
  2876. }
  2877. private void DatabaseSettings_OnClick(object sender, RoutedEventArgs e)
  2878. {
  2879. switch (ShowDatabaseConfiguration())
  2880. {
  2881. case DatabaseConfigurationResult.RestartRequired:
  2882. MessageBox.Show("Please restart the application to apply these changes!");
  2883. break;
  2884. }
  2885. }
  2886. private void CompanyInformation_OnClick(object sender, RoutedEventArgs e)
  2887. {
  2888. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  2889. if (info == null)
  2890. info = new CompanyInformation();
  2891. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  2892. }
  2893. private void SecurityDefaultsButton_OnClick(object sender, RoutedEventArgs e)
  2894. {
  2895. var window = new GlobalTokenWindow();
  2896. window.ShowDialog();
  2897. Security.Reset();
  2898. }
  2899. private void SystemLogsButton_OnClick(object sender, RoutedEventArgs e)
  2900. {
  2901. var logfile = Path.Combine(CoreUtils.GetPath(), string.Format("{0:yyyy-MM-dd}.log", DateTime.Today));
  2902. if (File.Exists(logfile))
  2903. {
  2904. var startInfo = new ProcessStartInfo("notepad.exe", logfile);
  2905. startInfo.Verb = "open";
  2906. startInfo.UseShellExecute = true;
  2907. Process.Start(startInfo);
  2908. }
  2909. else
  2910. {
  2911. MessageBox.Show(logfile + " does not exist!");
  2912. }
  2913. }
  2914. private void DocumentTypeList_OnClick(object sender, RoutedEventArgs e)
  2915. {
  2916. var list = new MasterList(typeof(DocumentType));
  2917. list.ShowDialog();
  2918. }
  2919. private void EditDetailsButton_OnClick(object sender, RoutedEventArgs e)
  2920. {
  2921. var employee = new Client<Employee>().Query(
  2922. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid))
  2923. .Rows.FirstOrDefault()?.ToObject<Employee>();
  2924. var item = new MyDetailsConfiguration(employee);
  2925. item.User = ClientFactory.UserGuid;
  2926. var buttons = new DynamicEditorButtons();
  2927. buttons.Add("Change Password", null, item, (sender, item) =>
  2928. {
  2929. var details = (item as MyDetailsConfiguration)!;
  2930. var changePassword = new ChangePassword(details.User);
  2931. if (changePassword.ShowDialog() == true && changePassword.Password != null)
  2932. {
  2933. var newUser = new User();
  2934. newUser.ID = details.User;
  2935. ChangePassword.ChangeUserPassword(newUser, changePassword.Password);
  2936. new Client<User>().Save(newUser, "Changed Password");
  2937. MessageBox.Show("Password changed!");
  2938. }
  2939. });
  2940. var editor = new DynamicEditorForm(typeof(MyDetailsConfiguration), buttons: buttons);
  2941. if (employee == null)
  2942. {
  2943. editor.OnFormCustomiseEditor += (sender, items, column, editor) =>
  2944. {
  2945. editor.Editable = Editable.Disabled;
  2946. };
  2947. }
  2948. editor.Items = new BaseObject[] { item };
  2949. if (editor.ShowDialog() == true)
  2950. {
  2951. if (employee != null)
  2952. {
  2953. item.SaveTo(employee);
  2954. new Client<Employee>().Save(employee, "Edited by user");
  2955. }
  2956. }
  2957. }
  2958. private void LogoutButton_OnClick(object sender, RoutedEventArgs e)
  2959. {
  2960. Logout();
  2961. }
  2962. private void LoginButton_OnClick(object sender, RoutedEventArgs e)
  2963. {
  2964. if (DoLogin() == ValidationStatus.VALID)
  2965. AfterLogin(null);
  2966. }
  2967. private void ExitButton_OnClick(object sender, RoutedEventArgs e)
  2968. {
  2969. //_closingFromSystemMenu = true;
  2970. Close();
  2971. }
  2972. #endregion
  2973. }