MainWindow.xaml.cs 160 KB

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