MainWindow.xaml.cs 164 KB

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