MainWindow.xaml.cs 126 KB

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