MainWindow.xaml.cs 176 KB

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