MainWindow.xaml.cs 177 KB

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