MainWindow.xaml.cs 125 KB

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