MainWindow.xaml.cs 128 KB

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