MainWindow.xaml.cs 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555
  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 - ({0:hh\\:mm})", DateTime.Now - lost);
  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.Provider = new SQLiteProvider(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.Provider.Load<User>();
  1271. if (!users.Any())
  1272. {
  1273. var user = new User { UserID = "ADMIN", Password = "admin" };
  1274. DbFactory.Provider.Save(user);
  1275. var employee = DbFactory.Provider.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.Provider.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. (o, e) =>
  2158. {
  2159. if (e is RemoteException remote)
  2160. {
  2161. if (remote.Status == StatusCode.Unauthenticated)
  2162. {
  2163. Logger.Send(LogType.Information, ClientFactory.UserID, "User has been logged out");
  2164. Dispatcher.Invoke(() =>
  2165. {
  2166. Logout("You have been logged out due to inactivity");
  2167. });
  2168. }
  2169. else
  2170. {
  2171. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error in CheckIsLoggedOn(): {CoreUtils.FormatException(remote)}");
  2172. }
  2173. }
  2174. else if (e is not null)
  2175. {
  2176. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error in CheckIsLoggedOn(): {CoreUtils.FormatException(e)}");
  2177. }
  2178. else if (o is not null)
  2179. {
  2180. var row = o.Rows.FirstOrDefault();
  2181. if (row == null)
  2182. {
  2183. station.ID = Guid.Empty;
  2184. new Client<Login>().Save(station, "", (o1, e1) => { });
  2185. }
  2186. else if (!row.Get<Login, string>(c => c.StationID).Equals(station.StationID))
  2187. {
  2188. Logger.Send(LogType.Information, ClientFactory.UserID, "User logged in somewhere else!");
  2189. bLogout = true;
  2190. Dispatcher.Invoke(() => { Logout(); });
  2191. }
  2192. }
  2193. }
  2194. );
  2195. }
  2196. private void Heartbeat()
  2197. {
  2198. //Task.Run(() =>
  2199. //{
  2200. try
  2201. {
  2202. bool IsClockedOn = this.IsClockedOn();
  2203. if (IsClockedOn)
  2204. {
  2205. if ((_kanbantrackingassignment != null) && (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay))
  2206. {
  2207. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2208. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2209. }
  2210. if (Security.IsAllowed<MonitorApplicationWindows>())
  2211. {
  2212. if (ActivityHistory == null)
  2213. ActivityHistory = new LocalConfiguration<DailyActivityHistory>().Load();
  2214. var appname = OpenWindowGetter.GetActiveWindowProcess();
  2215. var title = OpenWindowGetter.GetActiveWindowTitle();
  2216. ActivityHistory.Activities[DateTime.Now] = (!string.IsNullOrWhiteSpace(appname) ? appname.Trim() + " - " : "") + title;
  2217. new LocalConfiguration<DailyActivityHistory>().Save(ActivityHistory);
  2218. }
  2219. }
  2220. PanelHost.Heartbeat();
  2221. foreach(var window in SecondaryWindows.Values)
  2222. {
  2223. window.Heartbeat();
  2224. }
  2225. }
  2226. catch (Exception err)
  2227. {
  2228. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Exception in Heartbeat: {0}\n{1}", err.Message, err.StackTrace));
  2229. }
  2230. //});
  2231. }
  2232. private void Notifications_Changed(object sender)
  2233. {
  2234. if (Notifications.IsActive)
  2235. {
  2236. Notifications.Visibility = Visibility.Visible;
  2237. DockingGrid.ColumnDefinitions[1].Width = new GridLength(4, GridUnitType.Pixel);
  2238. DockingGrid.ColumnDefinitions[2].Width = Equals(0.0, DockingGrid.ColumnDefinitions[2].Width.Value)
  2239. ? new GridLength(300, GridUnitType.Pixel)
  2240. : DockingGrid.ColumnDefinitions[2].Width;
  2241. }
  2242. else
  2243. {
  2244. Notifications.Visibility = Visibility.Collapsed;
  2245. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  2246. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  2247. }
  2248. }
  2249. private void ReloadNotifications()
  2250. {
  2251. if (Security.CanView<Notification>())
  2252. Notifications.Refresh();
  2253. if (!NotificationsWatchDog.IsEnabled)
  2254. {
  2255. //Logger.Send(LogType.Information, ClientFactory.UserID, "Enabling Heartbeat");
  2256. NotificationsWatchDog.IsEnabled = true;
  2257. }
  2258. }
  2259. #endregion
  2260. private void RibbonWindow_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  2261. {
  2262. PanelHost.IncrementTrackingModuleClick();
  2263. }
  2264. private void RibbonWindow_PreviewKeyUp(object sender, KeyEventArgs e)
  2265. {
  2266. PanelHost.IncrementTrackingModuleKey();
  2267. }
  2268. #region Recording
  2269. //private IntPtr myHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  2270. //{
  2271. // switch (msg)
  2272. // {
  2273. // case 0x100:
  2274. // if (_subject != null)
  2275. // {
  2276. // _recorder.Stop();
  2277. // pausestarted = DateTime.Now;
  2278. // _subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2279. // }
  2280. // break;
  2281. // default:
  2282. // messages.TryGetValue(msg, out int value);
  2283. // messages[msg] = value + 1;
  2284. // break;
  2285. // }
  2286. // return IntPtr.Zero;
  2287. //}
  2288. private void RecordScreenButton_Click(object sender, RoutedEventArgs e)
  2289. {
  2290. ToggleRecording();
  2291. }
  2292. private bool ToggleRecording()
  2293. {
  2294. if (!Security.IsAllowed<CanRecordScreen>())
  2295. return true;
  2296. if (_recorder is null)
  2297. {
  2298. var windowInteropHelper = new WindowInteropHelper(this);
  2299. var screen = Screen.FromHandle(windowInteropHelper.Handle);
  2300. _screenleft = screen.WorkingArea.Left;
  2301. _screentop = screen.WorkingArea.Top;
  2302. _screenwidth = screen.WorkingArea.Width;
  2303. _screenheight = screen.WorkingArea.Height;
  2304. //VIDEO_WIDTH = _screenwidth;
  2305. //VIDEO_HEIGHT = _screenheight;
  2306. //SetupJPEGEncoder();
  2307. messages.Clear();
  2308. _bitmaps.Clear();
  2309. ConnectToRecordNotes();
  2310. StartAudio();
  2311. _recorder = new DispatcherTimer();
  2312. _recorder.Tick += (timer, args) => { TakeScreenShot(); };
  2313. _recorder.Interval = TimeSpan.FromMilliseconds(1000 / FRAMES_PER_SECOND);
  2314. _recorder.Start();
  2315. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsBitmapImage();
  2316. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2317. RecordingNotesButton.Visibility = Visibility.Visible;
  2318. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2319. AudioRecordingButton.Visibility = Visibility.Visible;
  2320. }
  2321. else
  2322. {
  2323. using (new WaitCursor())
  2324. {
  2325. StopRecording();
  2326. _recorder.Stop();
  2327. _recorder = null;
  2328. DisconnectRecorderNotes();
  2329. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  2330. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2331. RecordingNotesButton.Visibility = Visibility.Hidden;
  2332. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2333. AudioRecordingButton.Visibility = Visibility.Hidden;
  2334. var filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos),
  2335. string.Format("PRS Screen Recording {0:yyyy-MM-dd hh-mm-ss-ff}.avi", DateTime.Now));
  2336. ProcessScreenShots(filename);
  2337. }
  2338. }
  2339. return true;
  2340. }
  2341. private void StopRecording()
  2342. {
  2343. try
  2344. {
  2345. _audio?.StopRecording();
  2346. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2347. }
  2348. catch (Exception e)
  2349. {
  2350. Logger.Send(LogType.Error, "", string.Format("Unable to stop Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2351. }
  2352. }
  2353. private void StartAudio()
  2354. {
  2355. _audioMuted = true;
  2356. _audioStream = new MemoryStream();
  2357. _audio = new WaveIn
  2358. {
  2359. DeviceNumber = 0,
  2360. WaveFormat = new WaveFormat(44100, 16, 2)
  2361. };
  2362. _audio.DataAvailable += (o, e) =>
  2363. {
  2364. var buf = _audioMuted ? new byte[e.BytesRecorded] : e.Buffer;
  2365. _audioStream.Write(buf, 0, e.BytesRecorded);
  2366. };
  2367. try
  2368. {
  2369. _audio.StartRecording();
  2370. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2371. }
  2372. catch (Exception e)
  2373. {
  2374. Logger.Send(LogType.Error, "", string.Format("Unable to start Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2375. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2376. }
  2377. }
  2378. private bool ToggleRecordingAudio()
  2379. {
  2380. if (!Security.IsAllowed<CanRecordScreen>())
  2381. return true;
  2382. if (_recorder != null)
  2383. {
  2384. _audioMuted = !_audioMuted;
  2385. AudioRecordingStatus.Source = _audioMuted
  2386. ? PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage()
  2387. : PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2388. }
  2389. return true;
  2390. }
  2391. private void DisconnectRecorderNotes()
  2392. {
  2393. if (_client != null)
  2394. {
  2395. _client.WriteAsync("QUIT");
  2396. _client.StopAsync();
  2397. _client = null;
  2398. }
  2399. }
  2400. private void ConnectToRecordNotes()
  2401. {
  2402. var filename = Debugger.IsAttached
  2403. ? "c:\\development\\comal\\prsrecordingnotes\\bin\\debug\\prsrecordingnotes.exe"
  2404. : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "recordingnotes", "prsrecordingnotes.exe");
  2405. Logger.Send(LogType.Information, "", "Recording Notes: " + filename);
  2406. _recordingnotes = Process.Start(filename);
  2407. //PipeSecurity sec = new System.IO.Pipes.PipeSecurity();
  2408. //sec.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));
  2409. _client = new PipeServer<string>("PRSScreenRecorder", formatter:new BinaryFormatter()); //, sec);
  2410. _client.ClientConnected += (o, args) => args.Connection.WriteAsync("Connected to PRSScreenRecorder");
  2411. _client.MessageReceived += (o, args) =>
  2412. {
  2413. if (string.Equals(args.Message, "RESUME"))
  2414. Dispatcher.Invoke(() =>
  2415. {
  2416. _audio?.StartRecording();
  2417. totalpauses += DateTime.Now - pausestarted;
  2418. _recorder?.Start();
  2419. Activate();
  2420. Focus();
  2421. });
  2422. };
  2423. _client.StartAsync();
  2424. }
  2425. private bool ShowRecordingNotes()
  2426. {
  2427. if (_recorder != null)
  2428. {
  2429. _audio?.StopRecording();
  2430. _recorder.Stop();
  2431. pausestarted = DateTime.Now;
  2432. _client?.WriteAsync("EDIT");
  2433. //_subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2434. }
  2435. return true;
  2436. }
  2437. private void TakeScreenShot()
  2438. {
  2439. using (var bmp = new ScreenCapture().CaptureScreen(_screenleft, _screentop, _screenwidth, _screenheight))
  2440. {
  2441. var cursor = PointToScreen(Mouse.GetPosition(this));
  2442. using (var g = Graphics.FromImage(bmp))
  2443. {
  2444. var brush = new SolidBrush(System.Drawing.Color.FromArgb(128, 255, 255, 0));
  2445. g.FillEllipse(brush, new RectangleF((float)cursor.X - 25F, (float)cursor.Y - 25F, 50F, 50F));
  2446. var pen = new Pen(System.Drawing.Color.Black, 0.75F);
  2447. g.DrawLine(pen, (float)cursor.X - 10F, (float)cursor.Y, (float)cursor.X + 10F, (float)cursor.Y);
  2448. g.DrawLine(pen, (float)cursor.X, (float)cursor.Y - 10F, (float)cursor.X, (float)cursor.Y + 10F);
  2449. }
  2450. var key = DateTime.Now - totalpauses;
  2451. using (var reduced = ReduceBitmap(bmp, VIDEO_WIDTH, VIDEO_HEIGHT))
  2452. {
  2453. var ms = new MemoryStream();
  2454. reduced.Save(ms, ImageFormat.Png);
  2455. ms.Position = 0;
  2456. _bitmaps[key] = ms;
  2457. }
  2458. }
  2459. }
  2460. public Bitmap ReduceBitmap(Bitmap original, int reducedWidth, int reducedHeight)
  2461. {
  2462. var reduced = new Bitmap(reducedWidth, reducedHeight);
  2463. using (var dc = Graphics.FromImage(reduced))
  2464. {
  2465. // Figure out the ratio
  2466. var ratioX = (double)reducedWidth / original.Width;
  2467. var ratioY = (double)reducedHeight / original.Height;
  2468. // use whichever multiplier is smaller
  2469. var ratio = ratioX < ratioY ? ratioX : ratioY;
  2470. // now we can get the new height and width
  2471. var newHeight = Convert.ToInt32(original.Height * ratio);
  2472. var newWidth = Convert.ToInt32(original.Width * ratio);
  2473. // Now calculate the X,Y position of the upper-left corner
  2474. // (one of these will always be zero)
  2475. var posX = Convert.ToInt32((reducedWidth - original.Width * ratio) / 2);
  2476. var posY = Convert.ToInt32((reducedHeight - original.Height * ratio) / 2);
  2477. dc.InterpolationMode = InterpolationMode.HighQualityBicubic;
  2478. dc.Clear(System.Drawing.Color.Black); // white padding
  2479. //dc.DrawImage(original, posX, posY, newWidth, newHeight);
  2480. dc.DrawImage(original, new Rectangle(posX, posY, newWidth, newHeight), new Rectangle(0, 0, original.Width, original.Height),
  2481. GraphicsUnit.Pixel);
  2482. }
  2483. return reduced;
  2484. }
  2485. public static byte[] BitmapToByteArray(Bitmap bitmap, int width, int height)
  2486. {
  2487. // and buffer of appropriate size for storing its bits
  2488. var buffer = new byte[width * height * 4];
  2489. var pixelFormat = PixelFormat.Format32bppRgb;
  2490. // Now copy bits from bitmap to buffer
  2491. var bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);
  2492. //Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2493. Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2494. bitmap.UnlockBits(bits);
  2495. return buffer;
  2496. }
  2497. private void ProcessScreenShots(string filename)
  2498. {
  2499. if (!_bitmaps.Any() || _audioStream is null)
  2500. return;
  2501. Progress.Show("Saving Video");
  2502. var framRate = 10;
  2503. using (var writer = new AviWriter(filename))
  2504. {
  2505. writer.FramesPerSecond = framRate;
  2506. writer.EmitIndex1 = true;
  2507. _audioStream.Position = 0;
  2508. var audio = writer.AddAudioStream(2);
  2509. //audio.WriteBlock(_audioStream.GetBuffer(), 0, (int)_audioStream.Length);
  2510. //File.WriteAllBytes(Path.ChangeExtension(filename, "wav"), _audioStream.GetBuffer());
  2511. var audioByteRate = audio.BitsPerSample / 8 * audio.ChannelCount * audio.SamplesPerSecond;
  2512. var audioBlockSize = (int)(audioByteRate / writer.FramesPerSecond);
  2513. var audioBuffer = new byte[audioBlockSize];
  2514. _audioStream.Position = 0;
  2515. var encoder = new MJpegWpfVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT, 50);
  2516. var stream = writer.AddEncodingVideoStream(encoder, true, VIDEO_WIDTH, VIDEO_HEIGHT);
  2517. //var encoder = new SharpAvi.Codecs.UncompressedVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT);
  2518. //var stream = writer.AddEncodingVideoStream(encoder,true,VIDEO_WIDTH, VIDEO_HEIGHT);
  2519. //stream.Codec = CodecIds.Uncompressed;
  2520. //stream.BitsPerPixel = BitsPerPixel.Bpp16;
  2521. IEnumerable<DateTime> keys = _bitmaps.Keys.OrderBy(x => x);
  2522. var start = keys.First();
  2523. var end = keys.Last();
  2524. for (var cur = start; cur <= end; cur = cur + TimeSpan.FromMilliseconds(100))
  2525. {
  2526. Progress.SetMessage(string.Format("Processing ({0:F2} complete)",
  2527. (cur - start).TotalSeconds * 100.0F / (end - start).TotalSeconds));
  2528. var key = keys.LastOrDefault(x => x <= cur);
  2529. if (_bitmaps.ContainsKey(key))
  2530. {
  2531. var frame = (Image.FromStream(_bitmaps[key]) as Bitmap)!;
  2532. //frame.RotateFlip(RotateFlipType.RotateNoneFlipY);
  2533. var buf = BitmapToByteArray(frame, stream.Width, stream.Height);
  2534. stream.WriteFrame(true, buf, 0, buf.Length);
  2535. if (_audioStream.Position < _audioStream.Length)
  2536. {
  2537. var bytes = _audioStream.Read(audioBuffer, 0, audioBlockSize);
  2538. audio.WriteBlock(audioBuffer, 0, bytes);
  2539. }
  2540. }
  2541. }
  2542. writer.Close();
  2543. //foreach (var key in _bitmaps.Keys)
  2544. // File.Delete(_bitmaps[key]);
  2545. }
  2546. Progress.SetMessage("Transcoding");
  2547. //var inputFile = new MediaFile { Filename = filename };
  2548. //var outputFile = new MediaFile { Filename = Path.ChangeExtension(filename, "mp4") };
  2549. //using (var engine = new Engine())
  2550. //{
  2551. // //engine.ConvertProgressEvent += ConvertProgressEvent;
  2552. // engine.Convert(inputFile, outputFile);
  2553. //}
  2554. Progress.Close();
  2555. var dirName = Path.GetDirectoryName(filename);
  2556. if (dirName is not null)
  2557. {
  2558. var startInfo = new ProcessStartInfo(dirName);
  2559. startInfo.Verb = "open";
  2560. startInfo.UseShellExecute = true;
  2561. Process.Start(startInfo);
  2562. //MessageBox.Show("Recording Saved");
  2563. }
  2564. }
  2565. private void VideoRecordingButton_Click(object sender, RoutedEventArgs e)
  2566. {
  2567. ToggleRecording();
  2568. }
  2569. private void AudioRecordingButton_Click(object sender, RoutedEventArgs e)
  2570. {
  2571. ToggleRecordingAudio();
  2572. }
  2573. private void RecordingNotesButton_Click(object sender, RoutedEventArgs e)
  2574. {
  2575. ShowRecordingNotes();
  2576. }
  2577. #endregion
  2578. public static void ActivateWindow(Window window)
  2579. {
  2580. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2581. var threadId1 = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
  2582. var threadId2 = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
  2583. if (threadId1 != threadId2)
  2584. {
  2585. AttachThreadInput(threadId1, threadId2, true);
  2586. SetForegroundWindow(hwnd);
  2587. AttachThreadInput(threadId1, threadId2, false);
  2588. }
  2589. else
  2590. {
  2591. SetForegroundWindow(hwnd);
  2592. }
  2593. }
  2594. private static IntPtr GetForegroundWindow()
  2595. {
  2596. var active = GetActiveWindow();
  2597. var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => new WindowInteropHelper(x).Handle == active);
  2598. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2599. return hwnd;
  2600. }
  2601. [DllImport("user32.dll", SetLastError = true)]
  2602. private static extern IntPtr SetForegroundWindow(IntPtr hWnd);
  2603. [DllImport("user32.dll")]
  2604. private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
  2605. [DllImport("user32.dll")]
  2606. private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
  2607. [DllImport("user32.dll")]
  2608. private static extern IntPtr GetActiveWindow();
  2609. #region Check For Updates
  2610. private string GetUpdateLocation()
  2611. {
  2612. if (App.DatabaseSettings.DatabaseType == DatabaseType.Networked)
  2613. {
  2614. string url = "";
  2615. //var domain = App.DatabaseSettings.URL.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).Last();
  2616. //var port = App.DatabaseSettings.Port;
  2617. var domain = ClientFactory.Parameters?.FirstOrDefault()?.ToString() ?? "";
  2618. domain = domain.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? "";
  2619. if (!String.IsNullOrWhiteSpace(domain))
  2620. {
  2621. try
  2622. {
  2623. var client = new HttpClient { BaseAddress = new Uri($"https://{domain}") };
  2624. client.GetAsync("operations").Wait();
  2625. url = $"https://{domain}";
  2626. }
  2627. catch (Exception)
  2628. {
  2629. url = $"http://{domain}";
  2630. }
  2631. }
  2632. return url;
  2633. }
  2634. else
  2635. return Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update");
  2636. }
  2637. private string GetLatestVersion(string location)
  2638. {
  2639. return Client.Version();
  2640. }
  2641. private string GetReleaseNotes(string location)
  2642. {
  2643. return Client.ReleaseNotes();
  2644. }
  2645. private byte[]? GetInstaller(string location)
  2646. {
  2647. return Client.Installer();
  2648. }
  2649. private void CheckForUpdates()
  2650. {
  2651. Update.CheckForUpdates(
  2652. GetUpdateLocation, GetLatestVersion, GetReleaseNotes, GetInstaller, null, App.AutoUpdateSettings.Elevated, "PRSDesktopSetup.exe");
  2653. }
  2654. #endregion
  2655. #region Modules + Reports
  2656. public void ClearActions()
  2657. {
  2658. foreach (var module in CurrentModules)
  2659. {
  2660. if (module.Parent is Fluent.RibbonGroupBox bar)
  2661. bar.Items.Remove(module);
  2662. }
  2663. CurrentModules.Clear();
  2664. }
  2665. public void ClearReports()
  2666. {
  2667. if (CurrentTab is not null)
  2668. {
  2669. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  2670. if (ReportsBar is not null)
  2671. {
  2672. ReportsBar.Visibility = Security.IsAllowed<CanPrintReports>() ? Visibility.Visible : Visibility.Collapsed;
  2673. ReportsBar.Items.Clear();
  2674. }
  2675. }
  2676. }
  2677. public void CreateReport(PanelAction action)
  2678. {
  2679. if (CurrentTab is null)
  2680. return;
  2681. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  2682. if (ReportsBar is not null)
  2683. {
  2684. var button = new Fluent.Button
  2685. {
  2686. Header = action.Caption,
  2687. LargeIcon = action.Image.AsBitmapImage(),
  2688. MinWidth = 60
  2689. };
  2690. if (action.Menu is not null)
  2691. {
  2692. button.ContextMenu = action.Menu;
  2693. }
  2694. button.Click += (o, e) =>
  2695. {
  2696. action.Execute();
  2697. };
  2698. ReportsBar.Items.Add(button);
  2699. }
  2700. }
  2701. public void CreatePanelAction(PanelAction action)
  2702. {
  2703. if (CurrentTab is null)
  2704. return;
  2705. var Actions = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  2706. if (Actions is not null)
  2707. {
  2708. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  2709. {
  2710. var sep = new RibbonSeparator();
  2711. CurrentModules.Add(sep);
  2712. Actions.Items.Add(sep);
  2713. }
  2714. var button = new Fluent.Button
  2715. {
  2716. Header = action.Caption,
  2717. LargeIcon = action.Image?.AsBitmapImage(),
  2718. MinWidth = 60
  2719. };
  2720. button.Bind<PanelAction, String>(Fluent.Button.HeaderProperty, x=>x.Caption, null);
  2721. button.Bind<PanelAction, Bitmap>(Fluent.Button.LargeIconProperty, x => x.Image, new BitmapToBitmapImageConverter());
  2722. button.Bind<PanelAction, ContextMenu?>(Fluent.Button.ContextMenuProperty, x=>x.Menu);
  2723. button.Bind<PanelAction, bool>(Fluent.Button.IsEnabledProperty, x => x.IsEnabled);
  2724. button.Bind<PanelAction, Visibility>(Fluent.Button.VisibilityProperty, x => x.Visibility);
  2725. button.DataContext = action;
  2726. button.Click += (o, e) => action.Execute();
  2727. Actions.Items.Add(button);
  2728. CurrentModules.Add(button);
  2729. }
  2730. }
  2731. #endregion
  2732. #region Tracking Kanban
  2733. private void SelectTask_Click(object sender, RoutedEventArgs e)
  2734. {
  2735. ContextMenu menu = new ContextMenu();
  2736. MenuItem others = new MenuItem() { Header = "Other Tasks" };
  2737. using (new WaitCursor())
  2738. {
  2739. var kanbans = new Client<KanbanSubscriber>().Query(
  2740. new Filter<KanbanSubscriber>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
  2741. .And(x => x.Kanban.Completed).IsEqualTo(DateTime.MinValue)
  2742. .And(x => x.Kanban.Closed).IsEqualTo(DateTime.MinValue),
  2743. Columns.None<KanbanSubscriber>().Add(x => x.Kanban.ID)
  2744. .Add(x => x.Kanban.Number)
  2745. .Add(x => x.Kanban.Title)
  2746. .Add(x => x.Assignee),
  2747. new SortOrder<KanbanSubscriber>(x => x.Kanban.Number, SortDirection.Ascending)
  2748. );
  2749. foreach (var row in kanbans.Rows)
  2750. {
  2751. CreateTaskMenu(row.Get<KanbanSubscriber, bool>(c => c.Assignee) ? menu.Items : others.Items,
  2752. String.Format("{0} {1}",
  2753. row.Get<KanbanSubscriber, int>(c => c.Kanban.Number),
  2754. row.Get<KanbanSubscriber, String>(c => c.Kanban.Title)),
  2755. row.Get<KanbanSubscriber, Guid>(c => c.Kanban.ID)
  2756. );
  2757. }
  2758. menu.Items.Add(new Separator());
  2759. menu.Items.Add(others);
  2760. menu.Items.Add(new Separator());
  2761. CreateTaskMenu(menu.Items, "(No Task Selected)", Guid.Empty);
  2762. }
  2763. menu.IsOpen = true;
  2764. }
  2765. private Assignment? _kanbantrackingassignment = null;
  2766. private void SetTrackingKanban(Guid kanbanID, string header)
  2767. {
  2768. SelectedTaskName.Content = header;
  2769. var createNewAssignment = false;
  2770. if (_kanbantrackingassignment is not null)
  2771. {
  2772. if (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay)
  2773. {
  2774. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2775. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2776. }
  2777. // Update Existing Kanban
  2778. if (kanbanID == Guid.Empty)
  2779. _kanbantrackingassignment = null;
  2780. else if (_kanbantrackingassignment.Task.ID != kanbanID)
  2781. {
  2782. createNewAssignment = true;
  2783. }
  2784. }
  2785. else if (kanbanID != Guid.Empty)
  2786. {
  2787. createNewAssignment = true;
  2788. }
  2789. if (createNewAssignment)
  2790. {
  2791. _kanbantrackingassignment = new Assignment();
  2792. _kanbantrackingassignment.Task.ID = kanbanID;
  2793. _kanbantrackingassignment.EmployeeLink.ID = App.EmployeeID;
  2794. _kanbantrackingassignment.Title = header;
  2795. _kanbantrackingassignment.Date = DateTime.Today;
  2796. _kanbantrackingassignment.Actual.Start = DateTime.Now.TimeOfDay;
  2797. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay.Add(new TimeSpan(0, 2, 0));
  2798. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2799. }
  2800. }
  2801. private void ClearTrackingKanban()
  2802. => SetTrackingKanban(Guid.Empty, "(No Task Selected)");
  2803. private void CreateTaskMenu(ItemCollection items, String title, Guid id)
  2804. {
  2805. var item = new MenuItem()
  2806. {
  2807. Header = title,
  2808. Tag = id
  2809. };
  2810. item.Click += (o, args) =>
  2811. {
  2812. if (o is not MenuItem menu) return;
  2813. SetTrackingKanban((Guid)item.Tag, (menu.Header as string) ?? "");
  2814. };
  2815. items.Add(item);
  2816. }
  2817. #endregion
  2818. private void DockPanelBorder_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
  2819. {
  2820. if (sender is not Border border || !border.IsVisible)
  2821. return;
  2822. var dock = border.Child is IDockPanel panel ? panel : border.Child?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  2823. if (dock is null)
  2824. return;
  2825. dock.Refresh();
  2826. }
  2827. private void DockPanel_OnIsActiveChanged(object? sender, EventArgs e)
  2828. {
  2829. if (sender is not LayoutAnchorable layout)
  2830. return;
  2831. var content = layout.Content as DependencyObject;
  2832. var dock = content is IDockPanel panel ? panel : content?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  2833. if (dock is null)
  2834. return;
  2835. if (layout.IsActive && layout.IsVisible)
  2836. dock.Refresh();
  2837. }
  2838. private void _ribbon_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  2839. {
  2840. e.Handled = true;
  2841. }
  2842. #region Backstage Functions
  2843. private enum DatabaseConfigurationResult
  2844. {
  2845. RestartRequired,
  2846. RestartNotRequired,
  2847. Cancel
  2848. }
  2849. private DatabaseConfigurationResult ShowDatabaseConfiguration()
  2850. {
  2851. DatabaseConfigurationResult result;
  2852. var config = new DataBaseConfiguration();
  2853. if (config.ShowDialog() == true)
  2854. {
  2855. var newsettings = new LocalConfiguration<DatabaseSettings>(App.Profile).Load();
  2856. if (newsettings.RestartRequired(App.DatabaseSettings))
  2857. {
  2858. result = DatabaseConfigurationResult.RestartRequired;
  2859. }
  2860. else
  2861. {
  2862. result = DatabaseConfigurationResult.RestartNotRequired;
  2863. }
  2864. if ((newsettings.DatabaseType == DatabaseType.Standalone) && (newsettings.ColorScheme != App.DatabaseSettings.ColorScheme))
  2865. {
  2866. App.DatabaseSettings.ColorScheme = newsettings.ColorScheme;
  2867. ApplyColorScheme();
  2868. }
  2869. }
  2870. else
  2871. {
  2872. result = DatabaseConfigurationResult.Cancel;
  2873. }
  2874. return result;
  2875. }
  2876. private void DatabaseSettings_OnClick(object sender, RoutedEventArgs e)
  2877. {
  2878. switch (ShowDatabaseConfiguration())
  2879. {
  2880. case DatabaseConfigurationResult.RestartRequired:
  2881. MessageBox.Show("Please restart the application to apply these changes!");
  2882. break;
  2883. }
  2884. }
  2885. private void CompanyInformation_OnClick(object sender, RoutedEventArgs e)
  2886. {
  2887. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  2888. if (info == null)
  2889. info = new CompanyInformation();
  2890. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  2891. }
  2892. private void SecurityDefaultsButton_OnClick(object sender, RoutedEventArgs e)
  2893. {
  2894. var window = new GlobalTokenWindow();
  2895. window.ShowDialog();
  2896. Security.Reset();
  2897. }
  2898. private void SystemLogsButton_OnClick(object sender, RoutedEventArgs e)
  2899. {
  2900. var logfile = Path.Combine(CoreUtils.GetPath(), string.Format("{0:yyyy-MM-dd}.log", DateTime.Today));
  2901. if (File.Exists(logfile))
  2902. {
  2903. var startInfo = new ProcessStartInfo("notepad.exe", logfile);
  2904. startInfo.Verb = "open";
  2905. startInfo.UseShellExecute = true;
  2906. Process.Start(startInfo);
  2907. }
  2908. else
  2909. {
  2910. MessageBox.Show(logfile + " does not exist!");
  2911. }
  2912. }
  2913. private void DocumentTypeList_OnClick(object sender, RoutedEventArgs e)
  2914. {
  2915. var list = new MasterList(typeof(DocumentType));
  2916. list.ShowDialog();
  2917. }
  2918. private void EditDetailsButton_OnClick(object sender, RoutedEventArgs e)
  2919. {
  2920. var employee = new Client<Employee>().Query(
  2921. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid))
  2922. .Rows.FirstOrDefault()?.ToObject<Employee>();
  2923. var item = new MyDetailsConfiguration(employee);
  2924. item.User = ClientFactory.UserGuid;
  2925. var buttons = new DynamicEditorButtons();
  2926. buttons.Add("Change Password", null, item, (sender, item) =>
  2927. {
  2928. var details = (item as MyDetailsConfiguration)!;
  2929. var changePassword = new ChangePassword(details.User);
  2930. if (changePassword.ShowDialog() == true && changePassword.Password != null)
  2931. {
  2932. var newUser = new User();
  2933. newUser.ID = details.User;
  2934. ChangePassword.ChangeUserPassword(newUser, changePassword.Password);
  2935. new Client<User>().Save(newUser, "Changed Password");
  2936. MessageBox.Show("Password changed!");
  2937. }
  2938. });
  2939. var editor = new DynamicEditorForm(typeof(MyDetailsConfiguration), buttons: buttons);
  2940. if (employee == null)
  2941. {
  2942. editor.OnFormCustomiseEditor += (sender, items, column, editor) =>
  2943. {
  2944. editor.Editable = Editable.Disabled;
  2945. };
  2946. }
  2947. editor.Items = new BaseObject[] { item };
  2948. if (editor.ShowDialog() == true)
  2949. {
  2950. if (employee != null)
  2951. {
  2952. item.SaveTo(employee);
  2953. new Client<Employee>().Save(employee, "Edited by user");
  2954. }
  2955. }
  2956. }
  2957. private void LogoutButton_OnClick(object sender, RoutedEventArgs e)
  2958. {
  2959. Logout();
  2960. }
  2961. private void LoginButton_OnClick(object sender, RoutedEventArgs e)
  2962. {
  2963. if (DoLogin() == ValidationStatus.VALID)
  2964. AfterLogin(null);
  2965. }
  2966. private void ExitButton_OnClick(object sender, RoutedEventArgs e)
  2967. {
  2968. //_closingFromSystemMenu = true;
  2969. Close();
  2970. }
  2971. #endregion
  2972. }