MainWindow.xaml.cs 177 KB

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