MainWindow.xaml.cs 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458
  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 NAudio.Wave;
  39. using PRS.Shared;
  40. using InABox.WPF.Themes;
  41. using PRSDesktop.Configuration;
  42. using PRSDesktop.Forms;
  43. using PRSServer;
  44. using SharpAvi.Codecs;
  45. using SharpAvi.Output;
  46. using Syncfusion.Windows.Shared;
  47. using Syncfusion.Windows.Tools;
  48. using Syncfusion.Windows.Tools.Controls;
  49. using Activity = Comal.Classes.Activity;
  50. using Application = System.Windows.Application;
  51. using ButtonBase = System.Windows.Controls.Primitives.ButtonBase;
  52. using Color = System.Windows.Media.Color;
  53. using ColorConverter = System.Windows.Media.ColorConverter;
  54. using Control = System.Windows.Controls.Control;
  55. using Image = System.Drawing.Image;
  56. using KeyEventArgs = System.Windows.Input.KeyEventArgs;
  57. using MessageBox = System.Windows.MessageBox;
  58. using Pen = System.Drawing.Pen;
  59. using PixelFormat = System.Drawing.Imaging.PixelFormat;
  60. using Role = Comal.Classes.Role;
  61. using SortDirection = InABox.Core.SortDirection;
  62. using PRSDesktop.Components.Spreadsheet;
  63. using InABox.Wpf.Reports;
  64. using Comal.Classes.SecurityDescriptors;
  65. namespace PRSDesktop
  66. {
  67. /// <summary>
  68. /// Interaction logic for Main.xaml
  69. /// </summary>
  70. public partial class MainWindow : IPanelHost
  71. {
  72. //private const int WM_LBUTTONDOWN = 0x201;
  73. private static PipeServer<string>? _client;
  74. private IRpcClientTransport? _transport;
  75. private WaveIn? _audio;
  76. private bool _audioMuted;
  77. private MemoryStream? _audioStream;
  78. private readonly Dictionary<DateTime, Stream> _bitmaps = new();
  79. private Console? _console;
  80. private Dictionary<DateTime, Tuple<Rectangle, string>> _notes = new();
  81. //Dictionary<Type, IBasePanel> Panels = new Dictionary<Type, IBasePanel>();
  82. private DispatcherTimer? _recorder;
  83. private Process? _recordingnotes;
  84. private int _screenheight = 720;
  85. private int _screenleft;
  86. private int _screentop;
  87. private int _screenwidth = 1280;
  88. private readonly Dictionary<Guid, SecondaryWindow> _secondarywindows = new();
  89. private CoreTable? _timesheets;
  90. private DailyActivityHistory? ActivityHistory;
  91. private readonly List<Control> CurrentModules = new();
  92. private IBasePanel? CurrentPanel;
  93. private int CurrentPanel_Clicks;
  94. private int CurrentPanel_Keys;
  95. private string CurrentPanel_Label = "";
  96. private DateTime CurrentPanel_Ticks = DateTime.MinValue;
  97. private Fluent.RibbonTabItem? CurrentTab;
  98. private Fluent.Button? CurrentButton;
  99. private readonly int FRAMES_PER_SECOND = 10;
  100. private DatabaseType DatabaseType;
  101. private readonly Dictionary<int, int> messages = new();
  102. private readonly DispatcherTimer NotificationsWatchDog;
  103. private DateTime pausestarted = DateTime.MinValue;
  104. private readonly Scheduler scheduler = new() { Interval = new TimeSpan(0, 5, 0) };
  105. // We use a Guid for the StationID rather than an IP or Mac address
  106. // because we want true single-instance restriction. Using either of
  107. // the above allows for two instances on the once machine, and thus
  108. // double-counting in the Heartbeat() function
  109. private Login station = new() { StationID = Guid.NewGuid().ToString() };
  110. private TimeSpan totalpauses = new(0);
  111. private readonly int VIDEO_HEIGHT = 1080;
  112. private readonly int VIDEO_WIDTH = 1920;
  113. public MainWindow()
  114. {
  115. NotificationsWatchDog = new DispatcherTimer { IsEnabled = false };
  116. NotificationsWatchDog.Tick += Notifications_Tick;
  117. NotificationsWatchDog.Interval = new TimeSpan(0, 2, 0);
  118. ClientFactory.PushHandlers.AddHandler<Notification>(ReceiveNotification);
  119. ClientFactory.RegisterMailer(EmailType.IMAP, typeof(IMAPMailer));
  120. ClientFactory.RegisterMailer(EmailType.Exchange, typeof(ExchangeMailer));
  121. ClientFactory.OnLog += (type, userid, message, parameters) => Logger.Send(LogType.Information, ClientFactory.UserID, message, parameters);
  122. ClientFactory.OnRequestError += ClientFactory_OnRequestError;
  123. HotKeyManager.Initialize();
  124. HotKeyManager.RegisterHotKey(Key.F1, ShowHelp);
  125. HotKeyManager.RegisterHotKey(Key.F5, ToggleRecording);
  126. HotKeyManager.RegisterHotKey(Key.F6, ShowRecordingNotes);
  127. HotKeyManager.RegisterHotKey(Key.F4, ToggleRecordingAudio);
  128. var settings = App.DatabaseSettings;
  129. bool dbConnected;
  130. DatabaseType = settings.DatabaseType;
  131. switch (DatabaseType)
  132. {
  133. case DatabaseType.Standalone:
  134. ClientFactory.SetClientType(typeof(LocalClient<>), Platform.Wpf, CoreUtils.GetVersion());
  135. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  136. DbFactory.Logo = App.DatabaseSettings.Logo;
  137. dbConnected = true;
  138. break;
  139. case DatabaseType.Networked:
  140. if (App.DatabaseSettings.Protocol == SerializerProtocol.RPC)
  141. {
  142. //new RPC stuff (temporary disabled - for enabling when RPC is ready)
  143. _transport = new RpcClientSocketTransport(App.DatabaseSettings.URLs);
  144. _transport.OnClose += TransportConnectionLost;
  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. ThemeManager.BaseColor = (Color)ColorConverter.ConvertFromString(dbInfo.ColorScheme);
  193. if (dbInfo.Logo?.Any() == true)
  194. using (var ms = new MemoryStream(dbInfo.Logo))
  195. {
  196. Progress.DisplayImage = new Bitmap(ms).AsBitmapImage();
  197. }
  198. }
  199. catch
  200. {
  201. }
  202. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  203. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  204. SecondaryWindowStatus.Source = PRSDesktop.Resources.target.AsGrayScale().AsBitmapImage();
  205. ConsoleStatus.Source = PRSDesktop.Resources.view.AsGrayScale().AsBitmapImage();
  206. SelectTask.Source = PRSDesktop.Resources.uparrow.Invert().AsBitmapImage();
  207. Title = $"{(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  208. CheckForUpdates();
  209. Exception? startupException = null;
  210. ValidationStatus? loginStatus = null;
  211. Progress.ShowModal("Loading PRS", progress =>
  212. {
  213. DynamicGridUtils.PreviewReport = (t, m) => { ReportUtils.PreviewReport(t, m, false, Security.IsAllowed<CanDesignReports>()); };
  214. DynamicGridUtils.PrintMenu = (e, s, m, p) => { ReportUtils.PrintMenu(e, s, m, Security.IsAllowed<CanDesignReports>(), p); };
  215. ImportFactory.Register(typeof(ExcelImporter<>), "Excel File", "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm");
  216. ImportFactory.Register(typeof(CustomImporter<>), "Custom", "All Files (*.*)|*.*");
  217. FormUtils.Register();
  218. DigitalFormDocumentFactory.Init(
  219. new WpfDigitalFormDocumentHandler(
  220. b => Dispatcher.BeginInvoke(() =>
  221. {
  222. BackgroundUploadStatus.Visibility = b
  223. ? Visibility.Visible
  224. : Visibility.Hidden;
  225. }
  226. ),
  227. () => _transport?.IsConnected() ?? false
  228. )
  229. );
  230. DigitalFormDocumentFactory.Run();
  231. Logger.Send(LogType.Information, "", "Registering Classes");
  232. progress.Report("Registering Classes");
  233. var tasks = new List<Task>
  234. {
  235. Task.Run(() => CoreUtils.RegisterClasses(typeof(TaskGrid).Assembly)),
  236. Task.Run(() => CoreUtils.RegisterClasses()),
  237. Task.Run(() => ComalUtils.RegisterClasses()),
  238. Task.Run(() => PRSSharedUtils.RegisterClasses()),
  239. Task.Run(() => ReportUtils.RegisterClasses()),
  240. Task.Run(() => ConfigurationUtils.RegisterClasses()),
  241. Task.Run(() => DynamicGridUtils.RegisterClasses()),
  242. Task.Run(() =>
  243. {
  244. ScriptDocument.DefaultAssemblies.AddRange(
  245. Assembly.Load("RoslynPad.Roslyn.Windows"),
  246. Assembly.Load("RoslynPad.Editor.Windows"),
  247. typeof(Control).Assembly,
  248. typeof(MessageBox).Assembly,
  249. typeof(SolidColorBrush).Assembly
  250. );
  251. ScriptDocument.Initialize();
  252. }),
  253. Task.Run(() => DatabaseUpdateScripts.RegisterScripts())
  254. };
  255. Task.WaitAll(tasks.ToArray());
  256. progress.Report("Configuring Application");
  257. RegisterModules(progress);
  258. if (DatabaseType == DatabaseType.Standalone)
  259. {
  260. progress.Report("Starting local database...");
  261. try
  262. {
  263. StartLocalDatabase(progress);
  264. }
  265. catch (Exception err)
  266. {
  267. startupException = new Exception(
  268. string.Format(
  269. "Unable to open database ({0})\n\n{1}\n\n{2}",
  270. App.DatabaseSettings.FileName,
  271. err.Message,
  272. err.StackTrace
  273. )
  274. );
  275. }
  276. }
  277. });
  278. if (startupException != null)
  279. MessageBox.Show(startupException.Message);
  280. if (DoLogin(App.DatabaseSettings.Autologin) == ValidationStatus.VALID)
  281. {
  282. AfterLogin();
  283. }
  284. ProfileName.Content = App.Profile;
  285. URL.Content = GetDatabaseConnectionDescription();
  286. Progress.ShowModal("Starting Up", progress =>
  287. {
  288. if (loginStatus == ValidationStatus.VALID && DatabaseType == DatabaseType.Standalone)
  289. {
  290. progress.Report("Starting Scheduler");
  291. scheduler.Start();
  292. }
  293. });
  294. }
  295. #region Connection Management
  296. private string GetDatabaseConnectionDescription()
  297. {
  298. return DatabaseType switch
  299. {
  300. #if RPC
  301. DatabaseType.Networked => (ClientFactory.Parameters?.FirstOrDefault() as RpcClientSocketTransport)?.Host,
  302. #else
  303. DatabaseType.Networked => ClientFactory.Parameters?.FirstOrDefault() as string,
  304. #endif
  305. DatabaseType.Standalone => App.DatabaseSettings?.FileName,
  306. DatabaseType.Local => App.DatabaseSettings?.LocalServerName,
  307. _ => ""
  308. } ?? "";
  309. }
  310. /// <summary>
  311. /// Reconnect to the server.
  312. /// </summary>
  313. /// <returns><see langword="true"/> if connection was successful.</returns>
  314. private bool Reconnect()
  315. {
  316. if (_transport != null)
  317. {
  318. return _transport.Connect();
  319. }
  320. Logger.Send(LogType.Error, ClientFactory.UserID, "Trying to reconnect without a transport set.");
  321. return true; // Returning true so we don't get stuck in infinite loops in exceptional circumstances.
  322. }
  323. private enum ConnectionFailedResult
  324. {
  325. Quit,
  326. Restart,
  327. Ok
  328. }
  329. /// <summary>
  330. /// To be called when initial connection to the server has failed; asks the user if they want to retry,
  331. /// change the database settings, or simply quit PRS.
  332. /// </summary>
  333. /// <returns>The action to take next.</returns>
  334. /// <exception cref="Exception"></exception>
  335. private ConnectionFailedResult DoConnectionFailed()
  336. {
  337. bool connected = false;
  338. while (!connected)
  339. {
  340. var connectionFailedWindow = new ConnectionFailed();
  341. connectionFailedWindow.ShowDialog();
  342. var reconnect = false;
  343. switch (connectionFailedWindow.Result)
  344. {
  345. case ConnectionFailedWindowResult.OpenDatabaseConfiguration:
  346. var result = ShowDatabaseConfiguration();
  347. switch (result)
  348. {
  349. case DatabaseConfigurationResult.RestartRequired:
  350. var shouldRestart = MessageBox.Show(
  351. "A restart is required to apply these changes. Do you wish to restart now?",
  352. "Restart?",
  353. MessageBoxButton.YesNo);
  354. if (shouldRestart == MessageBoxResult.Yes)
  355. {
  356. return ConnectionFailedResult.Restart;
  357. }
  358. else
  359. {
  360. reconnect = true;
  361. }
  362. break;
  363. case DatabaseConfigurationResult.RestartNotRequired:
  364. reconnect = true;
  365. break;
  366. case DatabaseConfigurationResult.Cancel:
  367. reconnect = true;
  368. break;
  369. default:
  370. throw new Exception($"Invalid enum result {result}");
  371. }
  372. break;
  373. case ConnectionFailedWindowResult.RetryConnection:
  374. reconnect = true;
  375. break;
  376. case ConnectionFailedWindowResult.Quit:
  377. return ConnectionFailedResult.Quit;
  378. default:
  379. throw new Exception($"Invalid enum result {connectionFailedWindow.Result}");
  380. }
  381. if (!reconnect)
  382. {
  383. return ConnectionFailedResult.Quit;
  384. }
  385. connected = Reconnect();
  386. }
  387. return ConnectionFailedResult.Ok;
  388. }
  389. private void TransportConnectionLost(IRpcTransport transport, RpcTransportCloseArgs e)
  390. {
  391. if ((transport is IRpcClientTransport client))
  392. {
  393. Dispatcher.Invoke(() =>
  394. {
  395. var success = Progress.ShowModal("Reconnecting", "Exit PRS", (progress, ct) =>
  396. {
  397. try
  398. {
  399. DateTime lost = DateTime.Now;
  400. while (!client.IsConnected() && !ct.IsCancellationRequested)
  401. {
  402. progress.Report($"Connection lost - ({(DateTime.Now - lost):hh\\:mm})");
  403. try
  404. {
  405. Logger.Send(LogType.Error, ClientFactory.UserID, "Reconnecting - ({0:hh\\:mm})", DateTime.Now - lost);
  406. client.Connect(ct);
  407. if (client.IsConnected())
  408. break;
  409. }
  410. catch (System.Exception e1)
  411. {
  412. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnect Failed: {e1.Message}");
  413. }
  414. }
  415. if (client.IsConnected())
  416. {
  417. ClientFactory.Validate(ClientFactory.SessionID);
  418. }
  419. }
  420. catch (Exception e)
  421. {
  422. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnect Failed: {e.Message}");
  423. }
  424. });
  425. if (!success)
  426. {
  427. Close();
  428. }
  429. });
  430. }
  431. }
  432. #endregion
  433. private bool _loggingOut = false;
  434. private void ClientFactory_OnRequestError(RequestException e)
  435. {
  436. if (e.Status == StatusCode.Unauthenticated)
  437. {
  438. switch (e.Method)
  439. {
  440. case RequestMethod.Query:
  441. case RequestMethod.Save:
  442. case RequestMethod.Delete:
  443. case RequestMethod.MultiQuery:
  444. case RequestMethod.MultiSave:
  445. case RequestMethod.MultiDelete:
  446. if (!_loggingOut)
  447. {
  448. Dispatcher.InvokeAsync(() =>
  449. {
  450. _loggingOut = true;
  451. try
  452. {
  453. Logout(null, true);
  454. }
  455. finally
  456. {
  457. _loggingOut = false;
  458. }
  459. });
  460. }
  461. break;
  462. default:
  463. break;
  464. }
  465. }
  466. }
  467. private void ApplyColorScheme()
  468. {
  469. Color baseColor;
  470. try
  471. {
  472. baseColor = (Color)ColorConverter.ConvertFromString(App.DatabaseSettings.ColorScheme);
  473. }
  474. catch
  475. {
  476. baseColor = Colors.CornflowerBlue;
  477. }
  478. ThemeManager.BaseColor = baseColor;
  479. BaseDynamicGrid.SelectionBackground = ThemeManager.SelectionBackgroundBrush;
  480. BaseDynamicGrid.SelectionForeground = ThemeManager.SelectionForegroundBrush;
  481. BaseDynamicGrid.FilterBackground = ThemeManager.FilterBackgroundBrush;
  482. //_ribbon.Background = new SolidColorBrush(Colors.White);
  483. //_ribbon.BackStageColor = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  484. ////_ribbon.BackStage.Background = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  485. ////_ribbon.BackStage.Foreground = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Foreground);
  486. UpdateRibbonColors();
  487. CurrentPanel?.Refresh();
  488. }
  489. #region Configuration
  490. /*
  491. protected override void OnSourceInitialized(EventArgs e)
  492. {
  493. base.OnSourceInitialized(e);
  494. var source = PresentationSource.FromVisual(this) as HwndSource;
  495. source?.AddHook(WndProc);
  496. }
  497. private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  498. {
  499. var message = (App.Message)msg;
  500. switch (message)
  501. {
  502. case App.Message.Maximise:
  503. WindowState = WindowState.Maximized;
  504. break;
  505. }
  506. return IntPtr.Zero;
  507. }*/
  508. private interface ISetupActionItem
  509. {
  510. }
  511. private class SetupActionItem : ISetupActionItem
  512. {
  513. public string Name { get; set; }
  514. public Action Action { get; set; }
  515. public Bitmap? Image { get; set; }
  516. public Type? SecurityToken { get; set; }
  517. public Func<bool>? CanView { get; set; }
  518. public SetupActionItem(string name, Action action, Bitmap? image)
  519. {
  520. Name = name;
  521. Action = action;
  522. Image = image;
  523. }
  524. public bool IsVisible() => (SecurityToken == null || Security.IsAllowed(SecurityToken)) && (CanView == null || CanView());
  525. public SetupActionItem SetSecurityToken<T>() where T : ISecurityDescriptor, new()
  526. {
  527. SecurityToken = typeof(T);
  528. return this;
  529. }
  530. public SetupActionItem SetCanView<T>() where T : Entity
  531. {
  532. return SetSecurityToken<AutoSecurityDescriptor<T, CanView<T>>>();
  533. }
  534. }
  535. private class SetupSeparator : ISetupActionItem { }
  536. private Dictionary<Fluent.RibbonTabItem, List<ISetupActionItem>> SetupActions = new();
  537. private List<ISetupActionItem> GetSetupActionList(Fluent.RibbonTabItem tab)
  538. {
  539. if (!SetupActions.TryGetValue(tab, out var list))
  540. {
  541. list = new();
  542. SetupActions[tab] = list;
  543. }
  544. return list;
  545. }
  546. private SetupActionItem AddSetupAction(List<ISetupActionItem> list, string header, Action action, Bitmap? image)
  547. {
  548. var item = new SetupActionItem(header, action, image);
  549. list.Add(item);
  550. return item;
  551. }
  552. private SetupActionItem AddSetupAction(Fluent.RibbonTabItem tab, string header, Action action, Bitmap? image)
  553. => AddSetupAction(GetSetupActionList(tab), header, action, image);
  554. private SetupActionItem? AddSetupAction(Fluent.RibbonTabItem tab, string header, Action action, Bitmap? image, bool canView)
  555. {
  556. if (!canView)
  557. return null;
  558. return AddSetupAction(tab, header, action, image);
  559. }
  560. private SetupSeparator AddSetupSeparator(List<ISetupActionItem> list)
  561. {
  562. var separator = new SetupSeparator();
  563. list.Add(separator);
  564. return separator;
  565. }
  566. private SetupSeparator AddSetupSeparator(Fluent.RibbonTabItem tab)
  567. => AddSetupSeparator(GetSetupActionList(tab));
  568. private void AddSetupModulesAndReports(Fluent.RibbonTabItem tab)
  569. {
  570. AddSetupSeparator(tab);
  571. AddSetupAction(tab, "Custom Modules", ManageModules, PRSDesktop.Resources.script).SetSecurityToken<CanCustomiseModules>();
  572. AddSetupAction(tab, "Reports", ManageReports, PRSDesktop.Resources.printer).SetSecurityToken<CanDesignReports>();
  573. AddSetupAction(tab, "Email Templates", ManageEmailTemplates, PRSDesktop.Resources.email).SetSecurityToken<CanDesignReports>();
  574. }
  575. private void ConfigureMainScreen()
  576. {
  577. SetupScreen();
  578. var bMaps = Security.CanView<Equipment>()
  579. || Security.CanView<Job>()
  580. || Security.CanView<TimeSheet>()
  581. || Security.CanView<GPSTracker>();
  582. Progress.ShowModal(
  583. new ProgressSection("Configuring Main Screen", SetupMainScreen),
  584. new ProgressSection("Configuring Quotes Screen", () => SetupQuotesTab(bMaps)),
  585. new ProgressSection("Configuring Projects", () => SetupProjectsTab(bMaps)),
  586. new ProgressSection("Configuring Manufacturing", () => SetupManufacturingTab(bMaps)),
  587. new ProgressSection("Configuring Logistics", () => SetupLogisticsTab(bMaps)),
  588. new ProgressSection("Configuring Products", () => SetupProductsTab(bMaps)),
  589. new ProgressSection("Configuring Human Resources", () => SetupHumanResourcesTab(bMaps)),
  590. new ProgressSection("Configuring Accounts", () => SetupAccountsTab(bMaps)),
  591. new ProgressSection("Configuring Equipment", () => SetupEquipmentTab(bMaps)),
  592. new ProgressSection("Configuring Dashboards", () => SetupDashboardsTab(bMaps)),
  593. new ProgressSection("Configuring System Modules", SetupSystemModules)
  594. );
  595. }
  596. private void SetupScreen()
  597. {
  598. var button = _ribbon.FindVisualChildren<Fluent.DropDownButton>().FirstOrDefault();
  599. if (button != null)
  600. button.Visibility = Visibility.Collapsed;
  601. if (ClientFactory.UserGuid == Guid.Empty)
  602. _ribbonRow.Height = new GridLength(30, GridUnitType.Pixel);
  603. else
  604. _ribbonRow.Height = new GridLength(1, GridUnitType.Auto);
  605. SetupActions.Clear();
  606. }
  607. private void SetupMainScreen()
  608. {
  609. ReportUtils.ExportDefinitions.Clear();
  610. ReportUtils.ExportDefinitions.AddRange(AddTemplateDefinitions());
  611. //DockManager.SidePanelSize = OutstandingDailyReports(false) ? 0.00F : 30.00F;
  612. // Notifications Area
  613. SetVisibility(SendNotification, Security.CanView<Notification>());
  614. SetVisibility(Notifications, Security.CanView<Notification>());
  615. SetVisibility(TaskTracking, Security.IsAllowed<CanTrackTasksInDailyReport>());
  616. UserID.Content = ClientFactory.UserID;
  617. if (ClientFactory.PasswordExpiration != DateTime.MinValue)
  618. {
  619. var timeUntilExpiration = ClientFactory.PasswordExpiration - DateTime.Now;
  620. if (timeUntilExpiration.Days < 14)
  621. {
  622. PasswordExpiryNotice.Content = $"Password will expire in {timeUntilExpiration.Days} days!";
  623. PasswordExpiryNotice.Visibility = Visibility.Visible;
  624. }
  625. else
  626. {
  627. PasswordExpiryNotice.Visibility = Visibility.Collapsed;
  628. }
  629. }
  630. }
  631. private void SetupSystemModules()
  632. {
  633. SetVisibility(CompanyInformation, Security.CanView<CompanyInformation>());
  634. SetVisibleIfAny(BackstageSeparator0, CompanyInformation);
  635. SetVisibility(SecurityDefaultsButton,
  636. ClientFactory.IsSupported<GlobalSecurityToken>() && Security.IsAllowed<CanCustomiseSecurityDefaults>());
  637. SetVisibleIfAny(BackstageSeparator1, SecurityDefaultsButton);
  638. BackstageSeparator1a.Visibility = Visibility.Visible;
  639. SystemLogsButton.Visibility = Visibility.Visible;
  640. SetVisibility(DocumentTypeList, ClientFactory.IsSupported<DocumentType>() && Security.IsAllowed<CanViewDocumentTypes>());
  641. SetVisibility(DocumentList, ClientFactory.IsSupported<Document>() && Security.IsAllowed<CanViewDocumentList>());
  642. SetVisibility(QAFormSetupButton,
  643. ClientFactory.IsSupported<DigitalForm>() && Security.IsAllowed<CanAdministerDigitalFormsLibrary>());
  644. SetVisibleIfAny(BackstageSeparator2, DocumentTypeList, DocumentList, QAFormSetupButton);
  645. SetVisibility(VideoRecordingButton, Security.IsAllowed<CanRecordScreen>());
  646. LogoutButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  647. LoginButton.Visibility = ClientFactory.UserGuid != Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  648. EditDetailsButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  649. SetupDock<CanViewContactsDock>(ContactDock, Contacts);
  650. SetupDock<CanViewJobDock>(JobDock, Jobs);
  651. SetupDock<CanViewConsignmentDock>(ConsignmentDock, Consignments);
  652. SetupDock<CanViewDeliveryDock>(DeliveryDock, Deliveries);
  653. SetupDock<CanViewProductDock>(ProductLookupDock, ProductLookup);
  654. SetupDock<CanViewDigitalFormsDock>(DigitalFormsDock, DigitalForms);
  655. _ribbon.InvalidateArrange();
  656. }
  657. private void SetupDashboardsTab(bool bMaps)
  658. {
  659. if (!Security.IsAllowed<ViewDesktopDashboardsTab>())
  660. return;
  661. SetVisibility(DashboardsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  662. SetVisibility(DashboardMessagesButton, Security.CanView<Notification>());
  663. SetVisibility(DashboardsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  664. SetVisibility(DashboardsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  665. SetVisibility(DashboardsMapButton, bMaps);
  666. SetVisibility(DashboardsDailyReportButton,
  667. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  668. SetVisibility(FactoryProductivityButton,
  669. ClientFactory.IsSupported<ManufacturingHistory>()
  670. && Security.IsAllowed<CanViewFactoryKPIs>()
  671. && Security.IsAllowed<ViewDesktopFactoryKPIsDashboard>());
  672. SetVisibility(TemplateAnalysisButton,
  673. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>()
  674. && Security.IsAllowed<CanViewTemplateAnalysis>()
  675. && Security.IsAllowed<ViewDesktopTemplateAnalysisDashboard>());
  676. SetVisibility(FactoryAnalysisButton,
  677. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>()
  678. && Security.IsAllowed<CanViewFactoryAnalysis>()
  679. && Security.IsAllowed<ViewDesktopFactoryAnalysisDashboard>());
  680. SetVisibility(DatabaseActivityButton,
  681. ClientFactory.IsSupported<UserTracking>()
  682. && Security.IsAllowed<CanViewDatabaseActivity>()
  683. && Security.IsAllowed<ViewDesktopDatabaseActivityDashboard>());
  684. SetVisibility(UserActivityButton, ClientFactory.IsSupported<ModuleTracking>()
  685. && Security.IsAllowed<CanViewUserActivity>()
  686. && Security.IsAllowed<ViewDesktopUserActivityDashboard>());
  687. SetVisibility(DigitalFormsButton, Security.IsAllowed<CanViewDigitalFormsDashbaord>() && Security.IsAllowed<ViewDesktopDigitalFormsDashboard>());
  688. SetVisibility(QuickStatusButton, Security.IsAllowed<CanViewQuickStatus>() && Security.IsAllowed<ViewDesktopQuickStatusDashboard>());
  689. SetVisibleIfEither(DashboardsTaskSeparator,
  690. new FrameworkElement[]
  691. {
  692. DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton, DashboardsAttendanceButton,
  693. DashboardsMapButton,
  694. DashboardsDailyReportButton
  695. },
  696. new FrameworkElement[]
  697. {
  698. FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton,
  699. DigitalFormsButton, QuickStatusButton
  700. });
  701. SetVisibleIfAny(DashboardsActions, DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton,
  702. DashboardsAttendanceButton, DashboardsDailyReportButton, FactoryProductivityButton, TemplateAnalysisButton,
  703. FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton, DigitalFormsButton, QuickStatusButton);
  704. //DashboardsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  705. //DashboardsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  706. AddSetupModulesAndReports(DashboardsTab);
  707. SetVisibleIfAny(DashboardsTab, FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton,
  708. DatabaseActivityButton,
  709. UserActivityButton, DigitalFormsButton, QuickStatusButton);
  710. }
  711. private void SetupEquipmentTab(bool bMaps)
  712. {
  713. if (!Security.IsAllowed<ViewDesktopEquipmentTab>())
  714. return;
  715. SetVisibility(EquipmentDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  716. SetVisibility(EquipmentMessagesButton, Security.CanView<Notification>());
  717. SetVisibility(EquipmentTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  718. SetVisibility(EquipmentAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  719. SetVisibility(EquipmentMapButton, bMaps);
  720. SetVisibility(EquipmentDailyReportButton,
  721. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  722. SetVisibility(EquipmentButton, ClientFactory.IsSupported<Equipment>()
  723. && Security.CanView<Equipment>()
  724. && Security.IsAllowed<ViewDesktopEquipmentListScreen>());
  725. SetVisibleIfEither(EquipmentTaskSeparator,
  726. new FrameworkElement[]
  727. {
  728. EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton, EquipmentAttendanceButton, EquipmentMapButton,
  729. EquipmentDailyReportButton
  730. }, new FrameworkElement[] { EquipmentButton });
  731. SetVisibleIfAny(EquipmentActions, EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton,
  732. EquipmentAttendanceButton, EquipmentDailyReportButton, EquipmentButton);
  733. SetVisibility(TrackersMasterList, Security.CanView<GPSTracker>() && Security.IsAllowed<ViewDesktopGPSTrackersScreen>());
  734. AddSetupAction(EquipmentTab, "Tracker Types", TrackerTypes_Click, PRSDesktop.Resources.milestone,
  735. Security.CanView<GPSTrackerType>());
  736. AddSetupAction(EquipmentTab, "Stickers", Stickers_Click, PRSDesktop.Resources.barcode,
  737. Security.CanView<WebSticker>());
  738. AddSetupAction(EquipmentTab, "Digital Keys", DigitalKeys_Click, PRSDesktop.Resources.key,
  739. Security.CanView<DigitalKey>());
  740. AddSetupAction(EquipmentTab, "Equipment Groups", EquipmentGroupList_Click, PRSDesktop.Resources.specifications,
  741. Security.CanView<EquipmentGroup>());
  742. //EquipmentActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  743. //EquipmentReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  744. AddSetupModulesAndReports(EquipmentTab);
  745. SetTabVisibleIfAny(EquipmentTab, EquipmentButton, TrackersMasterList);
  746. }
  747. private void SetupAccountsTab(bool bMaps)
  748. {
  749. if (!Security.IsAllowed<ViewDesktopAccountsTab>())
  750. return;
  751. SetVisibility(AccountsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  752. SetVisibility(AccountsMessagesButton, Security.CanView<Notification>());
  753. SetVisibility(AccountsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  754. SetVisibility(AccountsDataButton, Security.IsAllowed<CanViewDataEntryPanel>());
  755. SetVisibility(AccountsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  756. SetVisibility(AccountsMapButton, bMaps);
  757. SetVisibility(AccountsDailyReportButton,
  758. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  759. SetVisibility(CustomerList, ClientFactory.IsSupported<Customer>()
  760. && Security.CanView<Customer>()
  761. && Security.IsAllowed<ViewDesktopCustomersScreen>());
  762. SetVisibility(InvoiceList, ClientFactory.IsSupported<Invoice>()
  763. && Security.CanView<Invoice>()
  764. && Security.IsAllowed<ViewDesktopInvoicesScreen>());
  765. SetVisibility(ReceiptList, ClientFactory.IsSupported<Receipt>()
  766. && Security.CanView<Receipt>()
  767. && Security.IsAllowed<ViewDesktopReceiptsScreen>());
  768. SetVisibility(SupplierList, ClientFactory.IsSupported<Supplier>()
  769. && Security.CanView<Supplier>()
  770. && Security.IsAllowed<ViewDesktopSuppliersScreen>());
  771. SetVisibility(PurchasesList, ClientFactory.IsSupported<PurchaseOrder>()
  772. && Security.CanView<PurchaseOrder>()
  773. && Security.IsAllowed<ViewDesktopPurchaseOrdersScreen>());
  774. SetVisibility(BillsList, ClientFactory.IsSupported<Bill>()
  775. && Security.CanView<Bill>()
  776. && Security.IsAllowed<ViewDesktopBillsScreen>());
  777. SetVisibility(PaymentsList, ClientFactory.IsSupported<Payment>()
  778. && Security.CanView<Payment>()
  779. && Security.IsAllowed<ViewDesktopPaymentsScreen>());
  780. SetVisibleIfEither(AccountsTaskSeparator1,
  781. new FrameworkElement[]
  782. {
  783. AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton, AccountsAttendanceButton, AccountsMapButton,
  784. AccountsDailyReportButton
  785. }, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList });
  786. SetVisibleIfEither(AccountsTaskSeparator2, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList },
  787. new FrameworkElement[] { SupplierList, PurchasesList, BillsList, PaymentsList });
  788. SetVisibleIfAny(AccountsActions, AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton,
  789. AccountsAttendanceButton,
  790. AccountsDailyReportButton, CustomerList, InvoiceList, ReceiptList, SupplierList, PurchasesList, BillsList, PaymentsList);
  791. AddSetupAction(AccountsTab, "Contact Types", ContactTypeList_Click, PRSDesktop.Resources.contacttype,
  792. ClientFactory.IsSupported<Contact>() && Security.CanView<ContactType>());
  793. AddSetupAction(AccountsTab, "Tax Codes", TaxCodeList_Click, PRSDesktop.Resources.taxcode,
  794. ClientFactory.IsSupported<GLCode>() && Security.CanView<TaxCode>());
  795. AddSetupAction(AccountsTab, "Receipt Types", ReceiptTypeList_Click, PRSDesktop.Resources.receipt,
  796. ClientFactory.IsSupported<GLCode>() && Security.CanView<ReceiptType>());
  797. AddSetupAction(AccountsTab, "Payment Types", PaymentTypeList_Click, PRSDesktop.Resources.payment,
  798. ClientFactory.IsSupported<GLCode>() && Security.CanView<PaymentType>());
  799. AddSetupAction(AccountsTab, "Cost Centres", CostCentresList_Click, PRSDesktop.Resources.costcentre,
  800. ClientFactory.IsSupported<CostCentre>() && Security.CanView<CostCentre>());
  801. AddSetupAction(AccountsTab, "GL Codes", GLCodesList_Click, PRSDesktop.Resources.glcode,
  802. ClientFactory.IsSupported<GLCode>() && Security.CanView<GLCode>());
  803. AddSetupAction(AccountsTab, "Purchase Order Categories", PurchaseOrderCategoriesButton_Click, PRSDesktop.Resources.service,
  804. ClientFactory.IsSupported<PurchaseOrderCategory>() && Security.CanView<PurchaseOrderCategory>());
  805. //AccountsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  806. //AccountsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  807. AddSetupSeparator(AccountsTab);
  808. AddSetupAction(AccountsTab, "Customer Spreadsheet Templates", () => ViewSpreadsheetTemplates<Customer>(), PRSDesktop.Resources.box,
  809. Security.CanView<CustomerSpreadsheet>());
  810. AddSetupAction(AccountsTab, "Supplier Spreadsheet Templates", () => ViewSpreadsheetTemplates<Supplier>(), PRSDesktop.Resources.box,
  811. Security.CanView<SupplierSpreadsheet>());
  812. AddSetupModulesAndReports(AccountsTab);
  813. SetTabVisibleIfAny(AccountsTab, CustomerList, InvoiceList, ReceiptList, SupplierList, PurchasesList, BillsList, PaymentsList);
  814. }
  815. private void SetupHumanResourcesTab(bool bMaps)
  816. {
  817. if (!Security.IsAllowed<ViewDesktopHumanResourcesTab>())
  818. return;
  819. SetVisibility(HumanResourcesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  820. SetVisibility(HumanResourcesMessagesButton, Security.CanView<Notification>());
  821. SetVisibility(HumanResourcesTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  822. SetVisibility(HumanResourcesAttendanceButton,
  823. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  824. SetVisibility(HumanResourcesMapButton, bMaps);
  825. SetVisibility(HumanResourcesDailyReportButton,
  826. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  827. SetVisibility(CalendarButton, Security.CanView<Assignment>() && Security.IsAllowed<ViewDesktopCalendarScreen>());
  828. SetVisibility(EmployeePlannerButton, Security.CanView<Assignment>() && Security.IsAllowed<ViewDesktopEmployeePlannerScreen>());
  829. SetVisibility(TimesheetsButton, Security.CanView<TimeSheet>() && Security.IsAllowed<ViewDesktopStaffTimeSheetsScreen>());
  830. SetVisibility(LeaveRequestsButton, Security.CanView<LeaveRequest>() && Security.IsAllowed<ViewDesktopLeaveRequestsScreen>());
  831. SetVisibility(OrgChartButton,
  832. ClientFactory.IsSupported<Employee>()
  833. && (
  834. Security.IsAllowed<CanViewOrgChartByEmployee>()
  835. || Security.IsAllowed<CanViewOrgChartByPosition>()
  836. || Security.IsAllowed<CanViewOrgChartByRole>()
  837. )
  838. && Security.IsAllowed<ViewDesktopOrgChartScreen>()
  839. );
  840. SetVisibility(MeetingsButton, Security.IsAllowed<ViewDesktopMeetingsScreen>());
  841. SetVisibleIfEither(HumanResourcesTaskSeparator,
  842. new FrameworkElement[]
  843. {
  844. HumanResourcesDashboardButton, HumanResourcesMessagesButton, HumanResourcesTaskButton, HumanResourcesAttendanceButton,
  845. HumanResourcesMapButton, HumanResourcesDailyReportButton
  846. }, new FrameworkElement[] { CalendarButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton });
  847. SetVisibleIfAny(HumanResourcesActions, HumanResourcesDashboardButton, HumanResourcesTaskButton,
  848. HumanResourcesAttendanceButton,
  849. HumanResourcesDailyReportButton, CalendarButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton);
  850. SetVisibility(UsersButton, Security.CanView<User>() && Security.IsAllowed<ViewDesktopUserAccountsScreen>());
  851. SetVisibility(EmployeesButton, Security.CanView<Employee>() && Security.IsAllowed<ViewDesktopEmployeeListScreen>());
  852. AddSetupAction(HumanResourcesTab, "Security Groups", SecurityGroupsButton_Click, PRSDesktop.Resources.securitygroup,
  853. Security.CanView<SecurityGroup>());
  854. AddSetupSeparator(HumanResourcesTab);
  855. AddSetupAction(HumanResourcesTab, "Employee Groups", GroupsSetup_Click, PRSDesktop.Resources.employees,
  856. Security.CanView<EmployeeGroup>());
  857. AddSetupAction(HumanResourcesTab, "Positions", PositionsSetup_Click, PRSDesktop.Resources.position,
  858. Security.CanView<EmployeePosition>());
  859. AddSetupAction(HumanResourcesTab, "Roles", RolesSetup_Click, PRSDesktop.Resources.employeerole,
  860. Security.CanView<EmployeeRole>());
  861. AddSetupAction(HumanResourcesTab, "Teams", EmployeeTeamsButton_Click, PRSDesktop.Resources.team,
  862. Security.CanView<EmployeeTeam>());
  863. AddSetupAction(HumanResourcesTab, "Activities", ActivityMenu_Click, PRSDesktop.Resources.quality,
  864. Security.CanView<Activity>());
  865. AddSetupAction(HumanResourcesTab, "Qualifications", QualificationMenu_Click, PRSDesktop.Resources.certificate,
  866. Security.CanView<Qualification>());
  867. AddSetupAction(HumanResourcesTab, "Rosters", RosterMenu_Click, PRSDesktop.Resources.assignments,
  868. Security.CanView<EmployeeRoster>());
  869. AddSetupSeparator(HumanResourcesTab);
  870. // AddSetupAction(HumanResourcesTab, "Rosters", RostersButton_Click, PRSDesktop.Resources.attendance,
  871. // Security.CanView<Roster>());
  872. AddSetupAction(HumanResourcesTab, "Overtime Rules", OvertimeRulesButton_Click, PRSDesktop.Resources.overtime,
  873. Security.CanView<OvertimeRule>());
  874. AddSetupAction(HumanResourcesTab, "Overtime", OvertimeButton_Click, PRSDesktop.Resources.overtime,
  875. Security.CanView<Overtime>());
  876. AddSetupAction(HumanResourcesTab, "Standard Leave", StandardLeaveButton_Click, PRSDesktop.Resources.fireworks,
  877. Security.CanView<StandardLeave>());
  878. SetVisibleIfEither(HumanResourcesSetupSeparator1,
  879. new FrameworkElement[] { CalendarButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton },
  880. new FrameworkElement[] { UsersButton, EmployeesButton });
  881. //HumanResourcesActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  882. //HumanResourcesReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  883. AddSetupSeparator(HumanResourcesTab);
  884. AddSetupAction(HumanResourcesTab, "Spreadsheet Templates", () => ViewSpreadsheetTemplates<Employee>(), PRSDesktop.Resources.box,
  885. Security.CanView<EmployeeSpreadsheet>());
  886. AddSetupModulesAndReports(HumanResourcesTab);
  887. SetTabVisibleIfAny(HumanResourcesTab, CalendarButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton, UsersButton, EmployeesButton);
  888. }
  889. private void SetupProductsTab(bool bMaps)
  890. {
  891. if (!Security.IsAllowed<ViewDesktopProductManagementTab>())
  892. return;
  893. SetVisibility(ProductsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  894. SetVisibility(ProductsMessagesButton, Security.CanView<Notification>());
  895. SetVisibility(ProductsTaskButton, Security.CanView<Kanban>());
  896. SetVisibility(ProductsAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  897. SetVisibility(ProductsMapButton, bMaps);
  898. SetVisibility(ProductsDailyReportButton,
  899. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  900. SetVisibility(ProductsMasterList, Security.CanView<Product>() && Security.IsAllowed<ViewDesktopProductListScreen>());
  901. SetVisibility(StockLocationList, Security.CanView<StockLocation>() && Security.IsAllowed<ViewDesktopStockLocationsScreen>());
  902. SetVisibility(StockMovementList, Security.CanView<StockMovement>() && Security.IsAllowed<ViewDesktopStockMovementsScreen>());
  903. SetVisibility(StockSummaryButton, Security.CanView<Product>()
  904. && Security.CanView<JobMaterial>()
  905. && Security.IsAllowed<ViewDesktopStockForecastScreen>());
  906. SetVisibility(ReservationManagementButton, Security.IsAllowed<ViewDesktopReservationManagementScreen>());
  907. SetVisibleIfEither(ProductsTaskSeparator,
  908. new FrameworkElement[]
  909. {
  910. ProductsDashboardButton, ProductsMessagesButton, ProductsTaskButton, ProductsAttendanceButton, ProductsMapButton,
  911. ProductsDailyReportButton
  912. }, new FrameworkElement[] { ProductsMasterList, StockLocationList, StockMovementList, StockSummaryButton });
  913. SetVisibleIfAny(ProductActions, ProductsMasterList, StockLocationList, StockMovementList, StockSummaryButton);
  914. AddSetupAction(ProductTab, "Product Dimensions", ProductDimensionUnitsList_Click, PRSDesktop.Resources.unitofmeasure,
  915. Security.CanView<ProductDimensionUnit>());
  916. AddSetupAction(ProductTab, "Product Groups", ProductGroupsList_Click, PRSDesktop.Resources.productgroup,
  917. Security.CanView<ProductGroup>());
  918. AddSetupAction(ProductTab, "Product Styles", ProductStylesList_Click, PRSDesktop.Resources.palette,
  919. Security.CanView<ProductStyle>());
  920. AddSetupAction(ProductTab, "Stock Areas", StockAreasList_Click, PRSDesktop.Resources.rack,
  921. Security.CanView<StockArea>());
  922. AddSetupAction(ProductTab, "Stock Warehouses", StockWarehouseList_Click, PRSDesktop.Resources.factorysetup,
  923. Security.CanView<StockWarehouse>());
  924. AddSetupSeparator(ProductTab);
  925. AddSetupAction(ProductTab, "Spreadsheet Templates", () => ViewSpreadsheetTemplates<Product>(), PRSDesktop.Resources.box,
  926. Security.CanView<ProductSpreadsheet>());
  927. AddSetupModulesAndReports(ProductTab);
  928. SetTabVisibleIfAny(ProductTab, ProductActions);
  929. }
  930. private void SetupLogisticsTab(bool bMaps)
  931. {
  932. if (!Security.IsAllowed<ViewDesktopLogisticsTab>())
  933. return;
  934. SetVisibility(LogisticsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  935. SetVisibility(LogisticsMessagesButton, Security.CanView<Notification>());
  936. SetVisibility(LogisticsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  937. SetVisibility(LogisticsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  938. SetVisibility(LogisticsMapButton, bMaps);
  939. SetVisibility(LogisticsDailyReportButton,
  940. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  941. SetVisibility(ReadyToGoItemsButton,
  942. ClientFactory.IsSupported<DeliveryItem>()
  943. && Security.IsAllowed<CanViewLogisticsReadyToGo>()
  944. && Security.IsAllowed<ViewDesktopReadyToGoScreen>());
  945. SetVisibility(DispatchButton, Security.CanView<Shipment>()
  946. && Security.CanView<DeliveryItem>()
  947. && Security.IsAllowed<ViewDesktopRackListScreen>());
  948. SetVisibility(RequisitionsButton, Security.CanView<Requisition>() && Security.IsAllowed<ViewDesktopSiteRequisitionsScreen>());
  949. SetVisibility(DeliveriesButton, Security.IsAllowed<CanViewDeliveriesModule>() && Security.IsAllowed<ViewDesktopDeliveriesScren>());
  950. SetVisibility(DeliveredItemsButton,
  951. ClientFactory.IsSupported<DeliveryItem>()
  952. && Security.IsAllowed<CanViewDeliveredOnSite>()
  953. && Security.IsAllowed<ViewDesktopDeliveredOnSiteScreen>());
  954. SetVisibility(ConsignmentButton, Security.CanView<Consignment>() && Security.IsAllowed<ViewDesktopIncomingConsignmentsScreen>());
  955. SetVisibleIfEither(LogisticsTaskSeparator1,
  956. new FrameworkElement[]
  957. {
  958. LogisticsDashboardButton, LogisticsMessagesButton, LogisticsTaskButton, LogisticsAttendanceButton, LogisticsMapButton,
  959. LogisticsDailyReportButton
  960. },
  961. new FrameworkElement[]
  962. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton });
  963. SetVisibleIfEither(LogisticsTaskSeparator2,
  964. new FrameworkElement[]
  965. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton },
  966. new FrameworkElement[] { ConsignmentButton });
  967. AddSetupAction(LogisticsTab, "Delivery Types", DeliveryTypesButton_Click, PRSDesktop.Resources.truck,
  968. Security.CanView<ConsignmentType>());
  969. AddSetupAction(LogisticsTab, "Consignment Types", ConsignmentTypesButton_Click, PRSDesktop.Resources.service,
  970. Security.CanView<DeliveryType>());
  971. //LogisticsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  972. //LogisticsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  973. AddSetupModulesAndReports(LogisticsTab);
  974. SetTabVisibleIfAny(LogisticsTab, DispatchButton, RequisitionsButton, DeliveriesButton, ReadyToGoItemsButton,
  975. DeliveredItemsButton,
  976. ConsignmentButton);
  977. }
  978. private void SetupManufacturingTab(bool bMaps)
  979. {
  980. if (!Security.IsAllowed<ViewDesktopManufacturingTab>())
  981. return;
  982. SetVisibility(ManufacturingDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  983. SetVisibility(ManufacturingMessagesButton, Security.CanView<Notification>());
  984. SetVisibility(ManufacturingTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  985. SetVisibility(ManufacturingAttendanceButton,
  986. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  987. SetVisibility(ManufacturingMapButton, bMaps);
  988. SetVisibility(ManufacturingDailyReportButton,
  989. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  990. SetVisibility(FactoryStatusButton,
  991. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket>()
  992. && Security.IsAllowed<CanViewFactoryStatus>()
  993. && Security.IsAllowed<ViewDesktopManufacturingStatusScreen>());
  994. SetVisibility(FactoryAllocationButton,
  995. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket, ManufacturingPacketStage>()
  996. && Security.IsAllowed<CanViewFactoryAllocation>()
  997. && Security.IsAllowed<ViewDesktopFactoryAllocationScreen>());
  998. //SetVisibility(FactoryScheduleButton, ClientFactory.IsSupported<Booking>() && ClientFactory.IsEnabled<>());
  999. SetVisibility(FactoryFloorButton,
  1000. ClientFactory.IsSupported<ManufacturingPacket>()
  1001. && Security.IsAllowed<CanViewFactoryFloor>()
  1002. && Security.IsAllowed<ViewDesktopFactoryFloorScreen>());
  1003. //SetVisibility(FactoryReadyButton, ClientFactory.IsSupported<ManufacturingPacket>() && Security.IsAllowed<CanViewFactoryReadyToGo>());
  1004. SetVisibleIfEither(ManufacturingTaskSeparator,
  1005. new FrameworkElement[]
  1006. {
  1007. ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton, ManufacturingAttendanceButton,
  1008. ManufacturingMapButton, ManufacturingDailyReportButton
  1009. }, new FrameworkElement[] { FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton /* , FactoryReadyButton */ });
  1010. SetVisibleIfAny(ManufacturingActions, ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton,
  1011. ManufacturingAttendanceButton, ManufacturingDailyReportButton, FactoryStatusButton, FactoryAllocationButton,
  1012. FactoryFloorButton);
  1013. AddSetupAction(ManufacturingTab, "Factory Settings", FactorySetup_Click, PRSDesktop.Resources.factorysetup,
  1014. ClientFactory.IsSupported<ManufacturingFactory>() && Security.IsAllowed<CanViewFactorySettings>());
  1015. AddSetupAction(ManufacturingTab, "Manufacturing Templates", TemplateSetup_Click, PRSDesktop.Resources.template,
  1016. Security.CanView<ManufacturingTemplate>());
  1017. AddSetupAction(ManufacturingTab, "Manufacturing Trolleys", TrolleySetup_Click, PRSDesktop.Resources.trolley,
  1018. Security.CanView<ManufacturingTrolley>());
  1019. AddSetupAction(ManufacturingTab, "Lost Time Types", LostTimeSetup_Click, PRSDesktop.Resources.smiley,
  1020. Security.CanView<ManufacturingLostTime>());
  1021. //ManufacturingActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  1022. //ManufacturingReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  1023. AddSetupModulesAndReports(ManufacturingTab);
  1024. SetTabVisibleIfAny(ManufacturingTab, FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton);
  1025. }
  1026. private void SetupProjectsTab(bool bMaps)
  1027. {
  1028. if (!Security.IsAllowed<ViewDesktopProjectsTab>())
  1029. return;
  1030. SetVisibility(ProjectsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  1031. SetVisibility(ProjectMessagesButton, Security.CanView<Notification>());
  1032. SetVisibility(ProjectTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  1033. SetVisibility(ProjectAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  1034. SetVisibility(ProjectsMapButton, bMaps);
  1035. SetVisibility(ProjectDailyReportButton,
  1036. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  1037. SetVisibility(ProjectsButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopProjectsScreen>());
  1038. SetVisibility(ServiceButton, false);
  1039. SetVisibility(ProjectPlannerButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopProjectPlannerScreen>());
  1040. SetVisibility(DesignManagementButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopDesignManagementScreen>());
  1041. SetVisibleIfEither(ProjectTaskSeparator,
  1042. new FrameworkElement[]
  1043. {
  1044. ProjectsDashboardButton, ProjectMessagesButton, ProjectTaskButton, ProjectAttendanceButton, ProjectsMapButton,
  1045. ProjectDailyReportButton
  1046. }, new FrameworkElement[] { QuotesButton, ProjectsButton, ServiceButton, ProjectPlannerButton });
  1047. AddSetupAction(ProjectsTab, "Job Statuses", JobStatusButton_Click, PRSDesktop.Resources.view,
  1048. Security.CanView<JobStatus>());
  1049. AddSetupAction(ProjectsTab, "Document MileStones", JobDocumentMileStoneButton_OnClick, PRSDesktop.Resources.revision,
  1050. true);
  1051. //AddSetupAction(ProjectsTab, "Document Tags", JobDocumentTagButton_OnClick, PRSDesktop.Resources.checklist,
  1052. // true);
  1053. AddSetupAction(ProjectsTab, "Financial Statuses", FinancialStatusButton_Click, PRSDesktop.Resources.view,
  1054. Security.CanView<JobScope>());
  1055. AddSetupAction(ProjectsTab, "Drawing Templates", DrawingTemplatesButton_Click, PRSDesktop.Resources.doc_misc,
  1056. true);
  1057. AddSetupSeparator(ProjectsTab);
  1058. AddSetupAction(ProjectsTab, "Spreadsheet Templates", () => ViewSpreadsheetTemplates<Job>(), PRSDesktop.Resources.box,
  1059. Security.CanView<JobSpreadsheet>());
  1060. AddSetupSeparator(ProjectsTab);
  1061. AddSetupAction(ProjectsTab, "Setout Groups", ViewSetoutGroups, PRSDesktop.Resources.draw,
  1062. Security.IsAllowed<CanConfigureFactoryFloor>());
  1063. AddSetupModulesAndReports(ProjectsTab);
  1064. //ProjectsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  1065. //ProjectReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  1066. SetTabVisibleIfAny(ProjectsTab, ProjectsButton, ServiceButton, ProjectPlannerButton);
  1067. }
  1068. private void SetupQuotesTab(bool bMaps)
  1069. {
  1070. if (!Security.IsAllowed<ViewDesktopQuotesTab>())
  1071. return;
  1072. SetVisibility(QuotesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  1073. SetVisibility(QuotesMessagesButton, Security.CanView<Notification>());
  1074. SetVisibility(QuotesTaskButton, Security.IsAllowed<CanViewTasks>());
  1075. SetVisibility(QuotesAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  1076. SetVisibility(QuotesMapButton, bMaps);
  1077. SetVisibility(QuotesDailyReportButton,
  1078. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  1079. SetVisibility(QuotesButton, Security.CanView<Quote>() && Security.IsAllowed<ViewDesktopQuotesScreen>());
  1080. SetVisibility(KitsMasterList, Security.CanView<Kit>() && Security.IsAllowed<ViewDesktopProductKitsScreen>());
  1081. SetVisibility(CostSheetsMasterList, Security.CanView<CostSheet>() && Security.IsAllowed<ViewDesktopCostSheetsScreen>());
  1082. SetVisibleIfEither(QuotesTaskSeparator,
  1083. new FrameworkElement[]
  1084. {
  1085. QuotesDashboardButton, QuotesMessagesButton, QuotesTaskButton, QuotesAttendanceButton, QuotesMapButton,
  1086. QuotesDailyReportButton
  1087. }, new FrameworkElement[] { QuotesButton });
  1088. SetVisibleIfEither(QuotesActionSeparator, new FrameworkElement[] { QuotesButton },
  1089. new FrameworkElement[] { KitsMasterList, CostSheetsMasterList });
  1090. SetVisibleIfAny(QuotesActions, QuotesButton, KitsMasterList, CostSheetsMasterList);
  1091. AddSetupAction(QuotesTab, "Status Codes", QuoteStatusButton_Click, PRSDesktop.Resources.quotestatus,
  1092. ClientFactory.IsSupported<Quote>() && Security.IsAllowed<CanModifyQuoteStatuses>());
  1093. AddSetupAction(QuotesTab, "Design Sections", QuoteDesignSectionButton_Click, PRSDesktop.Resources.design,
  1094. Security.CanView<QuoteDesignSection>());
  1095. AddSetupSeparator(QuotesTab);
  1096. AddSetupAction(QuotesTab, "Kit Conditions", KitConditionList_Click, PRSDesktop.Resources.kitcondition,
  1097. Security.CanView<KitCondition>());
  1098. AddSetupAction(QuotesTab, "Kit Formulae", KitFormulaeList_Click, PRSDesktop.Resources.kitformula,
  1099. Security.CanView<KitFormula>());
  1100. AddSetupAction(QuotesTab, "Cost Sheet Types", CostSheetTypeList_Click, PRSDesktop.Resources.costsheettype,
  1101. Security.CanView<CostSheetType>());
  1102. AddSetupAction(QuotesTab, "Cost Sheet Brands", CostSheetBrandList_Click, PRSDesktop.Resources.costsheetbrand,
  1103. Security.CanView<CostSheetBrand>());
  1104. AddSetupAction(QuotesTab, "Cost Sheet Sections", CostSheetSectionList_Click, PRSDesktop.Resources.costsheetsection,
  1105. Security.CanView<CostSheetSection>());
  1106. AddSetupSeparator(QuotesTab);
  1107. AddSetupAction(QuotesTab, "Symbols", QuoteDiagramSymbols_Checked, PRSDesktop.Resources.pencil,
  1108. Security.CanView<QuoteDiagramSymbol>());
  1109. AddSetupAction(QuotesTab, "Symbol Types", QuoteDiagramSymbolTypes_Checked, PRSDesktop.Resources.attachment,
  1110. Security.CanView<QuoteDiagramSymbol>());
  1111. AddSetupAction(QuotesTab, "Dimension Types", QuoteTakeOffUnits_Click, PRSDesktop.Resources.box,
  1112. Security.CanView<QuoteTakeOffUnit>());
  1113. AddSetupSeparator(QuotesTab);
  1114. AddSetupAction(QuotesTab, "Spreadsheet Templates", ViewSpreadsheetTemplates<Quote>, PRSDesktop.Resources.box,
  1115. Security.CanView<QuoteSpreadsheet>());
  1116. AddSetupModulesAndReports(QuotesTab);
  1117. SetTabVisibleIfAny(QuotesTab, QuotesActions);
  1118. }
  1119. private void ViewSpreadsheetTemplates<TEntity>() where TEntity : Entity
  1120. {
  1121. SpreadsheetTemplateGrid grid = new SpreadsheetTemplateGrid();
  1122. grid.AppliesTo = typeof(TEntity);
  1123. grid.Refresh(true, true);
  1124. DynamicContentDialog dlg = new DynamicContentDialog(grid, false);
  1125. dlg.Title = $"{typeof(TEntity).EntityName().Split(".").Last()} Spreadsheet Templates";
  1126. dlg.ShowDialog();
  1127. }
  1128. private IEnumerable<ReportExportDefinition> AddTemplateDefinitions()
  1129. {
  1130. if (CurrentPanel == null)
  1131. return new List<ReportExportDefinition>() { new ReportExportDefinition("Email Report", PRSDesktop.Resources.email, ReportExportType.PDF,
  1132. EmailUtils.DoEmailReport)};
  1133. else
  1134. return EmailUtils.CreateTemplateDefinitions(CurrentPanel.DataModel(Selection.None));
  1135. }
  1136. private void SetupDock<TSecurityDescriptor>(LayoutAnchorable layout, IDockPanel dock)
  1137. where TSecurityDescriptor : ISecurityDescriptor, new()
  1138. {
  1139. if (Security.IsAllowed<TSecurityDescriptor>())
  1140. {
  1141. if (!DockGroup.Children.Any(x => x == layout))
  1142. {
  1143. DockGroup.Children.Add(layout);
  1144. }
  1145. if (layout.IsVisible && (ClientFactory.UserGuid != Guid.Empty))
  1146. dock.Setup();
  1147. }
  1148. else
  1149. {
  1150. DockGroup.RemoveChild(layout);
  1151. }
  1152. }
  1153. private void LoadApplicationState()
  1154. {
  1155. if (ClientFactory.UserGuid != Guid.Empty)
  1156. {
  1157. _ribbon.IsCollapsed = false;
  1158. if (OutstandingDailyReports(false))
  1159. {
  1160. MessageBox.Show("There are outstanding Daily Reports that must be filled out before continuing!" +
  1161. "\n\nAccess to PRS is restricted until this is corrected.",
  1162. "Outstanding Reports"
  1163. );
  1164. var dailyReportPanel = LoadWindow<DailyReport>(ProjectDailyReportButton);
  1165. dailyReportPanel.OnTimeSheetConfirmed += e =>
  1166. {
  1167. if (!OutstandingDailyReports(true))
  1168. {
  1169. ConfigureMainScreen();
  1170. LoadApplicationState();
  1171. }
  1172. };
  1173. return;
  1174. }
  1175. using (new WaitCursor())
  1176. {
  1177. _ribbon.IsCollapsed = false;
  1178. LoadInitialWindow();
  1179. }
  1180. }
  1181. }
  1182. private void LoadInitialWindow()
  1183. {
  1184. var app = new LocalConfiguration<AppSettings>().Load();
  1185. if (app.Settings.ContainsKey("CurrentPanel"))
  1186. {
  1187. try
  1188. {
  1189. var bFound = false;
  1190. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1191. if (module.Length == 2)
  1192. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1193. {
  1194. if (String.Equals(tab.Header, module.First()))
  1195. {
  1196. _ribbon.SelectedTabItem = tab;
  1197. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1198. {
  1199. foreach (var item in bar.Items)
  1200. {
  1201. var button = item as Fluent.Button;
  1202. if (button != null && String.Equals(button.Header, module.Last()))
  1203. {
  1204. bFound = true;
  1205. button.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
  1206. break;
  1207. }
  1208. }
  1209. if (bFound)
  1210. break;
  1211. }
  1212. }
  1213. if (bFound)
  1214. break;
  1215. }
  1216. }
  1217. catch (Exception e)
  1218. {
  1219. MessageBox.Show(string.Format("Unable to Load {0}!\n\n{1}\n{2}", app.Settings["CurrentPanel"], e.Message, e.StackTrace));
  1220. }
  1221. }
  1222. }
  1223. private void _ribbon_OnLoaded(object sender, RoutedEventArgs e)
  1224. {
  1225. _ribbon.SelectedTabItem = CurrentTab;
  1226. }
  1227. private void LoadSecondaryWindows()
  1228. {
  1229. if (ClientFactory.UserGuid != Guid.Empty)
  1230. {
  1231. var windows = App.DatabaseSettings.SecondaryWindows;
  1232. foreach (var key in windows.Keys.ToArray())
  1233. {
  1234. _secondarywindows[key] = new SecondaryWindow(
  1235. key,
  1236. windows[key].Item1,
  1237. windows[key].Item2,
  1238. windows[key].Item3,
  1239. windows[key].Item4,
  1240. windows[key].Item5,
  1241. windows[key].Item6
  1242. );
  1243. _secondarywindows[key].Closed += (o, e) => { _secondarywindows.Remove(key); };
  1244. _secondarywindows[key].Show();
  1245. }
  1246. }
  1247. else
  1248. {
  1249. foreach (var key in _secondarywindows.Keys.ToArray())
  1250. {
  1251. App.IsClosing = true;
  1252. _secondarywindows[key].Close();
  1253. App.IsClosing = false;
  1254. }
  1255. }
  1256. }
  1257. private Fluent.RibbonTabItem GetTabItem(FrameworkElement? sender)
  1258. {
  1259. if (sender == null)
  1260. throw new Exception("No Tab Found!");
  1261. if (sender is Fluent.RibbonTabItem)
  1262. return (Fluent.RibbonTabItem)sender;
  1263. return GetTabItem(sender.Parent as FrameworkElement);
  1264. }
  1265. private T? LoadWindow<T>(Fluent.Button sender) where T : class, IBasePanel, new()
  1266. {
  1267. return LoadWindow<T>(sender, new CancelEventArgs());
  1268. }
  1269. private T? LoadWindow<T>(Fluent.Button sender, CancelEventArgs cancel) where T : class, IBasePanel, new()
  1270. {
  1271. using (new WaitCursor())
  1272. {
  1273. UnloadWindow(cancel);
  1274. if (cancel.Cancel)
  1275. {
  1276. return null;
  1277. }
  1278. CurrentTab = GetTabItem(sender);
  1279. CurrentButton = sender;
  1280. //CurrentButton.IsSelected = true;
  1281. UpdateRibbonColors();
  1282. var panel = new T();
  1283. CurrentPanel = panel;
  1284. ReportUtils.ExportDefinitions.Clear();
  1285. ReportUtils.ExportDefinitions.AddRange(AddTemplateDefinitions());
  1286. InitializePanelProperties(panel);
  1287. CurrentPanel.IsReady = false;
  1288. CurrentPanel.Setup();
  1289. CurrentPanel.IsReady = true;
  1290. CurrentPanel.OnUpdateDataModel += (s, m) =>
  1291. {
  1292. ReloadModules(s, m);
  1293. ReloadReports(s, m);
  1294. };
  1295. CurrentPanel_Label = sender.Header?.ToString() ?? "";
  1296. CurrentPanel_Ticks = DateTime.Now;
  1297. ContentControl.Content = CurrentPanel;
  1298. Title =
  1299. $"{CurrentPanel_Label} - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1300. if (sender != null)
  1301. {
  1302. var model = CurrentPanel.DataModel(Selection.None);
  1303. var section = CurrentPanel.SectionName;
  1304. ReloadModules(section, model);
  1305. ReloadReports(section, model);
  1306. }
  1307. CurrentPanel.Refresh();
  1308. if (CurrentPanel is NotificationPanel)
  1309. {
  1310. Logger.Send(LogType.Information, ClientFactory.UserID, "Disabling Heartbeat");
  1311. NotificationsWatchDog.IsEnabled = false;
  1312. Notifications.Visibility = Visibility.Collapsed;
  1313. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  1314. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  1315. }
  1316. else
  1317. {
  1318. ReloadNotifications();
  1319. }
  1320. if (sender != null)
  1321. {
  1322. var settings = new LocalConfiguration<AppSettings>().Load();
  1323. var module = string.Format("{0} / {1}", CurrentTab?.Header, sender.Header);
  1324. if (!settings.Settings.ContainsKey("CurrentPanel") || module != settings.Settings["CurrentPanel"])
  1325. {
  1326. settings.Settings["CurrentPanel"] = module;
  1327. try
  1328. {
  1329. new LocalConfiguration<AppSettings>().Save(settings);
  1330. }
  1331. catch (Exception e)
  1332. {
  1333. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1334. }
  1335. }
  1336. }
  1337. //stopwatch.Stop();
  1338. //Logger.Send(LogType.Information, ClientFactory.UserID, String.Format("Loading {0} to took {1} ms", sender != null ? sender.Label : module, stopwatch.ElapsedMilliseconds));
  1339. return panel;
  1340. }
  1341. }
  1342. private void UpdateRibbonColors()
  1343. {
  1344. foreach (var tab in _ribbon.Tabs)
  1345. {
  1346. bool bFound = false;
  1347. foreach (var grp in tab.Groups)
  1348. {
  1349. foreach (var btn in grp.Items)
  1350. {
  1351. if (btn is Fluent.Button fluentbutton)
  1352. {
  1353. bFound = bFound || (btn == CurrentButton);
  1354. fluentbutton.Background = (btn == CurrentButton) ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1355. fluentbutton.Foreground = (btn == CurrentButton) ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1356. }
  1357. }
  1358. tab.Background = bFound ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1359. tab.Foreground = bFound ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1360. }
  1361. }
  1362. }
  1363. private static void StartLocalDatabase(IProgress<string> progress)
  1364. {
  1365. var dirName = Path.GetDirectoryName(App.DatabaseSettings.FileName);
  1366. if (!Directory.Exists(dirName) && dirName != null)
  1367. Directory.CreateDirectory(dirName);
  1368. var FileName = App.DatabaseSettings.FileName;
  1369. var Exists = File.Exists(FileName);
  1370. progress.Report("Configuring Stores");
  1371. DbFactory.Stores = CoreUtils.TypeList(
  1372. new[]
  1373. {
  1374. typeof(DocumentStore).Assembly,
  1375. typeof(EquipmentStore).Assembly
  1376. },
  1377. myType =>
  1378. myType.IsClass
  1379. && !myType.IsAbstract
  1380. && !myType.IsGenericType
  1381. && myType.GetInterfaces().Contains(typeof(IStore))
  1382. ).ToArray();
  1383. DbFactory.Provider = new SQLiteProvider(App.DatabaseSettings.FileName);
  1384. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  1385. DbFactory.Logo = App.DatabaseSettings.Logo;
  1386. progress.Report("Starting Local Database");
  1387. DbFactory.Start();
  1388. progress.Report("Checking Database");
  1389. var users = DbFactory.Provider.Load<User>();
  1390. if (!users.Any())
  1391. {
  1392. var user = new User { UserID = "ADMIN", Password = "admin" };
  1393. DbFactory.Provider.Save(user);
  1394. var employee = DbFactory.Provider.Load(new Filter<Employee>(x => x.Code).IsEqualTo("ADMIN")).FirstOrDefault();
  1395. employee ??= new Employee { Code = "ADMIN", Name = "Administrator Account" };
  1396. employee.UserLink.ID = user.ID;
  1397. DbFactory.Provider.Save(employee);
  1398. }
  1399. StoreUtils.GoogleAPIKey = App.DatabaseSettings.GoogleAPIKey;
  1400. Job.JobNumberPrefix = App.DatabaseSettings.JobPrefix;
  1401. PurchaseOrder.PONumberPrefix = App.DatabaseSettings.PurchaseOrderPrefix;
  1402. }
  1403. #endregion
  1404. #region Login Management
  1405. private ValidationStatus? DoLogin(bool autoLogin)
  1406. {
  1407. ValidationStatus? result = null;
  1408. if (autoLogin)
  1409. {
  1410. if (App.DatabaseSettings.LoginType == LoginType.UserID)
  1411. {
  1412. try
  1413. {
  1414. result = ClientFactory.Validate(App.DatabaseSettings.UserID, App.DatabaseSettings.Password);
  1415. }
  1416. catch (Exception e)
  1417. {
  1418. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error connecting to server: {CoreUtils.FormatException(e)}");
  1419. MessageBox.Show("Error connecting to server.\nPlease check the server URL and port number.");
  1420. result = null;
  1421. }
  1422. if (result == ValidationStatus.INVALID)
  1423. {
  1424. MessageBox.Show("Unable to Login with User ID: " + App.DatabaseSettings.UserID);
  1425. }
  1426. }
  1427. }
  1428. if (result != ValidationStatus.VALID)
  1429. {
  1430. var login = new PinLogin(CoreUtils.GetVersion(), result ?? ValidationStatus.INVALID);
  1431. if (login.ShowDialog() == true)
  1432. {
  1433. result = ValidationStatus.VALID;
  1434. }
  1435. }
  1436. return result ?? ValidationStatus.INVALID;
  1437. }
  1438. /// <summary>
  1439. /// To be called after <see cref="DoLogin(bool)"/> and if a valid login session exists. Configures the main screen and loads the windows.
  1440. /// </summary>
  1441. private void AfterLogin()
  1442. {
  1443. LoadCurrentEmployee();
  1444. if (CheckTimesheetBypass(true))
  1445. {
  1446. UpdateCurrentLogin();
  1447. }
  1448. else
  1449. {
  1450. MessageBox.Show("You must clock on before logging in to PRS!");
  1451. ClientFactory.InvalidateUser();
  1452. App.EmployeeID = Guid.Empty;
  1453. App.EmployeeName = "";
  1454. App.EmployeeCode = "";
  1455. App.EmployeeEmail = "";
  1456. }
  1457. ApplyColorScheme();
  1458. ConfigureMainScreen();
  1459. LoadApplicationState();
  1460. LoadSecondaryWindows();
  1461. //if (_ribbon.Menu.IsVisible)
  1462. //{
  1463. // _ribbon.;
  1464. //}
  1465. }
  1466. /// <summary>
  1467. /// 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.
  1468. /// </summary>
  1469. private void UpdateCurrentLogin()
  1470. {
  1471. if (CoreUtils.GetVersion().Equals("???"))
  1472. return;
  1473. // Register this station with the Server
  1474. // Later on, the heartbeat will check to make sure
  1475. // that the StationID hasn't changed. If it has,
  1476. // then we've logged in somewhere else and we'll
  1477. // drop out of this station
  1478. var curr = new Client<Login>().Query(
  1479. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  1480. null
  1481. ).Rows.FirstOrDefault();
  1482. if (curr != null)
  1483. {
  1484. var c = curr.ToObject<Login>();
  1485. c.StationID = station.StationID;
  1486. station = c;
  1487. }
  1488. else
  1489. {
  1490. station.User.ID = ClientFactory.UserGuid;
  1491. station.TimeStamp = DateTime.Now;
  1492. }
  1493. new Client<Login>().Save(station, "", (o, e) => { });
  1494. }
  1495. private void LoadCurrentEmployee()
  1496. {
  1497. var me = new Client<Employee>().Query(
  1498. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid),
  1499. new Columns<Employee>(x => x.ID).Add(x => x.Email).Add(x => x.Name)
  1500. );
  1501. App.EmployeeID = me.Rows.FirstOrDefault()?.Get<Employee, Guid>(x => x.ID) ?? Guid.Empty;
  1502. App.EmployeeName = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Name) ?? "";
  1503. App.EmployeeCode = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Code) ?? "";
  1504. App.EmployeeEmail = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Email) ?? "";
  1505. }
  1506. private void ExecuteLogout()
  1507. {
  1508. new Client<Login>().Delete(station, "");
  1509. station.ID = Guid.Empty;
  1510. App.EmployeeID = Guid.Empty;
  1511. App.EmployeeName = "";
  1512. App.EmployeeEmail = "";
  1513. }
  1514. /// <summary>
  1515. /// Logs the user out and unloads windows
  1516. /// </summary>
  1517. /// <param name="message">A message to display as the reason for logging out, or <c>null</c> for no message.</param>
  1518. private bool Logout(string? message = null, bool force = false)
  1519. {
  1520. // 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,
  1521. // all the queries that get called here will throw exceptions and thus break our system, failing to log out.
  1522. try
  1523. {
  1524. FinalizeAutoTimesheet();
  1525. }
  1526. catch
  1527. {
  1528. if (!force) throw;
  1529. }
  1530. // Try to unload the window;
  1531. try
  1532. {
  1533. UnloadWindow(null);
  1534. if (DatabaseType == DatabaseType.Standalone && !CoreUtils.GetVersion().Equals("???"))
  1535. scheduler.Stop();
  1536. }
  1537. catch
  1538. {
  1539. if (!force) throw;
  1540. }
  1541. // Next, try to set things to being empty
  1542. try
  1543. {
  1544. if (!CoreUtils.GetVersion().Equals("???"))
  1545. if (station.ID != Guid.Empty)
  1546. {
  1547. ExecuteLogout();
  1548. }
  1549. ClearTrackingKanban();
  1550. }
  1551. catch
  1552. {
  1553. if (!force) throw;
  1554. }
  1555. ClientFactory.InvalidateUser();
  1556. ConfigureMainScreen();
  1557. LoadSecondaryWindows();
  1558. if (message != null)
  1559. {
  1560. MessageBox.Show(message);
  1561. }
  1562. if (DoLogin(false) == ValidationStatus.VALID)
  1563. {
  1564. AfterLogin();
  1565. }
  1566. return true;
  1567. }
  1568. #endregion
  1569. #region Timesheets
  1570. private void RefreshTimeSheets()
  1571. {
  1572. if (App.EmployeeID == Guid.Empty)
  1573. return;
  1574. var filter = new Filter<TimeSheet>(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID);
  1575. filter = filter.And(new Filter<TimeSheet>(x => x.Confirmed).IsEqualTo(DateTime.MinValue).Or(x => x.Date).IsEqualTo(DateTime.Today));
  1576. _timesheets = new Client<TimeSheet>().Query(
  1577. filter,
  1578. new Columns<TimeSheet>(
  1579. x => x.ID,
  1580. x => x.Date,
  1581. x => x.Finish
  1582. )
  1583. );
  1584. }
  1585. private CoreTable GetTimesheet()
  1586. {
  1587. return new Client<TimeSheet>().Query(
  1588. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today)
  1589. .And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID)
  1590. .And(x => x.Finish).IsEqualTo(TimeSpan.Zero)
  1591. );
  1592. }
  1593. private bool CheckTimesheetBypass(bool message)
  1594. {
  1595. if (!ClientFactory.IsSupported<TimeSheet>())
  1596. return true;
  1597. var isClockedOn = IsClockedOn();
  1598. if (!Security.IsAllowed<CanBypassTimeBench>())
  1599. {
  1600. if (!isClockedOn)
  1601. {
  1602. if (message)
  1603. MessageBox.Show("You must clock on before opening this screen");
  1604. return false;
  1605. }
  1606. return true;
  1607. }
  1608. if (Security.IsAllowed<AutoGenerateTimesheet>())
  1609. if (!isClockedOn)
  1610. {
  1611. var ts = new TimeSheet();
  1612. ts.Date = DateTime.Today;
  1613. ts.Start = DateTime.Now.TimeOfDay;
  1614. ts.EmployeeLink.ID = App.EmployeeID;
  1615. ts.Notes = "Automatic Login from PRS Desktop";
  1616. new Client<TimeSheet>().Save(ts, "AutoLogon because Timebench Bypass is enabled", (o, e) => { });
  1617. }
  1618. return true;
  1619. }
  1620. private bool IsClockedOn()
  1621. {
  1622. RefreshTimeSheets();
  1623. if (_timesheets == null)
  1624. return false;
  1625. return _timesheets.Rows.Any(r =>
  1626. r.Get<TimeSheet, DateTime>(c => c.Date).Date == DateTime.Today && r.Get<TimeSheet, TimeSpan>(c => c.Finish) == new TimeSpan());
  1627. }
  1628. #endregion
  1629. private string CurrentPanelSlug()
  1630. {
  1631. var app = new LocalConfiguration<AppSettings>().Load();
  1632. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1633. return module.LastOrDefault()?.Replace(" ", "_").Replace("/", "") ?? "";
  1634. }
  1635. private bool ShowHelp()
  1636. {
  1637. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + CurrentPanelSlug()) { UseShellExecute = true });
  1638. return true;
  1639. }
  1640. private void Wiki_Click(object sender, RoutedEventArgs e)
  1641. {
  1642. ShowHelp();
  1643. }
  1644. private void Window_Loaded(object sender, RoutedEventArgs e)
  1645. {
  1646. }
  1647. private void UnloadWindow(CancelEventArgs? cancel)
  1648. {
  1649. if (CurrentPanel != null)
  1650. {
  1651. Heartbeat(DateTime.Now - CurrentPanel_Ticks, true);
  1652. try
  1653. {
  1654. CurrentPanel.Shutdown(cancel);
  1655. if (cancel?.Cancel == true)
  1656. {
  1657. return;
  1658. }
  1659. }
  1660. catch (Exception e)
  1661. {
  1662. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Error in UnloadWindow(): {0}\n{1}", e.Message, e.StackTrace));
  1663. }
  1664. CurrentPanel_Ticks = DateTime.MinValue;
  1665. CurrentPanel_Label = "";
  1666. CurrentPanel_Clicks = 0;
  1667. CurrentPanel_Keys = 0;
  1668. Title =
  1669. $"{CurrentPanel_Label} - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1670. if (CurrentTab != null)
  1671. {
  1672. var border = VisualUtils.EnumChildrenOfType(CurrentTab, typeof(Border)).LastOrDefault();
  1673. if (border != null)
  1674. {
  1675. ((Border)border).Background = new SolidColorBrush(Colors.Transparent);
  1676. ((Border)border).BorderBrush = new SolidColorBrush(Colors.Transparent);
  1677. }
  1678. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  1679. if (ReportsBar is not null)
  1680. {
  1681. ReportsBar.Items.Clear();
  1682. ReportsBar.Visibility = Visibility.Collapsed;
  1683. ReportsBar.IsLauncherVisible = false;
  1684. }
  1685. var ActionBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  1686. if (ActionBar is not null)
  1687. {
  1688. ActionBar.IsLauncherVisible = false;
  1689. foreach (var module in CurrentModules)
  1690. ActionBar.Items.Remove(module);
  1691. }
  1692. }
  1693. }
  1694. CurrentTab = null;
  1695. CurrentButton = null;
  1696. CurrentPanel = null;
  1697. ContentControl.Content = null;
  1698. }
  1699. private void SecondaryWindow_Click(object sender, RoutedEventArgs e)
  1700. {
  1701. if (CurrentPanel == null)
  1702. return;
  1703. var id = Guid.NewGuid();
  1704. var window = new Tuple<string, string, double, double, double, double>(
  1705. CurrentPanel.GetType().EntityName(),
  1706. CurrentPanel_Label,
  1707. Left + 100,
  1708. Top + 100,
  1709. Width - 200,
  1710. Height - 200
  1711. );
  1712. App.DatabaseSettings.SecondaryWindows[id] = window;
  1713. new LocalConfiguration<DatabaseSettings>(App.Profile).Save(App.DatabaseSettings);
  1714. _secondarywindows[id] = new SecondaryWindow(
  1715. id,
  1716. window.Item1,
  1717. window.Item2,
  1718. window.Item3,
  1719. window.Item4,
  1720. window.Item5,
  1721. window.Item6
  1722. );
  1723. _secondarywindows[id].Show();
  1724. }
  1725. private void RibbonWindow_Activated(object sender, EventArgs e)
  1726. {
  1727. }
  1728. private void RegisterModules(IProgress<string> progress)
  1729. {
  1730. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1731. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1732. foreach (var item in bar.Items)
  1733. Dispatcher.Invoke(() =>
  1734. {
  1735. var button = item as RibbonButton;
  1736. if (button != null && button.Label != "Refresh")
  1737. if (bar.Header.Equals("Actions"))
  1738. Modules.Register(button.Label);
  1739. });
  1740. //foreach (var item in _ribbon.BackStage.Items)
  1741. //{
  1742. // BackStageCommandButton button = item as BackStageCommandButton;
  1743. // if ((button != null) && (button.Header != "Log Out") && (button.Header != "Exit"))
  1744. // SecurityFactory.Register("System", button.Header, String.Format("System: Configure {0}", button.Header));
  1745. //}
  1746. }
  1747. private void SetVisibility(FrameworkElement button, bool visible)
  1748. {
  1749. var vResult = true;
  1750. var eResult = ClientFactory.UserGuid != Guid.Empty && visible;
  1751. button.Visibility = vResult && eResult ? Visibility.Visible : Visibility.Collapsed;
  1752. if (button is RibbonButton rb)
  1753. {
  1754. CustomModules.Register(rb.Label);
  1755. rb.IsEnabled = !OutstandingDailyReports(false);
  1756. }
  1757. }
  1758. private void SetVisibleIfEither(FrameworkElement separator, FrameworkElement[] left, FrameworkElement[] right)
  1759. {
  1760. var bLeft = false;
  1761. foreach (var button in left)
  1762. bLeft = bLeft || button.Visibility == Visibility.Visible;
  1763. var bRight = false;
  1764. foreach (var button in right)
  1765. bRight = bRight || button.Visibility == Visibility.Visible;
  1766. separator.Visibility = bLeft && bRight ? Visibility.Visible : Visibility.Collapsed;
  1767. }
  1768. private void SetVisibleIfAny(FrameworkElement separator, params FrameworkElement[] buttons)
  1769. {
  1770. var bVisible = false;
  1771. foreach (var button in buttons)
  1772. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1773. separator.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1774. }
  1775. private void SetTabVisibleIfAny(Fluent.RibbonTabItem tab, params FrameworkElement[] buttons)
  1776. {
  1777. var bVisible = false;
  1778. foreach (var button in buttons)
  1779. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1780. bVisible = bVisible || (SetupActions.GetValueOrDefault(tab)?.Count(x => x is SetupActionItem) ?? 0) > 3;
  1781. tab.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1782. }
  1783. private Fluent.RibbonGroupBox? FindRibbonBar(Fluent.RibbonTabItem tab, Func<Fluent.RibbonGroupBox, bool> predicate)
  1784. {
  1785. foreach (var group in tab.Groups)
  1786. {
  1787. if (group != null)
  1788. if (predicate.Invoke(group))
  1789. return group;
  1790. }
  1791. return null;
  1792. }
  1793. //private Style tabselected = null;
  1794. //private Style tabunselected = null;
  1795. //private Style Getstyle(bool selected)
  1796. //{
  1797. // if (tabunselected == null)
  1798. // {
  1799. // tabunselected = new Style(typeof(TabButton));
  1800. // Setter st1 = new Setter(TabButton.BackgroundProperty, new SolidColorBrush(Colors.Transparent));
  1801. // tabunselected.Setters.Add(st1);
  1802. // }
  1803. // if (tabselected == null)
  1804. // {
  1805. // tabselected = new Style(typeof(TabButton));
  1806. // Setter st1 = new Setter(TabButton.BackgroundProperty, new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0x9E, 0xDA, 0x11)));
  1807. // tabselected.Setters.Add(st1);
  1808. // }
  1809. // return selected ? tabselected : tabunselected;
  1810. //}
  1811. #region Button Event Handlers
  1812. private void DataEntry_Click(object sender, RoutedEventArgs e)
  1813. {
  1814. LoadWindow<DataEntryPanel>((Fluent.Button)sender);
  1815. }
  1816. private void Console_Click(object sender, RoutedEventArgs a)
  1817. {
  1818. if (_console is null)
  1819. {
  1820. _console = new Console();
  1821. _console.Closing += (o, args) => _console = null;
  1822. }
  1823. _console.Show();
  1824. }
  1825. private void Quotes_Checked(object sender, RoutedEventArgs e)
  1826. {
  1827. LoadWindow<QuotePanel>((Fluent.Button)sender);
  1828. }
  1829. private void Jobs_Checked(object sender, RoutedEventArgs e)
  1830. {
  1831. LoadWindow<JobPanel>((Fluent.Button)sender);
  1832. }
  1833. private void ProjectPlanner_Checked(object sender, RoutedEventArgs e)
  1834. {
  1835. LoadWindow<JobResourcePlannerPanel>((Fluent.Button)sender);
  1836. }
  1837. private void DesignManagement_Checked(object sender, RoutedEventArgs e)
  1838. {
  1839. LoadWindow<StagingPanel>((Fluent.Button)sender);
  1840. }
  1841. private void Service_Checked(object sender, RoutedEventArgs e)
  1842. {
  1843. MessageBox.Show("Not Implemented");
  1844. //LoadWindow<JobPanel>((RibbonButton)sender);
  1845. }
  1846. private void Tasks_Checked(object sender, RoutedEventArgs e)
  1847. {
  1848. //LoadWindow<KanbanPanel>((RibbonButton)sender);
  1849. LoadWindow<TaskPanel>((Fluent.Button)sender);
  1850. }
  1851. private void ManufacturingMenu_Checked(object sender, RoutedEventArgs e)
  1852. {
  1853. LoadWindow<ManufacturingPanel>((Fluent.Button)sender);
  1854. }
  1855. // private void Schedule_Checked(object sender, RoutedEventArgs e)
  1856. // {
  1857. // LoadWindow<SchedulePanel>((RibbonButton)sender);
  1858. // }
  1859. private void FactoryFloorButton_Click(object sender, RoutedEventArgs e)
  1860. {
  1861. LoadWindow<FactoryPanel>((Fluent.Button)sender);
  1862. }
  1863. private void DispatchMenu_Checked(object sender, RoutedEventArgs e)
  1864. {
  1865. LoadWindow<DispatchPanel>((Fluent.Button)sender);
  1866. }
  1867. private void ReadyToGoMenu_Checked(object sender, RoutedEventArgs e)
  1868. {
  1869. LoadWindow<ReadyToGoPanel>((Fluent.Button)sender);
  1870. }
  1871. private void Equipment_Checked(object sender, RoutedEventArgs e)
  1872. {
  1873. LoadWindow<EquipmentPanel>((Fluent.Button)sender);
  1874. }
  1875. private void Requisitions_Checked(object sender, RoutedEventArgs e)
  1876. {
  1877. LoadWindow<RequisitionPanel>((Fluent.Button)sender);
  1878. }
  1879. //private void Purchases_Checked(object sender, RoutedEventArgs e)
  1880. //{
  1881. // LoadWindow(PurchasesMenu, new PurchasesPanel());
  1882. //}
  1883. private void Timesheets_Checked(object sender, RoutedEventArgs e)
  1884. {
  1885. LoadWindow<TimesheetPanel>((Fluent.Button)sender);
  1886. }
  1887. private void Attendance_Checked(object sender, RoutedEventArgs e)
  1888. {
  1889. LoadWindow<AttendancePanel>((Fluent.Button)sender);
  1890. }
  1891. private void Maps_Checked(object sender, RoutedEventArgs e)
  1892. {
  1893. LoadWindow<MapsPanel>((Fluent.Button)sender);
  1894. }
  1895. private void FactorySetup_Click()
  1896. {
  1897. var list = new MasterList(typeof(ManufacturingFactory));
  1898. list.ShowDialog();
  1899. }
  1900. private void TemplateSetup_Click()
  1901. {
  1902. var list = new MasterList(typeof(ManufacturingTemplate), "Factory.Name", null, true);
  1903. list.ShowDialog();
  1904. }
  1905. private void RefreshMenu_Click(object sender, RoutedEventArgs e)
  1906. {
  1907. if (CurrentPanel != null)
  1908. CurrentPanel.Refresh();
  1909. }
  1910. private void MenuItem_Click(object sender, RoutedEventArgs e)
  1911. {
  1912. }
  1913. private void QuoteStatusButton_Click()
  1914. {
  1915. var list = new MasterList(typeof(QuoteStatus));
  1916. list.ShowDialog();
  1917. }
  1918. private void QuoteDesignSectionButton_Click()
  1919. {
  1920. var list = new MasterList(typeof(QuoteDesignSection));
  1921. list.ShowDialog();
  1922. }
  1923. private void JobStatusButton_Click()
  1924. {
  1925. var list = new MasterList(typeof(JobStatus));
  1926. list.ShowDialog();
  1927. }
  1928. private void FinancialStatusButton_Click()
  1929. {
  1930. var list = new MasterList(typeof(JobScopeStatus));
  1931. list.ShowDialog();
  1932. }
  1933. private void DrawingTemplatesButton_Click()
  1934. {
  1935. var list = new MasterList(typeof(DrawingTemplate));
  1936. list.ShowDialog();
  1937. }
  1938. private void ViewSetoutGroups()
  1939. {
  1940. var list = new MasterList(typeof(SetoutGroup));
  1941. list.ShowDialog();
  1942. }
  1943. private void RolesSetup_Click()
  1944. {
  1945. var list = new MasterList(typeof(Role));
  1946. list.ShowDialog();
  1947. }
  1948. private void GroupsSetup_Click()
  1949. {
  1950. var list = new MasterList(typeof(EmployeeGroup));
  1951. list.ShowDialog();
  1952. }
  1953. private void PositionsSetup_Click()
  1954. {
  1955. var list = new MasterList(typeof(EmployeePosition));
  1956. list.ShowDialog();
  1957. }
  1958. private void UserSetup_Click(object sender, RoutedEventArgs e)
  1959. {
  1960. LoadWindow<UserPanel>((Fluent.Button)sender);
  1961. //MasterList list = new MasterList(typeof(User));
  1962. //list.ShowDialog();
  1963. }
  1964. private void Employees_Click(object sender, RoutedEventArgs e)
  1965. {
  1966. LoadWindow<EmployeePanel>((Fluent.Button)sender);
  1967. //MasterList list = new MasterList(typeof(Employee));
  1968. //list.ShowDialog();
  1969. }
  1970. private void Customers_Click(object sender, RoutedEventArgs e)
  1971. {
  1972. var list = new MasterList(typeof(Customer));
  1973. list.ShowDialog();
  1974. }
  1975. private void Stickers_Click()
  1976. {
  1977. var list = new MasterList(typeof(WebSticker));
  1978. list.ShowDialog();
  1979. }
  1980. private void Trackers_Click(object sender, RoutedEventArgs e)
  1981. {
  1982. LoadWindow<GPSTrackers>((Fluent.Button)sender);
  1983. //MasterList list = new MasterList(typeof(GPSTracker));
  1984. //list.ShowDialog();
  1985. }
  1986. private void TrackerTypes_Click()
  1987. {
  1988. var list = new MasterList(typeof(GPSTrackerType));
  1989. list.ShowDialog();
  1990. }
  1991. private void DigitalKeys_Click()
  1992. {
  1993. var list = new MasterList(typeof(DigitalKey));
  1994. list.ShowDialog();
  1995. }
  1996. private void SupplierMenu_Click(object sender, RoutedEventArgs e)
  1997. {
  1998. var list = new MasterList(typeof(Supplier));
  1999. list.ShowDialog();
  2000. }
  2001. private void DeliveredOnSiteMenu_Checked(object sender, RoutedEventArgs e)
  2002. {
  2003. LoadWindow<DeliveredOnSitePanel>((Fluent.Button)sender);
  2004. }
  2005. private void DatabaseScripts_Click(object sender, RoutedEventArgs e)
  2006. {
  2007. var list = new MasterList(typeof(Script), "Section", null, true);
  2008. list.ShowDialog();
  2009. }
  2010. private void WebTemplates_Click(object sender, RoutedEventArgs e)
  2011. {
  2012. MasterList list = new MasterList(typeof(WebTemplate), null, null, true);
  2013. list.ShowDialog();
  2014. }
  2015. private void ActivityMenu_Click()
  2016. {
  2017. var list = new MasterList(typeof(Activity));
  2018. list.ShowDialog();
  2019. }
  2020. private void QualificationMenu_Click()
  2021. {
  2022. var list = new MasterList(typeof(Qualification));
  2023. list.ShowDialog();
  2024. }
  2025. private void RosterMenu_Click()
  2026. {
  2027. var list = new MasterList(typeof(EmployeeRoster));
  2028. list.ShowDialog();
  2029. }
  2030. private void Reports_LauncherClick(object sender, RoutedEventArgs e)
  2031. {
  2032. }
  2033. private void Products_Checked(object sender, RoutedEventArgs e)
  2034. {
  2035. LoadWindow<ProductsPanel>((Fluent.Button)sender);
  2036. }
  2037. private void StockLocations_Checked(object sender, RoutedEventArgs e)
  2038. {
  2039. LoadWindow<StockLocationPanel>((Fluent.Button)sender);
  2040. }
  2041. private void StockMovements_Checked(object sender, RoutedEventArgs e)
  2042. {
  2043. LoadWindow<StockMovementPanel>((Fluent.Button)sender);
  2044. }
  2045. private void StockSummaryButton_Clicked(object sender, RoutedEventArgs e)
  2046. {
  2047. LoadWindow<StockSummaryPanel>((Fluent.Button)sender);
  2048. }
  2049. private void ReservationManagementButton_Clicked(object sender, RoutedEventArgs e)
  2050. {
  2051. LoadWindow<JobRequisitionsPanel>((Fluent.Button)sender);
  2052. }
  2053. private void KitsMasterList_Click(object sender, RoutedEventArgs e)
  2054. {
  2055. LoadWindow<KitPanel>((Fluent.Button)sender);
  2056. }
  2057. private void CostSheetsMasterList_Click(object sender, RoutedEventArgs e)
  2058. {
  2059. LoadWindow<CostSheetPanel>((Fluent.Button)sender);
  2060. }
  2061. private void LeaveRequestsButton_Click(object sender, RoutedEventArgs e)
  2062. {
  2063. LoadWindow<LeaveRequestPanel>((Fluent.Button)sender);
  2064. }
  2065. private void MeetingsButton_Click(object sender, RoutedEventArgs e)
  2066. {
  2067. LoadWindow<MeetingPanel>((Fluent.Button)sender);
  2068. }
  2069. private void OrgChartButton_Click(object sender, RoutedEventArgs e)
  2070. {
  2071. LoadWindow<OrgChartPanel>((Fluent.Button)sender);
  2072. }
  2073. private void EquipmentGroupList_Click()
  2074. {
  2075. var list = new MasterList(typeof(EquipmentGroup));
  2076. list.ShowDialog();
  2077. }
  2078. private void KitConditionList_Click()
  2079. {
  2080. var list = new MasterList(typeof(KitCondition));
  2081. list.ShowDialog();
  2082. }
  2083. //private void KitGroupList_Click(object sender, RoutedEventArgs e)
  2084. //{
  2085. // MasterList list = new MasterList(typeof(KitGroup));
  2086. // list.ShowDialog();
  2087. //}
  2088. private void KitFormulaeList_Click()
  2089. {
  2090. var list = new MasterList(typeof(KitFormula));
  2091. list.ShowDialog();
  2092. }
  2093. private void CustomFields_Click(object sender, RoutedEventArgs e)
  2094. {
  2095. var list = new MasterList(typeof(CustomProperty), "Class", null, true);
  2096. list.ShowDialog();
  2097. }
  2098. private void CostSheetTypeList_Click()
  2099. {
  2100. var list = new MasterList(typeof(CostSheetType));
  2101. list.ShowDialog();
  2102. }
  2103. private void CostSheetBrandList_Click()
  2104. {
  2105. var list = new MasterList(typeof(CostSheetBrand));
  2106. list.ShowDialog();
  2107. }
  2108. private void CostSheetSectionList_Click()
  2109. {
  2110. var list = new MasterList(typeof(CostSheetSection));
  2111. list.ShowDialog();
  2112. }
  2113. private void ProductDimensionUnitsList_Click()
  2114. {
  2115. var list = new MasterList(typeof(ProductDimensionUnit));
  2116. list.ShowDialog();
  2117. }
  2118. private void SupplierList_Click(object sender, RoutedEventArgs e)
  2119. {
  2120. LoadWindow<SupplierPanel>((Fluent.Button)sender);
  2121. }
  2122. private void CustomerList_Click(object sender, RoutedEventArgs e)
  2123. {
  2124. LoadWindow<CustomerPanel>((Fluent.Button)sender);
  2125. }
  2126. private void ProductGroupsList_Click()
  2127. {
  2128. var list = new MasterList(typeof(ProductGroup));
  2129. list.ShowDialog();
  2130. }
  2131. private void ProductStylesList_Click()
  2132. {
  2133. var list = new MasterList(typeof(ProductStyle));
  2134. list.ShowDialog();
  2135. }
  2136. private void StockAreasList_Click()
  2137. {
  2138. var list = new MasterList(typeof(StockArea));
  2139. list.ShowDialog();
  2140. }
  2141. private void CostCentresList_Click()
  2142. {
  2143. var list = new MasterList(typeof(CostCentre));
  2144. list.ShowDialog();
  2145. }
  2146. private void GLCodesList_Click()
  2147. {
  2148. var list = new MasterList(typeof(GLCode));
  2149. list.ShowDialog();
  2150. }
  2151. private void CalendarButton_Click(object sender, RoutedEventArgs e)
  2152. {
  2153. LoadWindow<CalendarPanel>((Fluent.Button)sender);
  2154. }
  2155. private void EmployeePlannerButton_Click(object sender, RoutedEventArgs e)
  2156. {
  2157. LoadWindow<EmployeeResourcePlannerPanel>((Fluent.Button)sender);
  2158. }
  2159. private void InvoiceList_Click(object sender, RoutedEventArgs e)
  2160. {
  2161. LoadWindow<InvoicePanel>((Fluent.Button)sender);
  2162. }
  2163. private void ReceiptList_Click(object sender, RoutedEventArgs e)
  2164. {
  2165. LoadWindow<CustomerReceipts>((Fluent.Button)sender);
  2166. }
  2167. private void PaymentsList_Click(object sender, RoutedEventArgs e)
  2168. {
  2169. LoadWindow<SupplierPayments>((Fluent.Button)sender);
  2170. }
  2171. private void BillsList_Click(object sender, RoutedEventArgs e)
  2172. {
  2173. LoadWindow<SupplierBillPanel>((Fluent.Button)sender);
  2174. }
  2175. private void PurchasesList_Click(object sender, RoutedEventArgs e)
  2176. {
  2177. LoadWindow<SupplierPurchaseOrderPanel>((Fluent.Button)sender);
  2178. }
  2179. private void ReceiptTypeList_Click()
  2180. {
  2181. var list = new MasterList(typeof(ReceiptType));
  2182. list.ShowDialog();
  2183. }
  2184. private void PaymentTypeList_Click()
  2185. {
  2186. var list = new MasterList(typeof(PaymentType));
  2187. list.ShowDialog();
  2188. }
  2189. private void TaxCodeList_Click()
  2190. {
  2191. var list = new MasterList(typeof(TaxCode));
  2192. list.ShowDialog();
  2193. }
  2194. private void ContactTypeList_Click()
  2195. {
  2196. var list = new MasterList(typeof(ContactType));
  2197. list.ShowDialog();
  2198. }
  2199. private void EmployeeTeamsButton_Click()
  2200. {
  2201. var list = new MasterList(typeof(Team));
  2202. list.ShowDialog();
  2203. }
  2204. // private void RostersButton_Click()
  2205. // {
  2206. // var list = new MasterList(typeof(Roster));
  2207. // list.ShowDialog();
  2208. // }
  2209. private void OvertimeRulesButton_Click()
  2210. {
  2211. var list = new MasterList(typeof(OvertimeRule));
  2212. list.ShowDialog();
  2213. }
  2214. private void OvertimeButton_Click()
  2215. {
  2216. var list = new MasterList(typeof(Overtime));
  2217. list.ShowDialog();
  2218. }
  2219. private void StandardLeaveButton_Click()
  2220. {
  2221. var list = new MasterList(typeof(StandardLeave));
  2222. list.ShowDialog();
  2223. }
  2224. private void SecurityGroupsButton_Click()
  2225. {
  2226. var list = new MasterList(typeof(SecurityGroup));
  2227. list.ShowDialog();
  2228. Security.Reset();
  2229. }
  2230. private void ImportDatabase_Click(object sender, RoutedEventArgs e)
  2231. {
  2232. Utility.DuplicateDatabase();
  2233. }
  2234. private void DeliveriesButton_Click(object sender, RoutedEventArgs e)
  2235. {
  2236. LoadWindow<DeliveryPanel>((Fluent.Button)sender);
  2237. }
  2238. private void TaskTypesButton_OnClick(object sender, RoutedEventArgs e)
  2239. {
  2240. var list = new MasterList(typeof(KanbanType));
  2241. list.ShowDialog();
  2242. }
  2243. private void TrolleySetup_Click()
  2244. {
  2245. var list = new MasterList(typeof(ManufacturingTrolley));
  2246. list.ShowDialog();
  2247. }
  2248. private void LostTimeSetup_Click()
  2249. {
  2250. var list = new MasterList(typeof(ManufacturingLostTime));
  2251. list.ShowDialog();
  2252. }
  2253. private void FactoryAllocationButton_Click(object sender, RoutedEventArgs e)
  2254. {
  2255. LoadWindow<ManufacturingAllocationPanel>((Fluent.Button)sender);
  2256. }
  2257. private void Messages_Checked(object sender, RoutedEventArgs e)
  2258. {
  2259. LoadWindow<NotificationPanel>((Fluent.Button)sender);
  2260. }
  2261. private void DatabaseActivityButton_Click(object sender, RoutedEventArgs e)
  2262. {
  2263. LoadWindow<DatabaseActivityDashboard>((Fluent.Button)sender);
  2264. }
  2265. private void FactoryProductivityButton_Click(object sender, RoutedEventArgs e)
  2266. {
  2267. LoadWindow<FactoryProductivityDashboard>((Fluent.Button)sender);
  2268. }
  2269. private void TemplateAnalysisButton_Click(object sender, RoutedEventArgs e)
  2270. {
  2271. LoadWindow<ManufacturingTemplateAnalysis>((Fluent.Button)sender);
  2272. }
  2273. private void FactoryAnalysisButton_Click(object sender, RoutedEventArgs e)
  2274. {
  2275. LoadWindow<FactoryFloorAnalysis>((Fluent.Button)sender);
  2276. }
  2277. private void UserActivityButton_Click(object sender, RoutedEventArgs e)
  2278. {
  2279. LoadWindow<UserActivity>((Fluent.Button)sender);
  2280. }
  2281. private void DigitalFormsButton_Click(object sender, RoutedEventArgs e)
  2282. {
  2283. LoadWindow<QADashboard>((Fluent.Button)sender);
  2284. }
  2285. private void QuickStatus_Click(object sender, RoutedEventArgs e)
  2286. {
  2287. LoadWindow<WidgetDashboard>((Fluent.Button)sender);
  2288. }
  2289. private void ConsignmentButton_Click(object sender, RoutedEventArgs e)
  2290. {
  2291. LoadWindow<ConsignmentsPanel>((Fluent.Button)sender);
  2292. }
  2293. private void ConsignmentTypesButton_Click()
  2294. {
  2295. var list = new MasterList(typeof(ConsignmentType));
  2296. list.ShowDialog();
  2297. }
  2298. private void PurchaseOrderCategoriesButton_Click()
  2299. {
  2300. var list = new MasterList(typeof(PurchaseOrderCategory));
  2301. list.ShowDialog();
  2302. }
  2303. private void DeliveryTypesButton_Click()
  2304. {
  2305. var list = new MasterList(typeof(DeliveryType));
  2306. list.ShowDialog();
  2307. }
  2308. private void ConfigureModules_Click(object sender, RoutedEventArgs e)
  2309. {
  2310. var window = new ModuleConfigurationWindow(DbFactory.Provider.URL);
  2311. if (window.ShowDialog() == true)
  2312. MessageBox.Show("These changes will be applied when the database is restarted!");
  2313. }
  2314. //private void NotificationsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
  2315. //{
  2316. // if (NotificationsList.SelectedIndex < 0)
  2317. // return;
  2318. // var editors = NotificationsList.FindVisualChildren<InABox.DynamicGrid.ExtendedRichTextEditor>().ToArray();
  2319. // var selected = editors[NotificationsList.SelectedIndex];
  2320. // selected.Text = (String)selected.Tag; //NotificationsList.SelectedIndex.ToString();
  2321. //}
  2322. //private void ViewNotification_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
  2323. //{
  2324. // Notification notification = (sender as Label).Tag as Notification;
  2325. // NotificationDetails details = new NotificationDetails(notification);
  2326. // details.ShowDialog();
  2327. // ReloadNotifications();
  2328. //}
  2329. private void DailyReport_Checked(object sender, RoutedEventArgs e)
  2330. {
  2331. LoadWindow<DailyReport>((Fluent.Button)sender);
  2332. }
  2333. private void Library_Click(object sender, RoutedEventArgs e)
  2334. {
  2335. Process.Start(
  2336. new ProcessStartInfo
  2337. {
  2338. FileName = App.DatabaseSettings.LibraryLocation,
  2339. UseShellExecute = true,
  2340. Verb = "open"
  2341. }
  2342. );
  2343. }
  2344. private void SendNotificationClick(object sender, RoutedEventArgs e)
  2345. {
  2346. var form = new NotificationForm { Description = "" };
  2347. if (form.ShowDialog() == true)
  2348. ReloadNotifications();
  2349. }
  2350. private void CompanyInformation_Click(object sender, RoutedEventArgs e)
  2351. {
  2352. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  2353. if (info == null)
  2354. info = new CompanyInformation();
  2355. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  2356. }
  2357. private void StockWarehouseList_Click()
  2358. {
  2359. var list = new MasterList(typeof(StockWarehouse));
  2360. list.ShowDialog();
  2361. }
  2362. private void Dashboards_Checked(object sender, RoutedEventArgs e)
  2363. {
  2364. LoadWindow<UtilityDashboard>((Fluent.Button)sender);
  2365. }
  2366. private void QuoteDiagramSymbols_Checked()
  2367. {
  2368. var list = new MasterList(typeof(QuoteDiagramSymbol), "Section.Name");
  2369. list.ShowDialog();
  2370. QuoteDiagramSymbolCache.Refresh();
  2371. }
  2372. private void QuoteDiagramSymbolTypes_Checked()
  2373. {
  2374. var list = new MasterList(typeof(QuoteDiagramSymbolSection));
  2375. list.ShowDialog();
  2376. QuoteDiagramSymbolCache.Refresh();
  2377. }
  2378. private void QuoteTakeOffUnits_Click()
  2379. {
  2380. var list = new MasterList(typeof(QuoteTakeOffUnit));
  2381. list.ShowDialog();
  2382. }
  2383. private void JobDocumentMileStoneButton_OnClick()
  2384. {
  2385. var list = new MasterList(typeof(JobDocumentSetMileStoneType));
  2386. list.ShowDialog();
  2387. }
  2388. // private void JobDocumentTagButton_OnClick()
  2389. // {
  2390. // var list = new MasterList(typeof(JobDocumentSetTag));
  2391. // list.ShowDialog();
  2392. // }
  2393. private void Setup_Click(object sender, RoutedEventArgs e)
  2394. {
  2395. var tab = _ribbon.SelectedTabItem;
  2396. if (tab is null)
  2397. return;
  2398. var items = new List<ISetupActionItem>();
  2399. if (SetupActions.TryGetValue(tab, out var actions))
  2400. {
  2401. foreach (var action in actions)
  2402. {
  2403. items.Add(action);
  2404. }
  2405. }
  2406. if (PanelSetupActions.Any())
  2407. {
  2408. AddSetupSeparator(items);
  2409. foreach (var action in PanelSetupActions)
  2410. {
  2411. items.Add(action);
  2412. }
  2413. }
  2414. items = items.Where(x => x is not SetupActionItem setup || setup.IsVisible()).ToList();
  2415. var menu = new ContextMenu();
  2416. for (var i = 0; i < items.Count; ++i)
  2417. {
  2418. var item = items[i];
  2419. if (item is SetupActionItem setupAction)
  2420. {
  2421. menu.AddItem(setupAction.Name, setupAction.Image, setupAction.Action);
  2422. }
  2423. else if (item is SetupSeparator && i > 0 && i < items.Count - 1)
  2424. {
  2425. var last = items[i - 1];
  2426. if (last is not SetupSeparator)
  2427. menu.AddSeparator();
  2428. }
  2429. }
  2430. if (CurrentPanel?.GetType().HasInterface(typeof(IPropertiesPanel<>)) == true && Security.IsAllowed<CanConfigurePanels>())
  2431. {
  2432. var securityInterface = CurrentPanel?.GetType().GetInterfaceDefinition(typeof(IPropertiesPanel<,>));
  2433. var canConfigure = false;
  2434. if (securityInterface is not null)
  2435. {
  2436. var token = securityInterface.GenericTypeArguments[1];
  2437. canConfigure = Security.IsAllowed(token);
  2438. }
  2439. else
  2440. {
  2441. canConfigure = Security.IsAllowed<CanConfigurePanels>();
  2442. }
  2443. if (canConfigure)
  2444. {
  2445. menu.AddItem("Configure Panel", PRSDesktop.Resources.edit, ConfigurePanel_Click);
  2446. }
  2447. }
  2448. if (menu.Items.Count == 0)
  2449. {
  2450. menu.AddItem("No Items", null, null, false);
  2451. }
  2452. menu.IsOpen = true;
  2453. }
  2454. private void InitializePanelProperties(IBasePanel panel)
  2455. {
  2456. var propertiesInterface = panel.GetType().GetInterfaceDefinition(typeof(IPropertiesPanel<>));
  2457. if (propertiesInterface is not null)
  2458. {
  2459. var propertiesType = propertiesInterface.GenericTypeArguments[0];
  2460. var method = typeof(MainWindow)
  2461. .GetMethod(nameof(InitializePanelPropertiesGeneric), BindingFlags.NonPublic | BindingFlags.Instance)
  2462. ?.MakeGenericMethod(panel.GetType(), propertiesType)
  2463. .Invoke(this, new object?[] { panel });
  2464. }
  2465. }
  2466. private void InitializePanelPropertiesGeneric<TPanel, TProperties>(TPanel panel)
  2467. where TPanel : IPropertiesPanel<TProperties>
  2468. where TProperties : BaseObject, IGlobalConfigurationSettings, new()
  2469. {
  2470. panel.Properties = LoadPanelProperties<TPanel, TProperties>();
  2471. }
  2472. private TProperties LoadPanelProperties<TPanel, TProperties>()
  2473. where TPanel : IPropertiesPanel<TProperties>
  2474. where TProperties : BaseObject, IGlobalConfigurationSettings, new()
  2475. {
  2476. var config = new GlobalConfiguration<TProperties>();
  2477. return config.Load();
  2478. }
  2479. private void SavePanelProperties<TPanel, TProperties>(TProperties properties)
  2480. where TPanel : IPropertiesPanel<TProperties>
  2481. where TProperties : BaseObject, IGlobalConfigurationSettings, new()
  2482. {
  2483. var config = new GlobalConfiguration<TProperties>();
  2484. config.Save(properties);
  2485. }
  2486. private void EditPanelProperties<TPanel, TProperties>()
  2487. where TPanel : IPropertiesPanel<TProperties>
  2488. where TProperties : BaseObject, IGlobalConfigurationSettings, new()
  2489. {
  2490. var properties = LoadPanelProperties<TPanel, TProperties>();
  2491. bool result;
  2492. if(DynamicGridUtils.TryFindDynamicGrid(typeof(DynamicGrid<>), typeof(TProperties), out var gridType))
  2493. {
  2494. var grid = (Activator.CreateInstance(gridType) as DynamicGrid<TProperties>)!;
  2495. result = grid.EditItems(new TProperties[] { properties });
  2496. }
  2497. else
  2498. {
  2499. var editor = new DynamicEditorForm(typeof(TProperties));
  2500. editor.Items = new BaseObject[] { properties };
  2501. result = editor.ShowDialog() == true;
  2502. }
  2503. if (result)
  2504. {
  2505. SavePanelProperties<TPanel, TProperties>(properties);
  2506. }
  2507. }
  2508. private void ConfigurePanel_Click()
  2509. {
  2510. if (CurrentPanel is null) return;
  2511. var propertiesInterface = CurrentPanel.GetType().GetInterfaceDefinition(typeof(IPropertiesPanel<>))!;
  2512. var propertiesType = propertiesInterface.GenericTypeArguments[0];
  2513. var method = typeof(MainWindow)
  2514. .GetMethod(nameof(EditPanelProperties), BindingFlags.NonPublic | BindingFlags.Instance)
  2515. ?.MakeGenericMethod(CurrentPanel.GetType(), propertiesType)
  2516. .Invoke(this, Array.Empty<object?>());
  2517. }
  2518. private void StartForm<TEntityForm, TEntity, TEntityLink>(DigitalForm form)
  2519. where TEntityForm : EntityForm<TEntity, TEntityLink, TEntityForm>, new()
  2520. where TEntity : Entity, new()
  2521. where TEntityLink : EntityLink<TEntity>, new()
  2522. {
  2523. var entityForm = new TEntityForm();
  2524. entityForm.Form.ID = form.ID;
  2525. entityForm.Form.Description = form.Description;
  2526. var entity = DFUtils.NewEntity<TEntityForm, TEntity, TEntityLink>(form);
  2527. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel, entity))
  2528. {
  2529. dataModel.Update(null);
  2530. }
  2531. }
  2532. private void Forms_Click(object sender, RoutedEventArgs e)
  2533. {
  2534. var select = new MultiSelectDialog<DigitalForm>(
  2535. Filter<DigitalForm>.And(
  2536. LookupFactory.DefineFilter<KanbanForm, DigitalForm>(Array.Empty<KanbanForm>()),
  2537. new Filter<DigitalForm>(x => x.ID).InQuery(
  2538. new Filter<EmployeeDigitalForm>(x => x.Employee.ID).IsEqualTo(App.EmployeeID),
  2539. x => x.Form.ID)),
  2540. LookupFactory.DefineColumns<DigitalForm>()
  2541. .Add(x => x.Description),
  2542. false);
  2543. if (select.ShowDialog() == true)
  2544. {
  2545. var digitalForm = select.Data().Rows.FirstOrDefault()?.ToObject<DigitalForm>();
  2546. if (digitalForm is not null)
  2547. {
  2548. StartForm<KanbanForm, Kanban, KanbanLink>(digitalForm);
  2549. }
  2550. };
  2551. }
  2552. #endregion
  2553. private bool OutstandingDailyReports(bool refresh)
  2554. {
  2555. if (!Security.IsAllowed<CanViewDailyReports>() || Security.IsAllowed<BypassOutstandingDailyReports>())
  2556. return false;
  2557. if (refresh)
  2558. RefreshTimeSheets();
  2559. if (_timesheets == null)
  2560. return false;
  2561. return _timesheets.Rows.Any(r => r.Get<TimeSheet, DateTime>(c => c.Date).Date < DateTime.Today);
  2562. }
  2563. private void ShutDownTransport()
  2564. {
  2565. if (_transport != null)
  2566. {
  2567. _transport.OnClose -= TransportConnectionLost;
  2568. if (_transport.IsConnected())
  2569. _transport.Disconnect();
  2570. _transport = null;
  2571. }
  2572. }
  2573. private void Window_Unloaded(object sender, RoutedEventArgs e)
  2574. {
  2575. ShutDownTransport();
  2576. }
  2577. private void RibbonWindow_Closed(object sender, EventArgs e)
  2578. {
  2579. ShutDownTransport();
  2580. DisconnectRecorderNotes();
  2581. Application.Current.Shutdown();
  2582. }
  2583. //private bool _closingFromSystemMenu = false;
  2584. private void Window_Closing(object sender, CancelEventArgs e)
  2585. {
  2586. /*if (!_closingFromSystemMenu && !CoreUtils.GetVersion().Equals("???"))
  2587. {
  2588. WindowState = WindowState.Minimized;
  2589. e.Cancel = true;
  2590. return;
  2591. }*/
  2592. if (CurrentPanel != null)
  2593. {
  2594. CurrentPanel.Shutdown(e);
  2595. if (e.Cancel)
  2596. {
  2597. return;
  2598. }
  2599. }
  2600. CurrentPanel = null;
  2601. App.IsClosing = true;
  2602. FinalizeAutoTimesheet();
  2603. if (!CoreUtils.GetVersion().Equals("???"))
  2604. scheduler.Stop();
  2605. CurrentTab = null;
  2606. UpdateRibbonColors();
  2607. if (!CoreUtils.GetVersion().Equals("???"))
  2608. if (station.ID != Guid.Empty)
  2609. ExecuteLogout();
  2610. ShutDownTransport();
  2611. }
  2612. private void FinalizeAutoTimesheet()
  2613. {
  2614. if (Security.IsAllowed<AutoGenerateTimesheet>())
  2615. {
  2616. var check = new Client<TimeSheet>().Query(
  2617. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today).And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID).And(x => x.Finish)
  2618. .IsEqualTo(TimeSpan.Zero)
  2619. );
  2620. if (check.Rows.Any())
  2621. {
  2622. var ts = check.Rows.First().ToObject<TimeSheet>();
  2623. if (DateTime.Now.TimeOfDay < ts.Start.Add(new TimeSpan(0, 2, 0)))
  2624. {
  2625. new Client<TimeSheet>().Delete(ts, "Deleting Auto TimeSheet because TimeBench Bypass is enabled", (o, ex) => { });
  2626. }
  2627. else
  2628. {
  2629. ts.Finish = DateTime.Now.TimeOfDay;
  2630. new Client<TimeSheet>().Save(ts, "Clocking off Auto Timesheet because Timesheet Bypass is enabled", (o, ex) => { });
  2631. }
  2632. }
  2633. }
  2634. }
  2635. #region Notifications + Heartbeat
  2636. private void ReceiveNotification(Notification notification)
  2637. {
  2638. if (Security.CanView<Notification>())
  2639. {
  2640. Notifications.AddNotification(notification);
  2641. }
  2642. if (CurrentPanel is NotificationPanel panel)
  2643. {
  2644. panel.AddNotification(notification);
  2645. }
  2646. }
  2647. private void Notifications_Tick(object? sender, EventArgs e)
  2648. {
  2649. if (ClientFactory.UserGuid != Guid.Empty)
  2650. {
  2651. try
  2652. {
  2653. ReloadNotifications();
  2654. }
  2655. catch (Exception err)
  2656. {
  2657. Logger.Send(LogType.Error, ClientFactory.UserID,
  2658. string.Format("Exception in Notifications_Tick:ReloadNotifications() {0}\n{1}", err.Message, err.StackTrace));
  2659. }
  2660. Heartbeat(DateTime.Now - CurrentPanel_Ticks, false);
  2661. try
  2662. {
  2663. CheckIsLoggedOn();
  2664. }
  2665. catch (Exception err2)
  2666. {
  2667. Logger.Send(LogType.Error, ClientFactory.UserID,
  2668. string.Format("Exception in Notifications_Tick:CheckIsLoggedOn() {0}\n{1}", err2.Message, err2.StackTrace));
  2669. }
  2670. }
  2671. //else
  2672. //{
  2673. // Logger.Send(LogType.Information, ClientFactory.UserID, "Notifications_Tick: ClientFactory.UserGuid is empty");
  2674. //}
  2675. }
  2676. private void CheckIsLoggedOn()
  2677. {
  2678. if (CoreUtils.GetVersion().Equals("???"))
  2679. return;
  2680. var bLogout = false;
  2681. if (!Security.IsAllowed<CanBypassTimeBench>())
  2682. if (!IsClockedOn())
  2683. {
  2684. Logger.Send(LogType.Information, ClientFactory.UserID, "User is no longer clocked in!");
  2685. bLogout = true;
  2686. Dispatcher.Invoke(() => { Logout(); });
  2687. }
  2688. if (!bLogout)
  2689. new Client<Login>().Query(
  2690. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  2691. new Columns<Login>(x => x.StationID),
  2692. null,
  2693. (o, e) =>
  2694. {
  2695. if (e is RemoteException remote)
  2696. {
  2697. if (remote.Status == StatusCode.Unauthenticated)
  2698. {
  2699. Logger.Send(LogType.Information, ClientFactory.UserID, "User has been logged out");
  2700. Dispatcher.Invoke(() =>
  2701. {
  2702. Logout("You have been logged out due to inactivity");
  2703. });
  2704. }
  2705. else
  2706. {
  2707. Logger.Send(LogType.Information, ClientFactory.UserID, CoreUtils.FormatException(remote));
  2708. }
  2709. }
  2710. else if (e is not null)
  2711. {
  2712. Logger.Send(LogType.Information, ClientFactory.UserID, CoreUtils.FormatException(e));
  2713. }
  2714. else if (o is not null)
  2715. {
  2716. var row = o.Rows.FirstOrDefault();
  2717. if (row == null)
  2718. {
  2719. station.ID = Guid.Empty;
  2720. new Client<Login>().Save(station, "", (o1, e1) => { });
  2721. }
  2722. else if (!row.Get<Login, string>(c => c.StationID).Equals(station.StationID))
  2723. {
  2724. Logger.Send(LogType.Information, ClientFactory.UserID, "User logged in somewhere else!");
  2725. bLogout = true;
  2726. Dispatcher.Invoke(() => { Logout(); });
  2727. }
  2728. }
  2729. }
  2730. );
  2731. }
  2732. private void Heartbeat(TimeSpan time, bool closing)
  2733. {
  2734. //Task.Run(() =>
  2735. //{
  2736. try
  2737. {
  2738. bool IsClockedOn = this.IsClockedOn();
  2739. if (IsClockedOn)
  2740. {
  2741. if ((_kanbantrackingassignment != null) && (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay))
  2742. {
  2743. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2744. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2745. }
  2746. if (Security.IsAllowed<MonitorApplicationWindows>())
  2747. {
  2748. if (ActivityHistory == null)
  2749. ActivityHistory = new LocalConfiguration<DailyActivityHistory>().Load();
  2750. var appname = OpenWindowGetter.GetActiveWindowProcess();
  2751. var title = OpenWindowGetter.GetActiveWindowTitle();
  2752. ActivityHistory.Activities[DateTime.Now] = (!string.IsNullOrWhiteSpace(appname) ? appname.Trim() + " - " : "") + title;
  2753. new LocalConfiguration<DailyActivityHistory>().Save(ActivityHistory);
  2754. }
  2755. }
  2756. //Logger.Send(LogType.Information, "", string.Format("Heartbeat: {0:hh\\:mm}{1}", time, closing ? " (closing)" : ""));
  2757. if (!closing && time.TotalMinutes < 5)
  2758. return;
  2759. CurrentPanel_Ticks = DateTime.Now;
  2760. if (CurrentPanel != null)
  2761. {
  2762. //Logger.Send(LogType.Information, "", string.Format("Heartbeat: {0}", CurrentPanel_Label));
  2763. if (ClientFactory.IsSupported<ModuleTracking>())
  2764. {
  2765. var keys = CurrentPanel_Keys;
  2766. CurrentPanel_Keys = 0;
  2767. var clicks = CurrentPanel_Clicks;
  2768. CurrentPanel_Clicks = 0;
  2769. var tracking = new ModuleTracking
  2770. {
  2771. Date = DateTime.Today,
  2772. Module = CurrentPanel_Label,
  2773. Clicks = clicks,
  2774. Keys = keys,
  2775. ActiveTime = clicks + keys > 0 ? time : new TimeSpan(),
  2776. IdleTime = clicks + keys == 0 ? time : new TimeSpan()
  2777. };
  2778. tracking.User.ID = ClientFactory.UserGuid;
  2779. new Client<ModuleTracking>().Save(tracking, "", (mt, ex) => { });
  2780. }
  2781. CurrentPanel.Heartbeat(time);
  2782. }
  2783. }
  2784. catch (Exception err)
  2785. {
  2786. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Exception in Heartbeat: {0}\n{1}", err.Message, err.StackTrace));
  2787. }
  2788. //});
  2789. }
  2790. private void Notifications_Changed(object sender)
  2791. {
  2792. if (Notifications.IsActive)
  2793. {
  2794. Notifications.Visibility = Visibility.Visible;
  2795. DockingGrid.ColumnDefinitions[1].Width = new GridLength(4, GridUnitType.Pixel);
  2796. DockingGrid.ColumnDefinitions[2].Width = Equals(0.0, DockingGrid.ColumnDefinitions[2].Width.Value)
  2797. ? new GridLength(300, GridUnitType.Pixel)
  2798. : DockingGrid.ColumnDefinitions[2].Width;
  2799. }
  2800. else
  2801. {
  2802. Notifications.Visibility = Visibility.Collapsed;
  2803. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  2804. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  2805. }
  2806. }
  2807. private void ReloadNotifications()
  2808. {
  2809. if (Security.CanView<Notification>())
  2810. Notifications.Refresh();
  2811. if (!NotificationsWatchDog.IsEnabled)
  2812. {
  2813. //Logger.Send(LogType.Information, ClientFactory.UserID, "Enabling Heartbeat");
  2814. NotificationsWatchDog.IsEnabled = true;
  2815. }
  2816. }
  2817. #endregion
  2818. private void RibbonWindow_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  2819. {
  2820. if (CurrentPanel != null)
  2821. CurrentPanel_Clicks++;
  2822. }
  2823. private void RibbonWindow_PreviewKeyUp(object sender, KeyEventArgs e)
  2824. {
  2825. if (CurrentPanel != null)
  2826. CurrentPanel_Keys++;
  2827. }
  2828. #region Recording
  2829. //private IntPtr myHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  2830. //{
  2831. // switch (msg)
  2832. // {
  2833. // case 0x100:
  2834. // if (_subject != null)
  2835. // {
  2836. // _recorder.Stop();
  2837. // pausestarted = DateTime.Now;
  2838. // _subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2839. // }
  2840. // break;
  2841. // default:
  2842. // messages.TryGetValue(msg, out int value);
  2843. // messages[msg] = value + 1;
  2844. // break;
  2845. // }
  2846. // return IntPtr.Zero;
  2847. //}
  2848. private void RecordScreenButton_Click(object sender, RoutedEventArgs e)
  2849. {
  2850. ToggleRecording();
  2851. }
  2852. private bool ToggleRecording()
  2853. {
  2854. if (!Security.IsAllowed<CanRecordScreen>())
  2855. return true;
  2856. if (_recorder is null)
  2857. {
  2858. var windowInteropHelper = new WindowInteropHelper(this);
  2859. var screen = Screen.FromHandle(windowInteropHelper.Handle);
  2860. _screenleft = screen.WorkingArea.Left;
  2861. _screentop = screen.WorkingArea.Top;
  2862. _screenwidth = screen.WorkingArea.Width;
  2863. _screenheight = screen.WorkingArea.Height;
  2864. //VIDEO_WIDTH = _screenwidth;
  2865. //VIDEO_HEIGHT = _screenheight;
  2866. //SetupJPEGEncoder();
  2867. messages.Clear();
  2868. _bitmaps.Clear();
  2869. ConnectToRecordNotes();
  2870. StartAudio();
  2871. _recorder = new DispatcherTimer();
  2872. _recorder.Tick += (timer, args) => { TakeScreenShot(); };
  2873. _recorder.Interval = TimeSpan.FromMilliseconds(1000 / FRAMES_PER_SECOND);
  2874. _recorder.Start();
  2875. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsBitmapImage();
  2876. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2877. RecordingNotesButton.Visibility = Visibility.Visible;
  2878. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2879. AudioRecordingButton.Visibility = Visibility.Visible;
  2880. }
  2881. else
  2882. {
  2883. using (new WaitCursor())
  2884. {
  2885. StopRecording();
  2886. _recorder.Stop();
  2887. _recorder = null;
  2888. DisconnectRecorderNotes();
  2889. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  2890. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2891. RecordingNotesButton.Visibility = Visibility.Hidden;
  2892. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2893. AudioRecordingButton.Visibility = Visibility.Hidden;
  2894. var filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos),
  2895. string.Format("PRS Screen Recording {0:yyyy-MM-dd hh-mm-ss-ff}.avi", DateTime.Now));
  2896. ProcessScreenShots(filename);
  2897. }
  2898. }
  2899. return true;
  2900. }
  2901. private void StopRecording()
  2902. {
  2903. try
  2904. {
  2905. _audio?.StopRecording();
  2906. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2907. }
  2908. catch (Exception e)
  2909. {
  2910. Logger.Send(LogType.Error, "", string.Format("Unable to stop Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2911. }
  2912. }
  2913. private void StartAudio()
  2914. {
  2915. _audioMuted = true;
  2916. _audioStream = new MemoryStream();
  2917. _audio = new WaveIn
  2918. {
  2919. DeviceNumber = 0,
  2920. WaveFormat = new WaveFormat(44100, 16, 2)
  2921. };
  2922. _audio.DataAvailable += (o, e) =>
  2923. {
  2924. var buf = _audioMuted ? new byte[e.BytesRecorded] : e.Buffer;
  2925. _audioStream.Write(buf, 0, e.BytesRecorded);
  2926. };
  2927. try
  2928. {
  2929. _audio.StartRecording();
  2930. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2931. }
  2932. catch (Exception e)
  2933. {
  2934. Logger.Send(LogType.Error, "", string.Format("Unable to start Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2935. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2936. }
  2937. }
  2938. private bool ToggleRecordingAudio()
  2939. {
  2940. if (!Security.IsAllowed<CanRecordScreen>())
  2941. return true;
  2942. if (_recorder != null)
  2943. {
  2944. _audioMuted = !_audioMuted;
  2945. AudioRecordingStatus.Source = _audioMuted
  2946. ? PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage()
  2947. : PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2948. }
  2949. return true;
  2950. }
  2951. private void DisconnectRecorderNotes()
  2952. {
  2953. if (_client != null)
  2954. {
  2955. _client.WriteAsync("QUIT");
  2956. _client.StopAsync();
  2957. _client = null;
  2958. }
  2959. }
  2960. private void ConnectToRecordNotes()
  2961. {
  2962. var filename = Debugger.IsAttached
  2963. ? "c:\\development\\comal\\prsrecordingnotes\\bin\\debug\\prsrecordingnotes.exe"
  2964. : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "recordingnotes", "prsrecordingnotes.exe");
  2965. Logger.Send(LogType.Information, "", "Recording Notes: " + filename);
  2966. _recordingnotes = Process.Start(filename);
  2967. //PipeSecurity sec = new System.IO.Pipes.PipeSecurity();
  2968. //sec.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));
  2969. _client = new PipeServer<string>("PRSScreenRecorder"); //, sec);
  2970. _client.ClientConnected += (o, args) => args.Connection.WriteAsync("Connected to PRSScreenRecorder");
  2971. _client.MessageReceived += (o, args) =>
  2972. {
  2973. if (string.Equals(args.Message, "RESUME"))
  2974. Dispatcher.Invoke(() =>
  2975. {
  2976. _audio?.StartRecording();
  2977. totalpauses += DateTime.Now - pausestarted;
  2978. _recorder?.Start();
  2979. Activate();
  2980. Focus();
  2981. });
  2982. };
  2983. _client.StartAsync();
  2984. }
  2985. private bool ShowRecordingNotes()
  2986. {
  2987. if (_recorder != null)
  2988. {
  2989. _audio?.StopRecording();
  2990. _recorder.Stop();
  2991. pausestarted = DateTime.Now;
  2992. _client?.WriteAsync("EDIT");
  2993. //_subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2994. }
  2995. return true;
  2996. }
  2997. private void TakeScreenShot()
  2998. {
  2999. using (var bmp = new ScreenCapture().CaptureScreen(_screenleft, _screentop, _screenwidth, _screenheight))
  3000. {
  3001. var cursor = PointToScreen(Mouse.GetPosition(this));
  3002. using (var g = Graphics.FromImage(bmp))
  3003. {
  3004. var brush = new SolidBrush(System.Drawing.Color.FromArgb(128, 255, 255, 0));
  3005. g.FillEllipse(brush, new RectangleF((float)cursor.X - 25F, (float)cursor.Y - 25F, 50F, 50F));
  3006. var pen = new Pen(System.Drawing.Color.Black, 0.75F);
  3007. g.DrawLine(pen, (float)cursor.X - 10F, (float)cursor.Y, (float)cursor.X + 10F, (float)cursor.Y);
  3008. g.DrawLine(pen, (float)cursor.X, (float)cursor.Y - 10F, (float)cursor.X, (float)cursor.Y + 10F);
  3009. }
  3010. var key = DateTime.Now - totalpauses;
  3011. using (var reduced = ReduceBitmap(bmp, VIDEO_WIDTH, VIDEO_HEIGHT))
  3012. {
  3013. var ms = new MemoryStream();
  3014. reduced.Save(ms, ImageFormat.Png);
  3015. ms.Position = 0;
  3016. _bitmaps[key] = ms;
  3017. }
  3018. }
  3019. }
  3020. public Bitmap ReduceBitmap(Bitmap original, int reducedWidth, int reducedHeight)
  3021. {
  3022. var reduced = new Bitmap(reducedWidth, reducedHeight);
  3023. using (var dc = Graphics.FromImage(reduced))
  3024. {
  3025. // Figure out the ratio
  3026. var ratioX = (double)reducedWidth / original.Width;
  3027. var ratioY = (double)reducedHeight / original.Height;
  3028. // use whichever multiplier is smaller
  3029. var ratio = ratioX < ratioY ? ratioX : ratioY;
  3030. // now we can get the new height and width
  3031. var newHeight = Convert.ToInt32(original.Height * ratio);
  3032. var newWidth = Convert.ToInt32(original.Width * ratio);
  3033. // Now calculate the X,Y position of the upper-left corner
  3034. // (one of these will always be zero)
  3035. var posX = Convert.ToInt32((reducedWidth - original.Width * ratio) / 2);
  3036. var posY = Convert.ToInt32((reducedHeight - original.Height * ratio) / 2);
  3037. dc.InterpolationMode = InterpolationMode.HighQualityBicubic;
  3038. dc.Clear(System.Drawing.Color.Black); // white padding
  3039. //dc.DrawImage(original, posX, posY, newWidth, newHeight);
  3040. dc.DrawImage(original, new Rectangle(posX, posY, newWidth, newHeight), new Rectangle(0, 0, original.Width, original.Height),
  3041. GraphicsUnit.Pixel);
  3042. }
  3043. return reduced;
  3044. }
  3045. public static byte[] BitmapToByteArray(Bitmap bitmap, int width, int height)
  3046. {
  3047. // and buffer of appropriate size for storing its bits
  3048. var buffer = new byte[width * height * 4];
  3049. var pixelFormat = PixelFormat.Format32bppRgb;
  3050. // Now copy bits from bitmap to buffer
  3051. var bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);
  3052. //Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  3053. Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  3054. bitmap.UnlockBits(bits);
  3055. return buffer;
  3056. }
  3057. private void ProcessScreenShots(string filename)
  3058. {
  3059. if (!_bitmaps.Any() || _audioStream is null)
  3060. return;
  3061. Progress.Show("Saving Video");
  3062. var framRate = 10;
  3063. using (var writer = new AviWriter(filename))
  3064. {
  3065. writer.FramesPerSecond = framRate;
  3066. writer.EmitIndex1 = true;
  3067. _audioStream.Position = 0;
  3068. var audio = writer.AddAudioStream(2);
  3069. //audio.WriteBlock(_audioStream.GetBuffer(), 0, (int)_audioStream.Length);
  3070. //File.WriteAllBytes(Path.ChangeExtension(filename, "wav"), _audioStream.GetBuffer());
  3071. var audioByteRate = audio.BitsPerSample / 8 * audio.ChannelCount * audio.SamplesPerSecond;
  3072. var audioBlockSize = (int)(audioByteRate / writer.FramesPerSecond);
  3073. var audioBuffer = new byte[audioBlockSize];
  3074. _audioStream.Position = 0;
  3075. var encoder = new MJpegWpfVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT, 50);
  3076. var stream = writer.AddEncodingVideoStream(encoder, true, VIDEO_WIDTH, VIDEO_HEIGHT);
  3077. //var encoder = new SharpAvi.Codecs.UncompressedVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT);
  3078. //var stream = writer.AddEncodingVideoStream(encoder,true,VIDEO_WIDTH, VIDEO_HEIGHT);
  3079. //stream.Codec = CodecIds.Uncompressed;
  3080. //stream.BitsPerPixel = BitsPerPixel.Bpp16;
  3081. IEnumerable<DateTime> keys = _bitmaps.Keys.OrderBy(x => x);
  3082. var start = keys.First();
  3083. var end = keys.Last();
  3084. for (var cur = start; cur <= end; cur = cur + TimeSpan.FromMilliseconds(100))
  3085. {
  3086. Progress.SetMessage(string.Format("Processing ({0:F2} complete)",
  3087. (cur - start).TotalSeconds * 100.0F / (end - start).TotalSeconds));
  3088. var key = keys.LastOrDefault(x => x <= cur);
  3089. if (_bitmaps.ContainsKey(key))
  3090. {
  3091. var frame = (Image.FromStream(_bitmaps[key]) as Bitmap)!;
  3092. //frame.RotateFlip(RotateFlipType.RotateNoneFlipY);
  3093. var buf = BitmapToByteArray(frame, stream.Width, stream.Height);
  3094. stream.WriteFrame(true, buf, 0, buf.Length);
  3095. if (_audioStream.Position < _audioStream.Length)
  3096. {
  3097. var bytes = _audioStream.Read(audioBuffer, 0, audioBlockSize);
  3098. audio.WriteBlock(audioBuffer, 0, bytes);
  3099. }
  3100. }
  3101. }
  3102. writer.Close();
  3103. //foreach (var key in _bitmaps.Keys)
  3104. // File.Delete(_bitmaps[key]);
  3105. }
  3106. Progress.SetMessage("Transcoding");
  3107. //var inputFile = new MediaFile { Filename = filename };
  3108. //var outputFile = new MediaFile { Filename = Path.ChangeExtension(filename, "mp4") };
  3109. //using (var engine = new Engine())
  3110. //{
  3111. // //engine.ConvertProgressEvent += ConvertProgressEvent;
  3112. // engine.Convert(inputFile, outputFile);
  3113. //}
  3114. Progress.Close();
  3115. var dirName = Path.GetDirectoryName(filename);
  3116. if (dirName is not null)
  3117. {
  3118. var startInfo = new ProcessStartInfo(dirName);
  3119. startInfo.Verb = "open";
  3120. startInfo.UseShellExecute = true;
  3121. Process.Start(startInfo);
  3122. //MessageBox.Show("Recording Saved");
  3123. }
  3124. }
  3125. private void VideoRecordingButton_Click(object sender, RoutedEventArgs e)
  3126. {
  3127. ToggleRecording();
  3128. }
  3129. private void AudioRecordingButton_Click(object sender, RoutedEventArgs e)
  3130. {
  3131. ToggleRecordingAudio();
  3132. }
  3133. private void RecordingNotesButton_Click(object sender, RoutedEventArgs e)
  3134. {
  3135. ShowRecordingNotes();
  3136. }
  3137. #endregion
  3138. public static void ActivateWindow(Window window)
  3139. {
  3140. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  3141. var threadId1 = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
  3142. var threadId2 = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
  3143. if (threadId1 != threadId2)
  3144. {
  3145. AttachThreadInput(threadId1, threadId2, true);
  3146. SetForegroundWindow(hwnd);
  3147. AttachThreadInput(threadId1, threadId2, false);
  3148. }
  3149. else
  3150. {
  3151. SetForegroundWindow(hwnd);
  3152. }
  3153. }
  3154. private static IntPtr GetForegroundWindow()
  3155. {
  3156. var active = GetActiveWindow();
  3157. var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => new WindowInteropHelper(x).Handle == active);
  3158. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  3159. return hwnd;
  3160. }
  3161. [DllImport("user32.dll", SetLastError = true)]
  3162. private static extern IntPtr SetForegroundWindow(IntPtr hWnd);
  3163. [DllImport("user32.dll")]
  3164. private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
  3165. [DllImport("user32.dll")]
  3166. private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
  3167. [DllImport("user32.dll")]
  3168. private static extern IntPtr GetActiveWindow();
  3169. //private void ConvertProgressEvent(object sender, ConvertProgressEventArgs e)
  3170. //{
  3171. // Dispatcher.Invoke(() =>
  3172. // {
  3173. // try
  3174. // {
  3175. // if (e.TotalDuration.TotalSeconds != 0.0F)
  3176. // Progress.SetMessage(String.Format("Transcoding ({0:F2}% complete)", e.ProcessedDuration.TotalSeconds * 100.0F / e.TotalDuration.TotalSeconds));
  3177. // }
  3178. // catch (Exception err)
  3179. // {
  3180. // }
  3181. // });
  3182. //}
  3183. #region Check For Updates
  3184. private string GetUpdateLocation()
  3185. {
  3186. if (App.DatabaseSettings.DatabaseType == DatabaseType.Networked)
  3187. {
  3188. string url = "";
  3189. //var domain = App.DatabaseSettings.URL.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).Last();
  3190. //var port = App.DatabaseSettings.Port;
  3191. var domain = ClientFactory.Parameters?.FirstOrDefault()?.ToString() ?? "";
  3192. domain = domain.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? "";
  3193. if (!String.IsNullOrWhiteSpace(domain))
  3194. {
  3195. try
  3196. {
  3197. var client = new HttpClient { BaseAddress = new Uri($"https://{domain}") };
  3198. client.GetAsync("operations").Wait();
  3199. url = $"https://{domain}";
  3200. }
  3201. catch (Exception)
  3202. {
  3203. url = $"http://{domain}";
  3204. }
  3205. }
  3206. return url;
  3207. }
  3208. else
  3209. return Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update");
  3210. }
  3211. private string GetLatestVersion(string location)
  3212. {
  3213. return Client.Version();
  3214. }
  3215. private string GetReleaseNotes(string location)
  3216. {
  3217. return Client.ReleaseNotes();
  3218. }
  3219. private byte[]? GetInstaller(string location)
  3220. {
  3221. return Client.Installer();
  3222. }
  3223. private void CheckForUpdates()
  3224. {
  3225. Update.CheckForUpdates(
  3226. GetUpdateLocation, GetLatestVersion, GetReleaseNotes, GetInstaller, null, App.AutoUpdateSettings.Elevated, "PRSDesktopSetup.exe");
  3227. }
  3228. #endregion
  3229. #region Modules
  3230. public void CreatePanelAction(PanelAction action)
  3231. {
  3232. if (_ribbon.SelectedTabItem is null)
  3233. return;
  3234. var Actions = FindRibbonBar(_ribbon.SelectedTabItem, x => x.Header.Equals("Actions"));
  3235. if (Actions is not null)
  3236. {
  3237. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  3238. {
  3239. var sep = new RibbonSeparator();
  3240. CurrentModules.Add(sep);
  3241. Actions.Items.Add(sep);
  3242. }
  3243. var button = new RibbonButton
  3244. {
  3245. Label = action.Caption,
  3246. LargeIcon = action.Image.AsBitmapImage(),
  3247. SizeForm = SizeForm.Large,
  3248. MinWidth = 60,
  3249. Tag = action
  3250. };
  3251. button.Click += PaneActionClick;
  3252. CurrentModules.Add(button);
  3253. Actions.Items.Add(button);
  3254. }
  3255. }
  3256. private List<ISetupActionItem> PanelSetupActions = new();
  3257. public void CreateSetupAction(PanelAction action)
  3258. {
  3259. if (_ribbon.SelectedTabItem is null)
  3260. return;
  3261. AddSetupAction(PanelSetupActions, action.Caption, () =>
  3262. {
  3263. action.Execute();
  3264. }, action.Image);
  3265. }
  3266. private void PaneActionClick(object sender, RoutedEventArgs e)
  3267. {
  3268. var button = (Control)sender;
  3269. var action = (PanelAction)button.Tag;
  3270. action.Execute();
  3271. }
  3272. private void ReloadModules(string sectionName, DataModel model)
  3273. {
  3274. foreach (var module in CurrentModules)
  3275. {
  3276. if (module.Parent is Fluent.RibbonGroupBox bar)
  3277. bar.Items.Remove(module);
  3278. }
  3279. CurrentModules.Clear();
  3280. PanelSetupActions.Clear();
  3281. if (CurrentPanel != null)
  3282. {
  3283. CurrentPanel.CreateToolbarButtons(this);
  3284. CreateModules(sectionName, model, new Progress<Tuple<string, Bitmap, CustomModule>>(CreateModuleButton));
  3285. }
  3286. }
  3287. private void CreateModules(string section, DataModel model, IProgress<Tuple<string, Bitmap, CustomModule>> progress)
  3288. {
  3289. if (ClientFactory.IsSupported<CustomModule>())
  3290. {
  3291. foreach (var (module, image) in CustomModuleUtils.LoadCustomModuleThumbnails(section, model))
  3292. {
  3293. progress.Report(new Tuple<string, Bitmap, CustomModule>(module.Name ?? "", image, module));
  3294. }
  3295. }
  3296. }
  3297. private void CreateModuleButton(Tuple<string, Bitmap, CustomModule> module)
  3298. {
  3299. Fluent.RibbonGroupBox? Actions = CurrentTab != null
  3300. ? FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"))
  3301. : null;
  3302. if (Actions != null)
  3303. {
  3304. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  3305. {
  3306. var sep = new RibbonSeparator();
  3307. CurrentModules.Add(sep);
  3308. Actions.Items.Add(sep);
  3309. }
  3310. if (!CurrentModules.Any(x => x is Fluent.Button button && module.Item1.Equals(button.Header)))
  3311. {
  3312. var button = new Fluent.Button
  3313. {
  3314. Header = module.Item1,
  3315. LargeIcon = module.Item2.AsBitmapImage(),
  3316. MinWidth = 60,
  3317. Tag = module.Item3
  3318. };
  3319. button.Click += Module_Click;
  3320. CurrentModules.Add(button);
  3321. Actions.Items.Add(button);
  3322. }
  3323. }
  3324. }
  3325. private void Module_Click(object sender, RoutedEventArgs e)
  3326. {
  3327. if (CurrentPanel != null)
  3328. {
  3329. var item = (Fluent.Button)sender;
  3330. var code = (CustomModule)item.Tag;
  3331. if (!string.IsNullOrWhiteSpace(code.Script))
  3332. try
  3333. {
  3334. Selection selection;
  3335. if (code.SelectedRecords && code.AllRecords)
  3336. selection = RecordSelectionDialog.Execute();
  3337. else if (code.SelectedRecords)
  3338. selection = Selection.Selected;
  3339. else if (code.AllRecords)
  3340. selection = Selection.All;
  3341. else
  3342. selection = Selection.None;
  3343. var result = ScriptDocument.RunCustomModule(CurrentPanel.DataModel(selection), CurrentPanel.Selected(), code.Script);
  3344. if (result)
  3345. CurrentPanel.Refresh();
  3346. }
  3347. catch (CompileException c)
  3348. {
  3349. MessageBox.Show(c.Message);
  3350. }
  3351. catch (Exception err)
  3352. {
  3353. MessageBox.Show(CoreUtils.FormatException(err));
  3354. }
  3355. else
  3356. MessageBox.Show("Unable to load " + item.Header);
  3357. }
  3358. }
  3359. private void ManageModules()
  3360. {
  3361. if (CurrentPanel != null)
  3362. {
  3363. var section = CurrentPanel.SectionName;
  3364. var dataModel = CurrentPanel.DataModel(Selection.Selected);
  3365. var manager = new CustomModuleManager()
  3366. {
  3367. Section = section,
  3368. DataModel = dataModel
  3369. };
  3370. manager.ShowDialog();
  3371. ReloadModules(section, dataModel);
  3372. }
  3373. }
  3374. private void ManageModulesClick(object sender, RoutedEventArgs e)
  3375. {
  3376. ManageModules();
  3377. }
  3378. #endregion
  3379. #region Report Buttons
  3380. private void ReloadReports(string section, DataModel model)
  3381. {
  3382. if (CurrentTab is null)
  3383. return;
  3384. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  3385. if (ReportsBar is not null)
  3386. {
  3387. ReportsBar.Visibility = Security.IsAllowed<CanPrintReports>() ? Visibility.Visible : Visibility.Collapsed;
  3388. //ReportsBar.IsLauncherVisible = Security.IsAllowed<CanDesignReports>();
  3389. ReportsBar.Items.Clear();
  3390. CreateReports(section, model, new Progress<Tuple<string, Guid>>(CreateReportButton));
  3391. }
  3392. }
  3393. private void CreateReports(string section, DataModel model, IProgress<Tuple<string, Guid>> progress)
  3394. {
  3395. var client = new Client<ReportTemplate>();
  3396. var templates = client.Query(
  3397. new Filter<ReportTemplate>(x => x.DataModel).IsEqualTo(model.Name)
  3398. .And(x => x.Section).IsEqualTo(section)
  3399. .And(x => x.Visible).IsEqualTo(true),
  3400. new Columns<ReportTemplate>(x => x.ID, x => x.Name),
  3401. new SortOrder<ReportTemplate>(x => x.Name)
  3402. );
  3403. foreach (var row in templates.Rows)
  3404. progress.Report(new Tuple<string, Guid>(row.Get<ReportTemplate, string>(x => x.Name), row.Get<ReportTemplate, Guid>(x => x.ID)));
  3405. }
  3406. public void CreateReportButton(Tuple<string, Guid> report)
  3407. {
  3408. if (CurrentTab is null)
  3409. return;
  3410. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  3411. if (ReportsBar is not null)
  3412. {
  3413. var bFound = false;
  3414. foreach (var item in ReportsBar.Items)
  3415. {
  3416. if (item is RibbonButton button && report.Item2.Equals(button.Tag))
  3417. bFound = true;
  3418. }
  3419. if (!bFound)
  3420. {
  3421. var button = new RibbonButton
  3422. {
  3423. Label = report.Item1,
  3424. LargeIcon = PRSDesktop.Resources.printer.AsBitmapImage(),
  3425. Tag = report.Item2,
  3426. SizeForm = SizeForm.Large,
  3427. MinWidth = 60
  3428. };
  3429. if (Security.IsAllowed<CanDesignReports>())
  3430. {
  3431. var menu = new ContextMenu();
  3432. menu.AddItem("Design Report", PRSDesktop.Resources.pencil, report.Item2, ReportButtonMenu_DesignReport_Click);
  3433. button.ContextMenu = menu;
  3434. }
  3435. button.Click += ReportMenu_Checked;
  3436. ReportsBar.Items.Add(button);
  3437. }
  3438. }
  3439. }
  3440. private void ReportButtonMenu_DesignReport_Click(Guid templateID)
  3441. {
  3442. if (CurrentPanel is null)
  3443. return;
  3444. var template = new Client<ReportTemplate>().Load(new Filter<ReportTemplate>(x => x.ID).IsEqualTo(templateID)).FirstOrDefault();
  3445. if (template is null)
  3446. {
  3447. Logger.Send(LogType.Error, "", $"No Report Template with ID '{templateID}'");
  3448. MessageBox.Show("Report does not exist!");
  3449. return;
  3450. }
  3451. ReportUtils.DesignReport(template, CurrentPanel.DataModel(Selection.None));
  3452. }
  3453. private void ReportMenu_Checked(object sender, RoutedEventArgs e)
  3454. {
  3455. if (CurrentPanel is null)
  3456. return;
  3457. var item = (RibbonButton)sender;
  3458. var id = (Guid)item.Tag;
  3459. var template = new Client<ReportTemplate>().Load(new Filter<ReportTemplate>(x => x.ID).IsEqualTo(id)).FirstOrDefault();
  3460. if (template == null)
  3461. {
  3462. Logger.Send(LogType.Error, "", $"No Report Template with ID '{id}'");
  3463. MessageBox.Show("Report does not exist!");
  3464. return;
  3465. }
  3466. var selection = Selection.None;
  3467. if (template.SelectedRecords && template.AllRecords)
  3468. selection = RecordSelectionDialog.Execute();
  3469. else if (template.SelectedRecords)
  3470. selection = Selection.Selected;
  3471. else if (template.AllRecords)
  3472. selection = Selection.All;
  3473. else
  3474. MessageBox.Show("Report must have either [Selected Records] or [All Records] checked to display!");
  3475. if (selection != Selection.None)
  3476. ReportUtils.PreviewReport(template, CurrentPanel.DataModel(selection), false, Security.IsAllowed<CanDesignReports>());
  3477. }
  3478. private void ManageReports()
  3479. {
  3480. if (CurrentTab is null || CurrentPanel is null)
  3481. return;
  3482. var section = CurrentPanel.SectionName;
  3483. var model = CurrentPanel.DataModel(Selection.None);
  3484. if (model == null)
  3485. {
  3486. MessageBox.Show("No DataModel for " + CurrentTab.Header);
  3487. return;
  3488. }
  3489. var form = new ReportManager { DataModel = model, Section = section, Populate = true };
  3490. form.ShowDialog();
  3491. ReloadReports(section, model);
  3492. }
  3493. private void ManageEmailTemplates()
  3494. {
  3495. if (CurrentTab is null || CurrentPanel is null)
  3496. return;
  3497. var section = CurrentPanel.SectionName;
  3498. var model = CurrentPanel.DataModel(Selection.None);
  3499. if (model == null)
  3500. {
  3501. MessageBox.Show("No DataModel for " + CurrentTab.Header);
  3502. return;
  3503. }
  3504. var window = new EmailTemplateManagerWindow(model);
  3505. window.ShowDialog();
  3506. }
  3507. private void ManageReportsMenu_Click(object sender, RoutedEventArgs e)
  3508. {
  3509. ManageReports();
  3510. }
  3511. #endregion
  3512. #region Tracking Kanban
  3513. private void SelectTask_Click(object sender, RoutedEventArgs e)
  3514. {
  3515. ContextMenu menu = new ContextMenu();
  3516. MenuItem others = new MenuItem() { Header = "Other Tasks" };
  3517. using (new WaitCursor())
  3518. {
  3519. var kanbans = new Client<KanbanSubscriber>().Query(
  3520. new Filter<KanbanSubscriber>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
  3521. .And(x => x.Kanban.Completed).IsEqualTo(DateTime.MinValue)
  3522. .And(x => x.Kanban.Closed).IsEqualTo(DateTime.MinValue),
  3523. new Columns<KanbanSubscriber>(x => x.Kanban.ID)
  3524. .Add(x => x.Kanban.Number)
  3525. .Add(x => x.Kanban.Title)
  3526. .Add(x => x.Assignee),
  3527. new SortOrder<KanbanSubscriber>(x => x.Kanban.Number, SortDirection.Ascending)
  3528. );
  3529. foreach (var row in kanbans.Rows)
  3530. {
  3531. CreateTaskMenu(row.Get<KanbanSubscriber, bool>(c => c.Assignee) ? menu.Items : others.Items,
  3532. String.Format("{0} {1}",
  3533. row.Get<KanbanSubscriber, int>(c => c.Kanban.Number),
  3534. row.Get<KanbanSubscriber, String>(c => c.Kanban.Title)),
  3535. row.Get<KanbanSubscriber, Guid>(c => c.Kanban.ID)
  3536. );
  3537. }
  3538. menu.Items.Add(new Separator());
  3539. menu.Items.Add(others);
  3540. menu.Items.Add(new Separator());
  3541. CreateTaskMenu(menu.Items, "(No Task Selected)", Guid.Empty);
  3542. }
  3543. menu.IsOpen = true;
  3544. }
  3545. private Assignment? _kanbantrackingassignment = null;
  3546. private void SetTrackingKanban(Guid kanbanID, string header)
  3547. {
  3548. SelectedTaskName.Content = header;
  3549. var createNewAssignment = false;
  3550. if (_kanbantrackingassignment is not null)
  3551. {
  3552. if (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay)
  3553. {
  3554. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  3555. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  3556. }
  3557. // Update Existing Kanban
  3558. if (kanbanID == Guid.Empty)
  3559. _kanbantrackingassignment = null;
  3560. else if (_kanbantrackingassignment.Task.ID != kanbanID)
  3561. {
  3562. createNewAssignment = true;
  3563. }
  3564. }
  3565. else if (kanbanID != Guid.Empty)
  3566. {
  3567. createNewAssignment = true;
  3568. }
  3569. if (createNewAssignment)
  3570. {
  3571. _kanbantrackingassignment = new Assignment();
  3572. _kanbantrackingassignment.Task.ID = kanbanID;
  3573. _kanbantrackingassignment.EmployeeLink.ID = App.EmployeeID;
  3574. _kanbantrackingassignment.Title = header;
  3575. _kanbantrackingassignment.Date = DateTime.Today;
  3576. _kanbantrackingassignment.Actual.Start = DateTime.Now.TimeOfDay;
  3577. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay.Add(new TimeSpan(0, 2, 0));
  3578. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  3579. }
  3580. }
  3581. private void ClearTrackingKanban()
  3582. => SetTrackingKanban(Guid.Empty, "(No Task Selected)");
  3583. private void CreateTaskMenu(ItemCollection items, String title, Guid id)
  3584. {
  3585. var item = new MenuItem()
  3586. {
  3587. Header = title,
  3588. Tag = id
  3589. };
  3590. item.Click += (o, args) =>
  3591. {
  3592. if (o is not MenuItem menu) return;
  3593. SetTrackingKanban((Guid)item.Tag, (menu.Header as string) ?? "");
  3594. };
  3595. items.Add(item);
  3596. }
  3597. #endregion
  3598. private void DockPanel_OnIsActiveChanged(object? sender, EventArgs e)
  3599. {
  3600. var layout = sender as LayoutAnchorable;
  3601. if (layout == null)
  3602. return;
  3603. var content = layout.Content as DependencyObject;
  3604. var dock = content is IDockPanel panel ? panel : content?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  3605. if (dock == null)
  3606. return;
  3607. if (layout.IsActive && layout.IsVisible)
  3608. dock.Refresh();
  3609. }
  3610. private void _ribbon_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  3611. {
  3612. e.Handled = true;
  3613. }
  3614. #region Backstage Functions
  3615. private enum DatabaseConfigurationResult
  3616. {
  3617. RestartRequired,
  3618. RestartNotRequired,
  3619. Cancel
  3620. }
  3621. private DatabaseConfigurationResult ShowDatabaseConfiguration()
  3622. {
  3623. DatabaseConfigurationResult result;
  3624. var config = new DataBaseConfiguration();
  3625. if (config.ShowDialog() == true)
  3626. {
  3627. var newsettings = new LocalConfiguration<DatabaseSettings>(App.Profile).Load();
  3628. if (newsettings.RestartRequired(App.DatabaseSettings))
  3629. {
  3630. result = DatabaseConfigurationResult.RestartRequired;
  3631. }
  3632. else
  3633. {
  3634. result = DatabaseConfigurationResult.RestartNotRequired;
  3635. }
  3636. if ((newsettings.DatabaseType == DatabaseType.Standalone) && (newsettings.ColorScheme != App.DatabaseSettings.ColorScheme))
  3637. {
  3638. App.DatabaseSettings.ColorScheme = newsettings.ColorScheme;
  3639. ApplyColorScheme();
  3640. }
  3641. }
  3642. else
  3643. {
  3644. result = DatabaseConfigurationResult.Cancel;
  3645. }
  3646. return result;
  3647. }
  3648. private void DatabaseSettings_OnClick(object sender, RoutedEventArgs e)
  3649. {
  3650. switch (ShowDatabaseConfiguration())
  3651. {
  3652. case DatabaseConfigurationResult.RestartRequired:
  3653. MessageBox.Show("Please restart the application to apply these changes!");
  3654. break;
  3655. }
  3656. }
  3657. private void CompanyInformation_OnClick(object sender, RoutedEventArgs e)
  3658. {
  3659. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  3660. if (info == null)
  3661. info = new CompanyInformation();
  3662. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  3663. }
  3664. private void SecurityDefaultsButton_OnClick(object sender, RoutedEventArgs e)
  3665. {
  3666. var window = new GlobalTokenWindow();
  3667. window.ShowDialog();
  3668. Security.Reset();
  3669. }
  3670. private void SystemLogsButton_OnClick(object sender, RoutedEventArgs e)
  3671. {
  3672. var logfile = Path.Combine(CoreUtils.GetPath(), string.Format("{0:yyyy-MM-dd}.log", DateTime.Today));
  3673. if (File.Exists(logfile))
  3674. {
  3675. var startInfo = new ProcessStartInfo("notepad.exe", logfile);
  3676. startInfo.Verb = "open";
  3677. startInfo.UseShellExecute = true;
  3678. Process.Start(startInfo);
  3679. }
  3680. else
  3681. {
  3682. MessageBox.Show(logfile + " does not exist!");
  3683. }
  3684. }
  3685. private void DocumentTypeList_OnClick(object sender, RoutedEventArgs e)
  3686. {
  3687. var list = new MasterList(typeof(DocumentType));
  3688. list.ShowDialog();
  3689. }
  3690. private void DocumentList_OnClick(object sender, RoutedEventArgs e)
  3691. {
  3692. var list = new MasterList(typeof(Document));
  3693. list.ShowDialog();
  3694. }
  3695. private void QAFormSetupButton_OnClick(object sender, RoutedEventArgs e)
  3696. {
  3697. var list = new MasterList(typeof(DigitalForm), "AppliesTo", null, true);
  3698. list.ShowDialog();
  3699. }
  3700. private void EditDetailsButton_OnClick(object sender, RoutedEventArgs e)
  3701. {
  3702. var employee = new Client<Employee>().Query(
  3703. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid))
  3704. .Rows.FirstOrDefault()?.ToObject<Employee>();
  3705. var item = new MyDetailsConfiguration(employee);
  3706. item.User = ClientFactory.UserGuid;
  3707. var buttons = new DynamicEditorButtons();
  3708. buttons.Add("Change Password", null, item, (sender, item) =>
  3709. {
  3710. var details = (item as MyDetailsConfiguration)!;
  3711. var changePassword = new ChangePassword(details.User);
  3712. if (changePassword.ShowDialog() == true && changePassword.Password != null)
  3713. {
  3714. var newUser = new User();
  3715. newUser.ID = details.User;
  3716. ChangePassword.ChangeUserPassword(newUser, changePassword.Password);
  3717. new Client<User>().Save(newUser, "Changed Password");
  3718. MessageBox.Show("Password changed!");
  3719. }
  3720. });
  3721. var editor = new DynamicEditorForm(typeof(MyDetailsConfiguration), buttons: buttons);
  3722. if (employee == null)
  3723. {
  3724. editor.OnFormCustomiseEditor += (sender, items, column, editor) =>
  3725. {
  3726. editor.Editable = Editable.Disabled;
  3727. };
  3728. }
  3729. editor.Items = new BaseObject[] { item };
  3730. if (editor.ShowDialog() == true)
  3731. {
  3732. if (employee != null)
  3733. {
  3734. item.SaveTo(employee);
  3735. new Client<Employee>().Save(employee, "Edited by user");
  3736. }
  3737. }
  3738. }
  3739. private void LogoutButton_OnClick(object sender, RoutedEventArgs e)
  3740. {
  3741. Logout();
  3742. }
  3743. private void LoginButton_OnClick(object sender, RoutedEventArgs e)
  3744. {
  3745. if (DoLogin(false) == ValidationStatus.VALID)
  3746. AfterLogin();
  3747. }
  3748. private void ExitButton_OnClick(object sender, RoutedEventArgs e)
  3749. {
  3750. //_closingFromSystemMenu = true;
  3751. Close();
  3752. }
  3753. #endregion
  3754. }
  3755. }