MainWindow.xaml.cs 130 KB

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