MainWindow.xaml.cs 129 KB

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