MainWindow.xaml.cs 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.ComponentModel;
  5. using System.Diagnostics;
  6. using System.Drawing;
  7. using System.Drawing.Drawing2D;
  8. using System.Drawing.Imaging;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net.Http;
  12. using System.Reflection;
  13. using System.Runtime.InteropServices;
  14. using System.Threading.Tasks;
  15. using System.Windows;
  16. using System.Windows.Controls;
  17. using System.Windows.Forms;
  18. using System.Windows.Input;
  19. using System.Windows.Interop;
  20. using System.Windows.Media;
  21. using System.Windows.Threading;
  22. using AvalonDock.Layout;
  23. using Comal.Classes;
  24. using Comal.Stores;
  25. using Comal.TaskScheduler.Shared;
  26. using H.Pipes;
  27. using InABox.Clients;
  28. using InABox.Configuration;
  29. using InABox.Core;
  30. using InABox.Database;
  31. using InABox.Database.SQLite;
  32. using InABox.DynamicGrid;
  33. using InABox.Mail;
  34. using InABox.Core.Reports;
  35. using InABox.IPC;
  36. using InABox.Rpc;
  37. using InABox.Scripting;
  38. using InABox.Wpf;
  39. using InABox.Wpf.Console;
  40. using InABox.WPF;
  41. using NAudio.Wave;
  42. using PRS.Shared;
  43. using InABox.WPF.Themes;
  44. using PRSDesktop.Configuration;
  45. using PRSDesktop.Forms;
  46. using PRSServer;
  47. using SharpAvi.Codecs;
  48. using SharpAvi.Output;
  49. using Syncfusion.Windows.Shared;
  50. using Syncfusion.Windows.Tools;
  51. using Syncfusion.Windows.Tools.Controls;
  52. using Activity = Comal.Classes.Activity;
  53. using Application = System.Windows.Application;
  54. using ButtonBase = System.Windows.Controls.Primitives.ButtonBase;
  55. using Color = System.Windows.Media.Color;
  56. using ColorConverter = System.Windows.Media.ColorConverter;
  57. using Control = System.Windows.Controls.Control;
  58. using Image = System.Drawing.Image;
  59. using KeyEventArgs = System.Windows.Input.KeyEventArgs;
  60. using MessageBox = System.Windows.MessageBox;
  61. using Pen = System.Drawing.Pen;
  62. using PixelFormat = System.Drawing.Imaging.PixelFormat;
  63. using Role = Comal.Classes.Role;
  64. using SortDirection = InABox.Core.SortDirection;
  65. using PRSDesktop.Components.Spreadsheet;
  66. using InABox.Wpf.Reports;
  67. using Comal.Classes.SecurityDescriptors;
  68. using System.Threading;
  69. using System.Windows.Data;
  70. using System.Windows.Media.Imaging;
  71. using H.Formatters;
  72. using PRSDesktop.Panels;
  73. using Syncfusion.SfSkinManager;
  74. using PRSDesktop.Forms.Issues;
  75. namespace PRSDesktop;
  76. /// <summary>
  77. /// Interaction logic for Main.xaml
  78. /// </summary>
  79. public partial class MainWindow : IPanelHostControl
  80. {
  81. //private const int WM_LBUTTONDOWN = 0x201;
  82. private static PipeServer<string>? _client;
  83. private IRpcClientTransport? _transport;
  84. private WaveIn? _audio;
  85. private bool _audioMuted;
  86. private MemoryStream? _audioStream;
  87. private readonly Dictionary<DateTime, Stream> _bitmaps = new();
  88. private DesktopConsole? _console;
  89. private Dictionary<DateTime, Tuple<Rectangle, string>> _notes = new();
  90. private DispatcherTimer? _recorder;
  91. private Process? _recordingnotes;
  92. private int _screenheight = 720;
  93. private int _screenleft;
  94. private int _screentop;
  95. private int _screenwidth = 1280;
  96. private readonly Dictionary<Guid, SecondaryWindow> SecondaryWindows = new();
  97. private CoreTable? _timesheets;
  98. private DailyActivityHistory? ActivityHistory;
  99. private readonly List<Control> CurrentModules = new();
  100. private Fluent.RibbonTabItem? CurrentTab;
  101. private Fluent.Button? CurrentButton;
  102. private readonly int FRAMES_PER_SECOND = 10;
  103. private DatabaseType DatabaseType;
  104. private readonly Dictionary<int, int> messages = new();
  105. private readonly DispatcherTimer NotificationsWatchDog;
  106. private DateTime pausestarted = DateTime.MinValue;
  107. private readonly Scheduler scheduler = new() { Interval = new TimeSpan(0, 5, 0) };
  108. // We use a Guid for the StationID rather than an IP or Mac address
  109. // because we want true single-instance restriction. Using either of
  110. // the above allows for two instances on the once machine, and thus
  111. // double-counting in the Heartbeat() function
  112. private Login station = new() { StationID = Guid.NewGuid().ToString() };
  113. private TimeSpan totalpauses = new(0);
  114. private readonly int VIDEO_HEIGHT = 1080;
  115. private readonly int VIDEO_WIDTH = 1920;
  116. private PanelHost PanelHost;
  117. public MainWindow()
  118. {
  119. PanelHost = new PanelHost(this);
  120. NotificationsWatchDog = new DispatcherTimer { IsEnabled = false };
  121. NotificationsWatchDog.Tick += Notifications_Tick;
  122. NotificationsWatchDog.Interval = new TimeSpan(0, 2, 0);
  123. ClientFactory.PushHandlers.AddHandler<Notification>(ReceiveNotification);
  124. ClientFactory.RegisterMailer(EmailType.IMAP, typeof(IMAPMailer));
  125. ClientFactory.RegisterMailer(EmailType.Exchange, typeof(ExchangeMailer));
  126. ClientFactory.OnLog += (type, userid, message, parameters) => Logger.Send(LogType.Information, ClientFactory.UserID, message, parameters);
  127. ClientFactory.OnRequestError += ClientFactory_OnRequestError;
  128. HotKeyManager.Initialize();
  129. HotKeyManager.RegisterHotKey(Key.F1, ShowHelp);
  130. //HotKeyManager.RegisterHotKey(Key.F5, ToggleRecording);
  131. //HotKeyManager.RegisterHotKey(Key.F6, ShowRecordingNotes);
  132. //HotKeyManager.RegisterHotKey(Key.F4, ToggleRecordingAudio);
  133. Logger.Send(LogType.Information, "", "Connecting to server");
  134. var settings = App.DatabaseSettings;
  135. bool dbConnected;
  136. DatabaseType = settings.DatabaseType;
  137. switch (DatabaseType)
  138. {
  139. case DatabaseType.Standalone:
  140. ClientFactory.SetClientType(typeof(LocalClient<>), Platform.Wpf, CoreUtils.GetVersion());
  141. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  142. DbFactory.Logo = App.DatabaseSettings.Logo;
  143. dbConnected = true;
  144. break;
  145. case DatabaseType.Networked:
  146. if (App.DatabaseSettings.Protocol == SerializerProtocol.RPC)
  147. {
  148. _transport = new RpcClientSocketTransport(App.DatabaseSettings.URLs);
  149. _transport.OnClose += TransportConnectionLost;
  150. _transport.OnException += Transport_OnException;
  151. _transport.OnOpen += Transport_OnOpen; ;
  152. dbConnected = _transport.Connect();
  153. ClientFactory.SetClientType(typeof(RpcClient<>), Platform.Wpf, CoreUtils.GetVersion(),
  154. _transport);
  155. }
  156. else
  157. {
  158. var url = RestClient<User>.Ping(App.DatabaseSettings.URLs, out DatabaseInfo info);
  159. ClientFactory.SetClientType(typeof(RestClient<>), Platform.Wpf, CoreUtils.GetVersion(), url, true);
  160. dbConnected = true;
  161. }
  162. break;
  163. case DatabaseType.Local:
  164. //new RPC stuff (temporary disabled - for enabling when RPC is ready)
  165. var pipename = DatabaseServerProperties.GetPipeName(App.DatabaseSettings.LocalServerName, true);
  166. _transport = new RpcClientPipeTransport(pipename);
  167. _transport.OnClose += TransportConnectionLost;
  168. dbConnected = _transport.Connect();
  169. ClientFactory.SetClientType(typeof(RpcClient<>), Platform.Wpf, CoreUtils.GetVersion(), _transport );
  170. //ClientFactory.SetClientType(typeof(IPCClient<>), Platform.Wpf, CoreUtils.GetVersion(),
  171. // DatabaseServerProperties.GetPipeName(App.DatabaseSettings.LocalServerName, false));
  172. //dbConnected = true;
  173. break;
  174. default:
  175. throw new Exception($"Invalid database type {DatabaseType}");
  176. }
  177. InitializeComponent();
  178. if (!dbConnected)
  179. {
  180. switch (DoConnectionFailed())
  181. {
  182. case ConnectionFailedResult.Quit:
  183. Close();
  184. return;
  185. case ConnectionFailedResult.Restart:
  186. App.ShouldRestart = true;
  187. Close();
  188. return;
  189. case ConnectionFailedResult.Ok:
  190. // Do nothing
  191. break;
  192. }
  193. }
  194. ThemeManager.BaseColor = Colors.CornflowerBlue;
  195. Progress.DisplayImage = PRSDesktop.Resources.splash_small.AsBitmapImage();
  196. try
  197. {
  198. var dbInfo = new Client<User>().Info();
  199. ClientFactory.DatabaseID = dbInfo.DatabaseID;
  200. ThemeManager.BaseColor = (Color)ColorConverter.ConvertFromString(dbInfo.ColorScheme);
  201. if (dbInfo.Logo?.Any() == true)
  202. using (var ms = new MemoryStream(dbInfo.Logo))
  203. {
  204. Progress.DisplayImage = new Bitmap(ms).AsBitmapImage();
  205. }
  206. }
  207. catch
  208. {
  209. }
  210. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  211. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  212. SecondaryWindowStatus.Source = PRSDesktop.Resources.target.AsGrayScale().AsBitmapImage();
  213. ConsoleStatus.Source = PRSDesktop.Resources.view.AsGrayScale().AsBitmapImage();
  214. SelectTask.Source = PRSDesktop.Resources.uparrow.Invert().AsBitmapImage();
  215. Title = $"{(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  216. Logger.Send(LogType.Information, "", "Checking for updates");
  217. CheckForUpdates();
  218. Exception? startupException = null;
  219. ValidationStatus? loginStatus = null;
  220. Progress.ShowModal("Loading PRS", progress =>
  221. {
  222. DynamicGridUtils.PreviewReport = (t, m) => { ReportUtils.PreviewReport(t, m, false, Security.IsAllowed<CanDesignReports>()); };
  223. DynamicGridUtils.PrintMenu = (e, s, m, p) => { ReportUtils.PrintMenu(e, s, m, Security.IsAllowed<CanDesignReports>(), p); };
  224. ImportFactory.Register(typeof(ExcelImporter<>), "Excel File", "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm");
  225. ImportFactory.Register(typeof(CustomImporter<>), "Custom", "All Files (*.*)|*.*");
  226. FormUtils.Register();
  227. DigitalFormDocumentFactory.Init(
  228. new WpfDigitalFormDocumentHandler(
  229. b => Dispatcher.BeginInvoke(() =>
  230. {
  231. BackgroundUploadStatus.Visibility = b
  232. ? Visibility.Visible
  233. : Visibility.Hidden;
  234. }
  235. ),
  236. () => _transport?.IsConnected() ?? false
  237. )
  238. );
  239. DigitalFormDocumentFactory.Run();
  240. Logger.Send(LogType.Information, "", "Registering Classes");
  241. progress.Report("Registering Classes");
  242. var tasks = new List<Task>
  243. {
  244. Task.Run(() =>
  245. {
  246. CoreUtils.RegisterClasses(typeof(TaskGrid).Assembly);
  247. CoreUtils.RegisterClasses();
  248. ComalUtils.RegisterClasses();
  249. PRSSharedUtils.RegisterClasses();
  250. WPFUtils.RegisterClasses();
  251. ReportUtils.RegisterClasses();
  252. ConfigurationUtils.RegisterClasses();
  253. }),
  254. Task.Run(() =>
  255. {
  256. ScriptDocument.DefaultAssemblies.AddRange(
  257. Assembly.Load("RoslynPad.Roslyn.Windows"),
  258. Assembly.Load("RoslynPad.Editor.Windows"),
  259. typeof(Control).Assembly,
  260. typeof(MessageBox).Assembly,
  261. typeof(SolidColorBrush).Assembly
  262. );
  263. ScriptDocument.Initialize();
  264. }),
  265. Task.Run(() => DatabaseUpdateScripts.RegisterScripts())
  266. };
  267. Task.WaitAll(tasks.ToArray());
  268. Logger.Send(LogType.Information, "", "Configuring Application");
  269. progress.Report("Configuring Application");
  270. RegisterModules(progress);
  271. if (DatabaseType == DatabaseType.Standalone)
  272. {
  273. progress.Report("Starting local database...");
  274. try
  275. {
  276. StartLocalDatabase(progress);
  277. }
  278. catch (Exception err)
  279. {
  280. startupException = new Exception(
  281. string.Format(
  282. "Unable to open database ({0})\n\n{1}\n\n{2}",
  283. App.DatabaseSettings.FileName,
  284. err.Message,
  285. err.StackTrace
  286. )
  287. );
  288. }
  289. }
  290. });
  291. if (startupException is null && App.DatabaseSettings.Autologin)
  292. {
  293. try
  294. {
  295. Logger.Send(LogType.Information, "", "Logging in");
  296. Dispatcher.Invoke(() =>
  297. {
  298. loginStatus = TryAutoLogin();
  299. });
  300. if(loginStatus == ValidationStatus.VALID)
  301. {
  302. // Do the AfterLogin() here so that we aren't opening and closing progress windows again and again.
  303. Progress.ShowModal("Loading PRS", progress =>
  304. {
  305. AfterLogin(progress);
  306. });
  307. }
  308. }
  309. catch(Exception e)
  310. {
  311. startupException = e;
  312. }
  313. }
  314. if (startupException != null)
  315. {
  316. MessageWindow.ShowError("Error during startup.", startupException);
  317. }
  318. // If the login status is valid, then we've already loaded everything, so we don't here.
  319. if(loginStatus != ValidationStatus.VALID)
  320. {
  321. Logger.Send(LogType.Information, "", "Logging in");
  322. if (DoLogin() == ValidationStatus.VALID)
  323. {
  324. AfterLogin(null);
  325. }
  326. else
  327. {
  328. ConfigureMainScreen(null);
  329. }
  330. }
  331. else
  332. {
  333. ConfigureMainScreen(null);
  334. }
  335. ProfileName.Content = App.Profile;
  336. URL.Content = GetDatabaseConnectionDescription();
  337. if (loginStatus == ValidationStatus.VALID && DatabaseType == DatabaseType.Standalone)
  338. {
  339. Progress.ShowModal("Starting Scheduler", progress =>
  340. {
  341. scheduler.Start();
  342. });
  343. }
  344. }
  345. #region Connection Management
  346. private string GetDatabaseConnectionDescription()
  347. {
  348. return DatabaseType switch
  349. {
  350. #if RPC
  351. DatabaseType.Networked => (ClientFactory.Parameters?.FirstOrDefault() as RpcClientSocketTransport)?.Host,
  352. #else
  353. DatabaseType.Networked => ClientFactory.Parameters?.FirstOrDefault() as string,
  354. #endif
  355. DatabaseType.Standalone => App.DatabaseSettings?.FileName,
  356. DatabaseType.Local => App.DatabaseSettings?.LocalServerName,
  357. _ => ""
  358. } ?? "";
  359. }
  360. /// <summary>
  361. /// Reconnect to the server.
  362. /// </summary>
  363. /// <returns><see langword="true"/> if connection was successful.</returns>
  364. private bool Reconnect()
  365. {
  366. if (_transport != null)
  367. {
  368. return _transport.Connect();
  369. }
  370. Logger.Send(LogType.Error, ClientFactory.UserID, "Trying to reconnect without a transport set.");
  371. return true; // Returning true so we don't get stuck in infinite loops in exceptional circumstances.
  372. }
  373. private enum ConnectionFailedResult
  374. {
  375. Quit,
  376. Restart,
  377. Ok
  378. }
  379. /// <summary>
  380. /// To be called when initial connection to the server has failed; asks the user if they want to retry,
  381. /// change the database settings, or simply quit PRS.
  382. /// </summary>
  383. /// <returns>The action to take next.</returns>
  384. /// <exception cref="Exception"></exception>
  385. private ConnectionFailedResult DoConnectionFailed()
  386. {
  387. bool connected = false;
  388. while (!connected)
  389. {
  390. var connectionFailedWindow = new ConnectionFailed();
  391. connectionFailedWindow.ShowDialog();
  392. var reconnect = false;
  393. switch (connectionFailedWindow.Result)
  394. {
  395. case ConnectionFailedWindowResult.OpenDatabaseConfiguration:
  396. var result = ShowDatabaseConfiguration();
  397. switch (result)
  398. {
  399. case DatabaseConfigurationResult.RestartRequired:
  400. var shouldRestart = MessageBox.Show(
  401. "A restart is required to apply these changes. Do you wish to restart now?",
  402. "Restart?",
  403. MessageBoxButton.YesNo);
  404. if (shouldRestart == MessageBoxResult.Yes)
  405. {
  406. return ConnectionFailedResult.Restart;
  407. }
  408. else
  409. {
  410. reconnect = true;
  411. }
  412. break;
  413. case DatabaseConfigurationResult.RestartNotRequired:
  414. reconnect = true;
  415. break;
  416. case DatabaseConfigurationResult.Cancel:
  417. reconnect = true;
  418. break;
  419. default:
  420. throw new Exception($"Invalid enum result {result}");
  421. }
  422. break;
  423. case ConnectionFailedWindowResult.RetryConnection:
  424. reconnect = true;
  425. break;
  426. case ConnectionFailedWindowResult.Quit:
  427. return ConnectionFailedResult.Quit;
  428. default:
  429. throw new Exception($"Invalid enum result {connectionFailedWindow.Result}");
  430. }
  431. if (!reconnect)
  432. {
  433. return ConnectionFailedResult.Quit;
  434. }
  435. connected = Reconnect();
  436. }
  437. return ConnectionFailedResult.Ok;
  438. }
  439. private void Transport_OnOpen(IRpcTransport transport, RpcTransportOpenArgs e)
  440. {
  441. Logger.Send(LogType.Information, ClientFactory.UserID, "Connection opened");
  442. }
  443. private void Transport_OnException(IRpcTransport transport, RpcTransportExceptionArgs e)
  444. {
  445. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error in connection: {CoreUtils.FormatException(e.Exception)}");
  446. }
  447. private void TransportConnectionLost(IRpcTransport transport, RpcTransportCloseArgs e)
  448. {
  449. Logger.Send(LogType.Information, ClientFactory.UserID, "Connection lost");
  450. if (transport is IRpcClientTransport client)
  451. {
  452. Dispatcher.Invoke(() =>
  453. {
  454. var reconnection = new ReconnectionWindow();
  455. var cancellationTokenSource = new CancellationTokenSource();
  456. reconnection.OnCancelled = () => cancellationTokenSource.Cancel();
  457. var ct = cancellationTokenSource.Token;
  458. var work = () =>
  459. {
  460. try
  461. {
  462. DateTime lost = DateTime.Now;
  463. while (!client.IsConnected() && !ct.IsCancellationRequested)
  464. {
  465. try
  466. {
  467. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnecting - ({DateTime.Now - lost:hh\\:mm})");
  468. if (client.Connect(ct))
  469. {
  470. break;
  471. }
  472. }
  473. catch (System.Exception e1)
  474. {
  475. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnect Failed: {e1.Message}");
  476. // TODO: Remove this suppression
  477. if (e1.Message.StartsWith("The socket is connected, you needn't connect again!"))
  478. {
  479. break;
  480. }
  481. }
  482. }
  483. if (client.IsConnected())
  484. {
  485. Logger.Send(LogType.Information, ClientFactory.UserID, "Reconnected");
  486. ClientFactory.Validate(ClientFactory.SessionID);
  487. Logger.Send(LogType.Information, ClientFactory.UserID, "Validated");
  488. return true;
  489. }
  490. }
  491. catch (Exception e)
  492. {
  493. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnect Failed: {e.Message}");
  494. }
  495. return false;
  496. };
  497. var task = Task.Run(() =>
  498. {
  499. var result = work();
  500. Dispatcher.Invoke(() =>
  501. {
  502. reconnection.Close();
  503. });
  504. return result;
  505. }, ct);
  506. reconnection.ShowDialog();
  507. if (!task.Result)
  508. {
  509. Close();
  510. }
  511. });
  512. }
  513. }
  514. #endregion
  515. private bool _loggingOut = false;
  516. private void ClientFactory_OnRequestError(RequestException e)
  517. {
  518. if (e.Status == StatusCode.Unauthenticated)
  519. {
  520. switch (e.Method)
  521. {
  522. case RequestMethod.Query:
  523. case RequestMethod.Save:
  524. case RequestMethod.Delete:
  525. case RequestMethod.MultiQuery:
  526. case RequestMethod.MultiSave:
  527. case RequestMethod.MultiDelete:
  528. if (!_loggingOut)
  529. {
  530. Dispatcher.InvokeAsync(() =>
  531. {
  532. _loggingOut = true;
  533. try
  534. {
  535. Logout(null, true);
  536. }
  537. finally
  538. {
  539. _loggingOut = false;
  540. }
  541. });
  542. }
  543. break;
  544. default:
  545. break;
  546. }
  547. }
  548. }
  549. private void ApplyColorScheme()
  550. {
  551. Color baseColor;
  552. try
  553. {
  554. baseColor = (Color)ColorConverter.ConvertFromString(App.DatabaseSettings.ColorScheme);
  555. }
  556. catch
  557. {
  558. baseColor = Colors.CornflowerBlue;
  559. }
  560. ThemeManager.BaseColor = baseColor;
  561. DynamicGridUtils.SelectionBackground = ThemeManager.SelectionBackgroundBrush;
  562. DynamicGridUtils.SelectionForeground = ThemeManager.SelectionForegroundBrush;
  563. DynamicGridUtils.FilterBackground = ThemeManager.FilterBackgroundBrush;
  564. //_ribbon.Background = new SolidColorBrush(Colors.White);
  565. //_ribbon.BackStageColor = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  566. ////_ribbon.BackStage.Background = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  567. ////_ribbon.BackStage.Foreground = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Foreground);
  568. UpdateRibbonColors();
  569. PanelHost.Refresh();
  570. }
  571. #region Configuration
  572. /*
  573. protected override void OnSourceInitialized(EventArgs e)
  574. {
  575. base.OnSourceInitialized(e);
  576. var source = PresentationSource.FromVisual(this) as HwndSource;
  577. source?.AddHook(WndProc);
  578. }
  579. private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  580. {
  581. var message = (App.Message)msg;
  582. switch (message)
  583. {
  584. case App.Message.Maximise:
  585. WindowState = WindowState.Maximized;
  586. break;
  587. }
  588. return IntPtr.Zero;
  589. }*/
  590. private void ConfigureMainScreen(IProgress<string>? progress)
  591. {
  592. var bMaps = Security.CanView<Equipment>()
  593. || Security.CanView<Job>()
  594. || Security.CanView<TimeSheet>()
  595. || Security.CanView<GPSTracker>();
  596. var sections = new[]
  597. {
  598. new ProgressSection("Configuring Main Screen", SetupMainScreen),
  599. new ProgressSection("Configuring Projects", () => SetupProjectsTab(bMaps)),
  600. new ProgressSection("Configuring Manufacturing", () => SetupManufacturingTab(bMaps)),
  601. new ProgressSection("Configuring Logistics", () => SetupLogisticsTab(bMaps)),
  602. new ProgressSection("Configuring Products", () => SetupProductsTab(bMaps)),
  603. new ProgressSection("Configuring Human Resources", () => SetupHumanResourcesTab(bMaps)),
  604. new ProgressSection("Configuring Accounts", () => SetupAccountsTab(bMaps)),
  605. new ProgressSection("Configuring Equipment", () => SetupEquipmentTab(bMaps)),
  606. new ProgressSection("Configuring DigitalForms", () => SetupDigitalFormsTab(bMaps)),
  607. new ProgressSection("Configuring Dashboards", () => SetupDashboardsTab(bMaps)),
  608. new ProgressSection("Configuring System Modules", SetupSystemModules)
  609. };
  610. if(progress is not null)
  611. {
  612. Dispatcher.Invoke(SetupScreen);
  613. foreach(var section in sections)
  614. {
  615. progress.Report(section.Message);
  616. Dispatcher.Invoke(section.Action);
  617. }
  618. }
  619. else
  620. {
  621. SetupScreen();
  622. Progress.ShowModal(sections);
  623. }
  624. }
  625. private void SetupScreen()
  626. {
  627. var button = _ribbon.FindVisualChildren<Fluent.DropDownButton>().FirstOrDefault();
  628. if (button != null)
  629. button.Visibility = Visibility.Collapsed;
  630. if (ClientFactory.UserGuid == Guid.Empty)
  631. _ribbonRow.Height = new GridLength(30, GridUnitType.Pixel);
  632. else
  633. _ribbonRow.Height = new GridLength(1, GridUnitType.Auto);
  634. }
  635. private void SetupMainScreen()
  636. {
  637. //DockManager.SidePanelSize = OutstandingDailyReports(false) ? 0.00F : 30.00F;
  638. // Notifications Area
  639. SetVisibility(SendNotification, Security.CanView<Notification>());
  640. SetVisibility(Notifications, Security.CanView<Notification>());
  641. SetVisibility(TaskTracking, Security.IsAllowed<CanTrackTasksInDailyReport>());
  642. UserID.Content = ClientFactory.UserID;
  643. if (ClientFactory.PasswordExpiration != DateTime.MinValue)
  644. {
  645. var timeUntilExpiration = ClientFactory.PasswordExpiration - DateTime.Now;
  646. if (timeUntilExpiration.Days < 14)
  647. {
  648. PasswordExpiryNotice.Content = $"Password will expire in {timeUntilExpiration.Days} days!";
  649. PasswordExpiryNotice.Visibility = Visibility.Visible;
  650. }
  651. else
  652. {
  653. PasswordExpiryNotice.Visibility = Visibility.Collapsed;
  654. }
  655. }
  656. }
  657. private void SetupSystemModules()
  658. {
  659. SetVisibility(CompanyInformation, Security.CanView<CompanyInformation>());
  660. SetVisibleIfAny(BackstageSeparator0, CompanyInformation);
  661. SetVisibility(SecurityDefaultsButton,
  662. ClientFactory.IsSupported<GlobalSecurityToken>() && Security.IsAllowed<CanCustomiseSecurityDefaults>());
  663. SetVisibleIfAny(BackstageSeparator1, SecurityDefaultsButton);
  664. BackstageSeparator1a.Visibility = Visibility.Visible;
  665. SystemLogsButton.Visibility = Visibility.Visible;
  666. SetVisibility(DocumentTypeList, ClientFactory.IsSupported<DocumentType>() && Security.IsAllowed<CanViewDocumentTypes>());
  667. SetVisibleIfAny(BackstageSeparator2, DocumentTypeList);
  668. SetVisibility(VideoRecordingButton, Security.IsAllowed<CanRecordScreen>());
  669. LogoutButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  670. LoginButton.Visibility = ClientFactory.UserGuid != Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  671. EditDetailsButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  672. SetupDock<CanViewContactsDock>(ContactDock, Contacts);
  673. SetupDock<CanViewJobDock>(JobDock, Jobs);
  674. SetupDock<CanViewConsignmentDock>(ConsignmentDock, Consignments);
  675. SetupDock<CanViewDeliveryDock>(DeliveryDock, Deliveries);
  676. SetupDock<CanViewProductDock>(ProductLookupDock, ProductLookup);
  677. SetupDock<CanViewDigitalFormsDock>(DigitalFormsDock, DigitalForms);
  678. SetupDock<CanViewProblemsDock>(ProblemsDock, Problems);
  679. SetupDock<CanViewRequisitionsDock>(RequisitionsDock, Requisitions);
  680. _ribbon.InvalidateArrange();
  681. }
  682. private void SetupDashboardsTab(bool bMaps)
  683. {
  684. if (!Security.IsAllowed<ViewDesktopDashboardsTab>())
  685. return;
  686. SetVisibility(DashboardsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  687. SetVisibility(DashboardMessagesButton, Security.CanView<Notification>());
  688. SetVisibility(DashboardsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  689. SetVisibility(DashboardsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  690. SetVisibility(DashboardsMapButton, bMaps);
  691. SetVisibility(DashboardsDailyReportButton,
  692. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  693. SetVisibility(FactoryProductivityButton,
  694. ClientFactory.IsSupported<ManufacturingHistory>()
  695. && Security.IsAllowed<CanViewFactoryKPIs>()
  696. && Security.IsAllowed<ViewDesktopFactoryKPIsDashboard>());
  697. SetVisibility(TemplateAnalysisButton,
  698. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>()
  699. && Security.IsAllowed<CanViewTemplateAnalysis>()
  700. && Security.IsAllowed<ViewDesktopTemplateAnalysisDashboard>());
  701. SetVisibility(FactoryAnalysisButton,
  702. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>()
  703. && Security.IsAllowed<CanViewFactoryAnalysis>()
  704. && Security.IsAllowed<ViewDesktopFactoryAnalysisDashboard>());
  705. SetVisibility(DatabaseActivityButton,
  706. ClientFactory.IsSupported<UserTracking>()
  707. && Security.IsAllowed<CanViewDatabaseActivity>()
  708. && Security.IsAllowed<ViewDesktopDatabaseActivityDashboard>());
  709. SetVisibility(UserActivityButton, ClientFactory.IsSupported<ModuleTracking>()
  710. && Security.IsAllowed<CanViewUserActivity>()
  711. && Security.IsAllowed<ViewDesktopUserActivityDashboard>());
  712. SetVisibility(QuickStatusButton, Security.IsAllowed<CanViewQuickStatus>() && Security.IsAllowed<ViewDesktopQuickStatusDashboard>());
  713. SetVisibleIfEither(DashboardsTaskSeparator,
  714. new FrameworkElement[]
  715. {
  716. DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton, DashboardsAttendanceButton,
  717. DashboardsMapButton,
  718. DashboardsDailyReportButton
  719. },
  720. new FrameworkElement[]
  721. {
  722. FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton, QuickStatusButton
  723. });
  724. SetVisibleIfAny(DashboardsActions, DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton,
  725. DashboardsAttendanceButton, DashboardsDailyReportButton, FactoryProductivityButton, TemplateAnalysisButton,
  726. FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton, QuickStatusButton);
  727. //DashboardsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  728. //DashboardsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  729. SetVisibleIfAny(DashboardsTab, FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton,
  730. DatabaseActivityButton,
  731. UserActivityButton, QuickStatusButton);
  732. }
  733. private void SetupDigitalFormsTab(bool bMaps)
  734. {
  735. if (!Security.IsAllowed<ViewDesktopDigitalFormsTab>())
  736. return;
  737. SetVisibility(DigitalFormsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  738. SetVisibility(DigitalFormsMessagesButton, Security.CanView<Notification>());
  739. SetVisibility(DigitalFormsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  740. SetVisibility(DigitalFormsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  741. SetVisibility(DigitalFormsMapButton, bMaps);
  742. SetVisibility(DigitalFormsDailyReportButton,
  743. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  744. SetVisibility(DigitalFormsFormsLibraryButton, ClientFactory.IsSupported<DigitalForm>()
  745. && Security.CanView<DigitalForm>()
  746. && Security.IsAllowed<CanAdministerDigitalFormsLibrary>());
  747. SetVisibility(DigitalFormsCompletedFormsButton, Security.IsAllowed<CanViewDigitalFormsDashbaord>() && Security.IsAllowed<ViewDesktopDigitalFormsDashboard>());
  748. SetVisibleIfEither(DigitalFormsTaskSeparator,
  749. new FrameworkElement[]
  750. {
  751. DigitalFormsDashboardButton, DigitalFormsMessagesButton, DigitalFormsTaskButton, DigitalFormsAttendanceButton, DigitalFormsMapButton,
  752. DigitalFormsDailyReportButton
  753. }, new FrameworkElement[] { DigitalFormsFormsLibraryButton, DigitalFormsCompletedFormsButton });
  754. SetVisibleIfAny(DigitalFormsActions, DigitalFormsDashboardButton, DigitalFormsMessagesButton, DigitalFormsTaskButton,
  755. DigitalFormsAttendanceButton, DigitalFormsDailyReportButton, DigitalFormsFormsLibraryButton, DigitalFormsCompletedFormsButton);
  756. SetTabVisibleIfAny(DigitalFormsTab, DigitalFormsFormsLibraryButton, DigitalFormsCompletedFormsButton);
  757. }
  758. private void SetupEquipmentTab(bool bMaps)
  759. {
  760. if (!Security.IsAllowed<ViewDesktopEquipmentTab>())
  761. return;
  762. SetVisibility(EquipmentDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  763. SetVisibility(EquipmentMessagesButton, Security.CanView<Notification>());
  764. SetVisibility(EquipmentTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  765. SetVisibility(EquipmentAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  766. SetVisibility(EquipmentMapButton, bMaps);
  767. SetVisibility(EquipmentDailyReportButton,
  768. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  769. SetVisibility(EquipmentButton, ClientFactory.IsSupported<Equipment>()
  770. && Security.CanView<Equipment>()
  771. && Security.IsAllowed<ViewDesktopEquipmentListScreen>());
  772. SetVisibility(EquipmentPlannerButton,
  773. ClientFactory.IsSupported<Equipment>()
  774. && Security.CanView<Equipment>()
  775. && ClientFactory.IsSupported<Assignment>()
  776. && Security.CanView<Assignment>()
  777. && Security.IsAllowed<ViewDesktopEquipmentPlannerScreen>());
  778. SetVisibleIfEither(EquipmentTaskSeparator,
  779. new FrameworkElement[]
  780. {
  781. EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton, EquipmentAttendanceButton, EquipmentMapButton,
  782. EquipmentDailyReportButton
  783. }, new FrameworkElement[] { EquipmentButton, EquipmentPlannerButton });
  784. SetVisibleIfAny(EquipmentActions, EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton,
  785. EquipmentAttendanceButton, EquipmentDailyReportButton, EquipmentButton, EquipmentPlannerButton);
  786. SetVisibility(TrackersMasterList, Security.CanView<GPSTracker>() && Security.IsAllowed<ViewDesktopGPSTrackersScreen>());
  787. SetTabVisibleIfAny(EquipmentTab, EquipmentButton, TrackersMasterList);
  788. }
  789. private void SetupAccountsTab(bool bMaps)
  790. {
  791. if (!Security.IsAllowed<ViewDesktopAccountsTab>())
  792. return;
  793. SetVisibility(AccountsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  794. SetVisibility(AccountsMessagesButton, Security.CanView<Notification>());
  795. SetVisibility(AccountsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  796. SetVisibility(AccountsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  797. SetVisibility(AccountsMapButton, bMaps);
  798. SetVisibility(AccountsDailyReportButton,
  799. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  800. SetVisibility(CustomerList, ClientFactory.IsSupported<Customer>()
  801. && Security.CanView<Customer>()
  802. && Security.IsAllowed<ViewDesktopCustomersScreen>());
  803. SetVisibility(InvoiceList, ClientFactory.IsSupported<Invoice>()
  804. && Security.CanView<Invoice>()
  805. && Security.IsAllowed<ViewDesktopInvoicesScreen>());
  806. SetVisibility(ReceiptList, ClientFactory.IsSupported<Receipt>()
  807. && Security.CanView<Receipt>()
  808. && Security.IsAllowed<ViewDesktopReceiptsScreen>());
  809. SetVisibility(SupplierList, ClientFactory.IsSupported<Supplier>()
  810. && Security.CanView<Supplier>()
  811. && Security.IsAllowed<ViewDesktopSuppliersScreen>());
  812. SetVisibility(AccountsDataButton, Security.IsAllowed<CanViewDataEntryPanel>());
  813. SetVisibility(PurchasesList, ClientFactory.IsSupported<PurchaseOrder>()
  814. && Security.CanView<PurchaseOrder>()
  815. && Security.IsAllowed<ViewDesktopPurchaseOrdersScreen>());
  816. SetVisibility(BillsList, ClientFactory.IsSupported<Bill>()
  817. && Security.CanView<Bill>()
  818. && Security.IsAllowed<ViewDesktopBillsScreen>());
  819. SetVisibility(PaymentsList, ClientFactory.IsSupported<Payment>()
  820. && Security.CanView<Payment>()
  821. && Security.IsAllowed<ViewDesktopPaymentsScreen>());
  822. SetVisibleIfEither(AccountsTaskSeparator1,
  823. new FrameworkElement[]
  824. {
  825. AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton, AccountsAttendanceButton, AccountsMapButton,
  826. AccountsDailyReportButton
  827. }, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList });
  828. SetVisibleIfEither(AccountsTaskSeparator2, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList },
  829. new FrameworkElement[] { SupplierList, AccountsDataButton, PurchasesList, BillsList, PaymentsList });
  830. SetVisibleIfAny(AccountsActions, AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton,
  831. AccountsAttendanceButton,
  832. AccountsDailyReportButton, CustomerList, InvoiceList, ReceiptList, SupplierList, PurchasesList, BillsList, PaymentsList);
  833. SetTabVisibleIfAny(AccountsTab, CustomerList, InvoiceList, ReceiptList, SupplierList, AccountsDataButton, PurchasesList, BillsList, PaymentsList);
  834. }
  835. private void SetupHumanResourcesTab(bool bMaps)
  836. {
  837. if (!Security.IsAllowed<ViewDesktopHumanResourcesTab>())
  838. return;
  839. SetVisibility(HumanResourcesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  840. SetVisibility(HumanResourcesMessagesButton, Security.CanView<Notification>());
  841. SetVisibility(HumanResourcesTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  842. SetVisibility(HumanResourcesAttendanceButton,
  843. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  844. SetVisibility(HumanResourcesMapButton, bMaps);
  845. SetVisibility(HumanResourcesDailyReportButton,
  846. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  847. SetVisibility(CalendarButton, Security.CanView<Assignment>() && Security.IsAllowed<ViewDesktopCalendarScreen>());
  848. SetVisibility(EmployeePlannerButton, Security.CanView<Assignment>() && Security.IsAllowed<ViewDesktopEmployeePlannerScreen>());
  849. SetVisibility(TimesheetsButton, Security.CanView<TimeSheet>() && Security.IsAllowed<ViewDesktopStaffTimeSheetsScreen>());
  850. SetVisibility(LeaveRequestsButton, Security.CanView<LeaveRequest>() && Security.IsAllowed<ViewDesktopLeaveRequestsScreen>());
  851. SetVisibility(OrgChartButton,
  852. ClientFactory.IsSupported<Employee>()
  853. &&
  854. Security.IsAllowed<ViewDesktopOrgChartScreen>()
  855. );
  856. SetVisibility(MeetingsButton, Security.IsAllowed<ViewDesktopMeetingsScreen>());
  857. SetVisibleIfEither(HumanResourcesTaskSeparator,
  858. new FrameworkElement[]
  859. {
  860. HumanResourcesDashboardButton, HumanResourcesMessagesButton, HumanResourcesTaskButton, HumanResourcesAttendanceButton,
  861. HumanResourcesMapButton, HumanResourcesDailyReportButton
  862. }, new FrameworkElement[] { CalendarButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton });
  863. SetVisibleIfAny(HumanResourcesActions, HumanResourcesDashboardButton, HumanResourcesTaskButton,
  864. HumanResourcesAttendanceButton,
  865. HumanResourcesDailyReportButton, CalendarButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton);
  866. SetVisibility(UsersButton, Security.CanView<User>() && Security.IsAllowed<ViewDesktopUserAccountsScreen>());
  867. SetVisibility(EmployeesButton, Security.CanView<Employee>() && Security.IsAllowed<ViewDesktopEmployeeListScreen>());
  868. SetVisibleIfEither(HumanResourcesSetupSeparator1,
  869. new FrameworkElement[] { CalendarButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton },
  870. new FrameworkElement[] { UsersButton, EmployeesButton });
  871. SetTabVisibleIfAny(HumanResourcesTab, CalendarButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton, UsersButton, EmployeesButton);
  872. }
  873. private void SetupProductsTab(bool bMaps)
  874. {
  875. if (!Security.IsAllowed<ViewDesktopProductManagementTab>())
  876. return;
  877. SetVisibility(ProductsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  878. SetVisibility(ProductsMessagesButton, Security.CanView<Notification>());
  879. SetVisibility(ProductsTaskButton, Security.CanView<Kanban>());
  880. SetVisibility(ProductsAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  881. SetVisibility(ProductsMapButton, bMaps);
  882. SetVisibility(ProductsDailyReportButton,
  883. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  884. SetVisibility(ProductsMasterList, Security.CanView<Product>() && Security.IsAllowed<ViewDesktopProductListScreen>());
  885. SetVisibility(StockLocationList, Security.CanView<StockLocation>() && Security.IsAllowed<ViewDesktopStockLocationsScreen>());
  886. SetVisibility(StockMovementList, Security.CanView<StockMovement>() && Security.IsAllowed<ViewDesktopStockMovementsScreen>());
  887. SetVisibility(StockForecastButton, Security.CanView<Product>()
  888. && Security.CanView<JobMaterial>()
  889. && Security.IsAllowed<ViewDesktopStockForecastScreen>());
  890. SetVisibility(ReservationManagementButton, Security.IsAllowed<ViewDesktopReservationManagementScreen>());
  891. SetVisibleIfEither(ProductsTaskSeparator,
  892. new FrameworkElement[]
  893. {
  894. ProductsDashboardButton, ProductsMessagesButton, ProductsTaskButton, ProductsAttendanceButton, ProductsMapButton,
  895. ProductsDailyReportButton
  896. }, new FrameworkElement[] { ProductsMasterList, StockLocationList, StockMovementList, StockForecastButton });
  897. SetVisibleIfAny(ProductActions, ProductsMasterList, StockLocationList, StockMovementList, StockForecastButton);
  898. SetTabVisibleIfAny(ProductTab, ProductActions);
  899. }
  900. private void SetupLogisticsTab(bool bMaps)
  901. {
  902. if (!Security.IsAllowed<ViewDesktopLogisticsTab>())
  903. return;
  904. SetVisibility(LogisticsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  905. SetVisibility(LogisticsMessagesButton, Security.CanView<Notification>());
  906. SetVisibility(LogisticsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  907. SetVisibility(LogisticsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  908. SetVisibility(LogisticsMapButton, bMaps);
  909. SetVisibility(LogisticsDailyReportButton,
  910. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  911. SetVisibility(ReadyToGoItemsButton,
  912. ClientFactory.IsSupported<DeliveryItem>()
  913. && Security.IsAllowed<CanViewLogisticsReadyToGo>()
  914. && Security.IsAllowed<ViewDesktopReadyToGoScreen>());
  915. SetVisibility(DispatchButton, Security.CanView<Shipment>()
  916. && Security.CanView<DeliveryItem>()
  917. && Security.IsAllowed<ViewDesktopRackListScreen>());
  918. SetVisibility(RequisitionsButton, Security.CanView<Requisition>() && Security.IsAllowed<ViewDesktopSiteRequisitionsScreen>());
  919. SetVisibility(DeliveriesButton, Security.IsAllowed<CanViewDeliveriesModule>() && Security.IsAllowed<ViewDesktopDeliveriesScren>());
  920. SetVisibility(DeliveredItemsButton,
  921. ClientFactory.IsSupported<DeliveryItem>()
  922. && Security.IsAllowed<CanViewDeliveredOnSite>()
  923. && Security.IsAllowed<ViewDesktopDeliveredOnSiteScreen>());
  924. SetVisibility(ConsignmentButton, Security.CanView<Consignment>() && Security.IsAllowed<ViewDesktopIncomingConsignmentsScreen>());
  925. SetVisibleIfEither(LogisticsTaskSeparator1,
  926. new FrameworkElement[]
  927. {
  928. LogisticsDashboardButton, LogisticsMessagesButton, LogisticsTaskButton, LogisticsAttendanceButton, LogisticsMapButton,
  929. LogisticsDailyReportButton
  930. },
  931. new FrameworkElement[]
  932. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton });
  933. SetVisibleIfEither(LogisticsTaskSeparator2,
  934. new FrameworkElement[]
  935. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton },
  936. new FrameworkElement[] { ConsignmentButton });
  937. SetTabVisibleIfAny(LogisticsTab, DispatchButton, RequisitionsButton, DeliveriesButton, ReadyToGoItemsButton,
  938. DeliveredItemsButton,
  939. ConsignmentButton);
  940. }
  941. private void SetupManufacturingTab(bool bMaps)
  942. {
  943. if (!Security.IsAllowed<ViewDesktopManufacturingTab>())
  944. return;
  945. SetVisibility(ManufacturingDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  946. SetVisibility(ManufacturingMessagesButton, Security.CanView<Notification>());
  947. SetVisibility(ManufacturingTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  948. SetVisibility(ManufacturingAttendanceButton,
  949. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  950. SetVisibility(ManufacturingMapButton, bMaps);
  951. SetVisibility(ManufacturingDailyReportButton,
  952. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  953. SetVisibleIfAny(ManufacturingTaskSeparator,
  954. new FrameworkElement[]
  955. {
  956. ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton, ManufacturingAttendanceButton,
  957. ManufacturingMapButton, ManufacturingDailyReportButton
  958. });
  959. SetVisibility(DesignManagementButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopDesignManagementScreen>());
  960. SetVisibility(ManufacturingDesignSeparator, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopDesignManagementScreen>());
  961. SetVisibility(FactoryStatusButton,
  962. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket>()
  963. && Security.IsAllowed<CanViewFactoryStatus>()
  964. && Security.IsAllowed<ViewDesktopManufacturingStatusScreen>());
  965. SetVisibility(FactoryAllocationButton,
  966. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket, ManufacturingPacketStage>()
  967. && Security.IsAllowed<CanViewFactoryAllocation>()
  968. && Security.IsAllowed<ViewDesktopFactoryAllocationScreen>());
  969. //SetVisibility(FactoryScheduleButton, ClientFactory.IsSupported<Booking>() && ClientFactory.IsEnabled<>());
  970. SetVisibility(FactoryFloorButton,
  971. ClientFactory.IsSupported<ManufacturingPacket>()
  972. && Security.IsAllowed<CanViewFactoryFloor>()
  973. && Security.IsAllowed<ViewDesktopFactoryFloorScreen>());
  974. //SetVisibility(FactoryReadyButton, ClientFactory.IsSupported<ManufacturingPacket>() && Security.IsAllowed<CanViewFactoryReadyToGo>());
  975. SetVisibleIfAny(ManufacturingActionSeparator,
  976. new FrameworkElement[]
  977. {
  978. FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton
  979. });
  980. SetVisibleIfAny(ManufacturingActions, ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton,
  981. ManufacturingAttendanceButton, ManufacturingDailyReportButton, FactoryStatusButton, FactoryAllocationButton,
  982. FactoryFloorButton);
  983. SetTabVisibleIfAny(ManufacturingTab, FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton);
  984. }
  985. private void SetupProjectsTab(bool bMaps)
  986. {
  987. if (!Security.IsAllowed<ViewDesktopProjectsTab>())
  988. return;
  989. SetVisibility(ProjectsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  990. SetVisibility(ProjectMessagesButton, Security.CanView<Notification>());
  991. SetVisibility(ProjectTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  992. SetVisibility(ProjectAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  993. SetVisibility(ProjectsMapButton, bMaps);
  994. SetVisibility(ProjectDailyReportButton,
  995. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  996. SetVisibility(ProjectsButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopProjectsScreen>());
  997. //SetVisibility(ServiceButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopServiceScreen>());
  998. SetVisibility(ProjectPlannerButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopProjectPlannerScreen>());
  999. SetVisibleIfEither(ProjectTaskSeparator,
  1000. new FrameworkElement[]
  1001. {
  1002. ProjectsDashboardButton, ProjectMessagesButton, ProjectTaskButton, ProjectAttendanceButton, ProjectsMapButton,
  1003. ProjectDailyReportButton
  1004. }, new FrameworkElement[] { QuotesButton, ProjectsButton, ProjectPlannerButton });
  1005. SetVisibility(QuotesButton, Security.CanView<Quote>() && Security.IsAllowed<ViewDesktopQuotesScreen>());
  1006. SetVisibility(KitsMasterList, Security.CanView<Kit>() && Security.IsAllowed<ViewDesktopProductKitsScreen>());
  1007. SetVisibility(CostSheetsMasterList, Security.CanView<CostSheet>() && Security.IsAllowed<ViewDesktopCostSheetsScreen>());
  1008. SetVisibleIfAny(ProjectsSetup, KitsMasterList, CostSheetsMasterList);
  1009. //ProjectsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  1010. //ProjectReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  1011. SetTabVisibleIfAny(ProjectsTab, QuotesButton, ProjectsButton, ProjectPlannerButton, CostSheetsMasterList, KitsMasterList);
  1012. }
  1013. private void SetupDock<TSecurityDescriptor>(LayoutAnchorable layout, IDockPanel dock)
  1014. where TSecurityDescriptor : ISecurityDescriptor, new()
  1015. {
  1016. if (Security.IsAllowed<TSecurityDescriptor>())
  1017. {
  1018. if (!DockGroup.Children.Any(x => x == layout))
  1019. {
  1020. DockGroup.Children.Add(layout);
  1021. }
  1022. if (layout.IsVisible && (ClientFactory.UserGuid != Guid.Empty))
  1023. dock.Setup();
  1024. }
  1025. else
  1026. {
  1027. DockGroup.RemoveChild(layout);
  1028. }
  1029. }
  1030. private void LoadApplicationState()
  1031. {
  1032. if (ClientFactory.UserGuid != Guid.Empty)
  1033. {
  1034. _ribbon.IsCollapsed = false;
  1035. if (OutstandingDailyReports(false))
  1036. {
  1037. MessageWindow.ShowMessage("There are outstanding Daily Reports that must be filled out before continuing!"
  1038. + "\n\nAccess to PRS is restricted until this is corrected.",
  1039. "Outstanding Reports");
  1040. var dailyReportPanel = LoadWindow<DailyReport>(ProjectDailyReportButton);
  1041. if(dailyReportPanel is not null)
  1042. {
  1043. dailyReportPanel.OnTimeSheetConfirmed += e =>
  1044. {
  1045. if (!OutstandingDailyReports(true))
  1046. {
  1047. ConfigureMainScreen(null);
  1048. LoadApplicationState();
  1049. }
  1050. };
  1051. }
  1052. return;
  1053. }
  1054. using (new WaitCursor())
  1055. {
  1056. _ribbon.IsCollapsed = false;
  1057. LoadInitialWindow();
  1058. }
  1059. }
  1060. }
  1061. private void LoadInitialWindow()
  1062. {
  1063. var app = new LocalConfiguration<AppSettings>().Load();
  1064. if (app.Settings.ContainsKey("CurrentPanel"))
  1065. {
  1066. try
  1067. {
  1068. var bFound = false;
  1069. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1070. if (module.Length == 2)
  1071. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1072. {
  1073. if (String.Equals(tab.Header, module.First()))
  1074. {
  1075. _ribbon.SelectedTabItem = tab;
  1076. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1077. {
  1078. foreach (var item in bar.Items)
  1079. {
  1080. var button = item as Fluent.Button;
  1081. if (button != null && String.Equals(button.Header, module.Last()))
  1082. {
  1083. bFound = true;
  1084. button.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
  1085. break;
  1086. }
  1087. }
  1088. if (bFound)
  1089. break;
  1090. }
  1091. }
  1092. if (bFound)
  1093. break;
  1094. }
  1095. }
  1096. catch (Exception e)
  1097. {
  1098. MessageWindow.ShowError($"Unable to load {app.Settings["CurrentPanel"]}", e);
  1099. }
  1100. }
  1101. }
  1102. private void _ribbon_OnLoaded(object sender, RoutedEventArgs e)
  1103. {
  1104. _ribbon.SelectedTabItem = CurrentTab;
  1105. }
  1106. private void LoadSecondaryWindows()
  1107. {
  1108. if (ClientFactory.UserGuid != Guid.Empty)
  1109. {
  1110. var windows = App.DatabaseSettings.SecondaryWindows;
  1111. foreach (var key in windows.Keys.ToArray())
  1112. {
  1113. SecondaryWindows[key] = new SecondaryWindow(
  1114. key,
  1115. windows[key].Item1,
  1116. windows[key].Item2,
  1117. windows[key].Item3,
  1118. windows[key].Item4,
  1119. windows[key].Item5,
  1120. windows[key].Item6
  1121. );
  1122. SecondaryWindows[key].Closed += (o, e) => { SecondaryWindows.Remove(key); };
  1123. SecondaryWindows[key].Show();
  1124. }
  1125. }
  1126. else
  1127. {
  1128. foreach (var key in SecondaryWindows.Keys.ToArray())
  1129. {
  1130. App.IsClosing = true;
  1131. SecondaryWindows[key].Close();
  1132. App.IsClosing = false;
  1133. }
  1134. }
  1135. }
  1136. private Fluent.RibbonTabItem GetTabItem(FrameworkElement? sender)
  1137. {
  1138. if (sender == null)
  1139. throw new Exception("No Tab Found!");
  1140. if (sender is Fluent.RibbonTabItem)
  1141. return (Fluent.RibbonTabItem)sender;
  1142. return GetTabItem(sender.Parent as FrameworkElement);
  1143. }
  1144. private IEnumerable<IBasePanel> Panels
  1145. {
  1146. get
  1147. {
  1148. if(PanelHost.CurrentPanel is not null)
  1149. {
  1150. yield return PanelHost.CurrentPanel;
  1151. }
  1152. foreach(var window in SecondaryWindows.Values)
  1153. {
  1154. yield return window.Panel;
  1155. }
  1156. }
  1157. }
  1158. private T? LoadWindow<T>(Fluent.Button sender) where T : class, IBasePanel, new()
  1159. {
  1160. return LoadWindow<T>(sender, new CancelEventArgs());
  1161. }
  1162. private T? LoadWindow<T>(Fluent.Button sender, CancelEventArgs cancel) where T : class, IBasePanel, new()
  1163. {
  1164. using (new WaitCursor())
  1165. {
  1166. UnloadWindow(cancel);
  1167. if (cancel.Cancel)
  1168. {
  1169. return null;
  1170. }
  1171. CurrentTab = GetTabItem(sender);
  1172. CurrentButton = sender;
  1173. //CurrentButton.IsSelected = true;
  1174. UpdateRibbonColors();
  1175. var moduleName = sender.Header?.ToString() ?? "";
  1176. var panel = PanelHost.LoadPanel<T>(moduleName);
  1177. ContentControl.Content = panel;
  1178. Title =
  1179. $"{moduleName} - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1180. PanelHost.Refresh();
  1181. if (panel is NotificationPanel)
  1182. {
  1183. Logger.Send(LogType.Information, ClientFactory.UserID, "Disabling Heartbeat");
  1184. NotificationsWatchDog.IsEnabled = false;
  1185. Notifications.Visibility = Visibility.Collapsed;
  1186. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  1187. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  1188. }
  1189. else
  1190. {
  1191. ReloadNotifications();
  1192. }
  1193. if (sender != null)
  1194. {
  1195. var settings = new LocalConfiguration<AppSettings>().Load();
  1196. var module = string.Format("{0} / {1}", CurrentTab?.Header, sender.Header);
  1197. if (!settings.Settings.ContainsKey("CurrentPanel") || module != settings.Settings["CurrentPanel"])
  1198. {
  1199. settings.Settings["CurrentPanel"] = module;
  1200. try
  1201. {
  1202. new LocalConfiguration<AppSettings>().Save(settings);
  1203. }
  1204. catch (Exception e)
  1205. {
  1206. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1207. }
  1208. }
  1209. }
  1210. return panel;
  1211. }
  1212. }
  1213. private void UpdateRibbonColors()
  1214. {
  1215. foreach (var tab in _ribbon.Tabs)
  1216. {
  1217. bool bFound = false;
  1218. foreach (var grp in tab.Groups)
  1219. {
  1220. foreach (var btn in grp.Items)
  1221. {
  1222. if (btn is Fluent.Button fluentbutton)
  1223. {
  1224. bFound = bFound || (btn == CurrentButton);
  1225. fluentbutton.Background = (btn == CurrentButton) ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1226. fluentbutton.Foreground = (btn == CurrentButton) ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1227. }
  1228. }
  1229. tab.Background = bFound ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1230. tab.Foreground = bFound ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1231. }
  1232. }
  1233. }
  1234. private static void StartLocalDatabase(IProgress<string> progress)
  1235. {
  1236. var dirName = Path.GetDirectoryName(App.DatabaseSettings.FileName);
  1237. if (!Directory.Exists(dirName) && dirName != null)
  1238. Directory.CreateDirectory(dirName);
  1239. var FileName = App.DatabaseSettings.FileName;
  1240. var Exists = File.Exists(FileName);
  1241. progress.Report("Configuring Stores");
  1242. DbFactory.Stores = CoreUtils.TypeList(
  1243. new[]
  1244. {
  1245. typeof(Store<>).Assembly,
  1246. typeof(EquipmentStore).Assembly
  1247. },
  1248. myType =>
  1249. myType.IsClass
  1250. && !myType.IsAbstract
  1251. && !myType.IsGenericType
  1252. && myType.GetInterfaces().Contains(typeof(IStore))
  1253. ).ToArray();
  1254. DbFactory.ProviderFactory = new SQLiteProviderFactory(App.DatabaseSettings.FileName);
  1255. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  1256. DbFactory.Logo = App.DatabaseSettings.Logo;
  1257. progress.Report("Starting Local Database");
  1258. DbFactory.Start();
  1259. ClientFactory.DatabaseID = DbFactory.ID;
  1260. progress.Report("Checking Database");
  1261. var users = DbFactory.NewProvider(Logger.Main).Load<User>();
  1262. if (!users.Any())
  1263. {
  1264. var user = new User { UserID = "ADMIN", Password = "admin" };
  1265. DbFactory.NewProvider(Logger.Main).Save(user);
  1266. var employee = DbFactory.NewProvider(Logger.Main).Load(new Filter<Employee>(x => x.Code).IsEqualTo("ADMIN")).FirstOrDefault();
  1267. employee ??= new Employee { Code = "ADMIN", Name = "Administrator Account" };
  1268. employee.UserLink.ID = user.ID;
  1269. DbFactory.NewProvider(Logger.Main).Save(employee);
  1270. }
  1271. StoreUtils.GoogleAPIKey = App.DatabaseSettings.GoogleAPIKey;
  1272. Job.JobNumberPrefix = App.DatabaseSettings.JobPrefix;
  1273. PurchaseOrder.PONumberPrefix = App.DatabaseSettings.PurchaseOrderPrefix;
  1274. }
  1275. #endregion
  1276. #region Login Management
  1277. private ValidationStatus? TryAutoLogin()
  1278. {
  1279. ValidationStatus? result = null;
  1280. if (App.DatabaseSettings.LoginType == LoginType.UserID)
  1281. {
  1282. try
  1283. {
  1284. result = ClientFactory.Validate(App.DatabaseSettings.UserID, App.DatabaseSettings.Password);
  1285. }
  1286. catch (Exception e)
  1287. {
  1288. MessageWindow.ShowError("Error connecting to server.\nPlease check the server URL and port number.", e);
  1289. result = null;
  1290. }
  1291. if (result == ValidationStatus.INVALID)
  1292. {
  1293. MessageWindow.ShowMessage("Unable to Login with User ID: " + App.DatabaseSettings.UserID, "Login failed");
  1294. }
  1295. }
  1296. return result;
  1297. }
  1298. private ValidationStatus? DoLogin()
  1299. {
  1300. ValidationStatus? result = null;
  1301. if (result != ValidationStatus.VALID)
  1302. {
  1303. var login = new PinLogin(CoreUtils.GetVersion(), result ?? ValidationStatus.INVALID);
  1304. if (login.ShowDialog() == true)
  1305. {
  1306. result = ValidationStatus.VALID;
  1307. }
  1308. }
  1309. return result ?? ValidationStatus.INVALID;
  1310. }
  1311. /// <summary>
  1312. /// To be called after <see cref="DoLogin(bool)"/> and if a valid login session exists. Configures the main screen and loads the windows.
  1313. /// </summary>
  1314. /// <param name="progress">If not <see langword="null"/>, then rather than opening a new progress window, just uses that.</param>
  1315. private void AfterLogin(IProgress<string>? progress)
  1316. {
  1317. Logger.Send(LogType.Information, "", "Loading employee");
  1318. LoadCurrentEmployee();
  1319. if (CheckTimesheetBypass(true))
  1320. {
  1321. UpdateCurrentLogin();
  1322. }
  1323. else
  1324. {
  1325. MessageWindow.ShowMessage("You must clock on before logging in to PRS!", "Not clocked in.");
  1326. ClientFactory.InvalidateUser();
  1327. App.EmployeeID = Guid.Empty;
  1328. App.EmployeeName = "";
  1329. App.EmployeeCode = "";
  1330. App.EmployeeEmail = "";
  1331. }
  1332. Logger.Send(LogType.Information, "", "Setting colours");
  1333. if(progress is null)
  1334. {
  1335. ApplyColorScheme();
  1336. }
  1337. else
  1338. {
  1339. Dispatcher.Invoke(ApplyColorScheme);
  1340. }
  1341. Logger.Send(LogType.Information, "", "Configuring main window");
  1342. ConfigureMainScreen(progress);
  1343. Logger.Send(LogType.Information, "", "Loading current window");
  1344. if(progress is null)
  1345. {
  1346. LoadApplicationState();
  1347. }
  1348. else
  1349. {
  1350. Dispatcher.Invoke(LoadApplicationState);
  1351. }
  1352. Logger.Send(LogType.Information, "", "Loading secondary window");
  1353. if(progress is null)
  1354. {
  1355. LoadSecondaryWindows();
  1356. }
  1357. else
  1358. {
  1359. Dispatcher.Invoke(LoadSecondaryWindows);
  1360. }
  1361. //if (_ribbon.Menu.IsVisible)
  1362. //{
  1363. // _ribbon.;
  1364. //}
  1365. }
  1366. /// <summary>
  1367. /// 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.
  1368. /// </summary>
  1369. private void UpdateCurrentLogin()
  1370. {
  1371. if (CoreUtils.GetVersion().Equals("???"))
  1372. return;
  1373. // Register this station with the Server
  1374. // Later on, the heartbeat will check to make sure
  1375. // that the StationID hasn't changed. If it has,
  1376. // then we've logged in somewhere else and we'll
  1377. // drop out of this station
  1378. var curr = new Client<Login>().Query(
  1379. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  1380. null
  1381. ).Rows.FirstOrDefault();
  1382. if (curr != null)
  1383. {
  1384. var c = curr.ToObject<Login>();
  1385. c.StationID = station.StationID;
  1386. station = c;
  1387. }
  1388. else
  1389. {
  1390. station.User.ID = ClientFactory.UserGuid;
  1391. station.TimeStamp = DateTime.Now;
  1392. }
  1393. new Client<Login>().Save(station, "", (o, e) => { });
  1394. }
  1395. private void LoadCurrentEmployee()
  1396. {
  1397. var me = new Client<Employee>().Query(
  1398. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid),
  1399. Columns.None<Employee>().Add(x => x.ID).Add(x => x.Email).Add(x => x.Name)
  1400. );
  1401. App.EmployeeID = me.Rows.FirstOrDefault()?.Get<Employee, Guid>(x => x.ID) ?? Guid.Empty;
  1402. App.EmployeeName = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Name) ?? "";
  1403. App.EmployeeCode = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Code) ?? "";
  1404. App.EmployeeEmail = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Email) ?? "";
  1405. }
  1406. private void ExecuteLogout()
  1407. {
  1408. new Client<Login>().Delete(station, "");
  1409. station.ID = Guid.Empty;
  1410. App.EmployeeID = Guid.Empty;
  1411. App.EmployeeName = "";
  1412. App.EmployeeEmail = "";
  1413. }
  1414. /// <summary>
  1415. /// Logs the user out and unloads windows
  1416. /// </summary>
  1417. /// <param name="message">A message to display as the reason for logging out, or <c>null</c> for no message.</param>
  1418. private bool Logout(string? message = null, bool force = false)
  1419. {
  1420. // 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,
  1421. // all the queries that get called here will throw exceptions and thus break our system, failing to log out.
  1422. try
  1423. {
  1424. FinalizeAutoTimesheet();
  1425. }
  1426. catch
  1427. {
  1428. if (!force) throw;
  1429. }
  1430. // Try to unload the window;
  1431. try
  1432. {
  1433. UnloadWindow(null);
  1434. if (DatabaseType == DatabaseType.Standalone && !CoreUtils.GetVersion().Equals("???"))
  1435. scheduler.Stop();
  1436. }
  1437. catch
  1438. {
  1439. if (!force) throw;
  1440. }
  1441. // Next, try to set things to being empty
  1442. try
  1443. {
  1444. if (!CoreUtils.GetVersion().Equals("???"))
  1445. if (station.ID != Guid.Empty)
  1446. {
  1447. ExecuteLogout();
  1448. }
  1449. ClearTrackingKanban();
  1450. }
  1451. catch
  1452. {
  1453. if (!force) throw;
  1454. }
  1455. ClientFactory.InvalidateUser();
  1456. ConfigureMainScreen(null);
  1457. LoadSecondaryWindows();
  1458. if (message != null)
  1459. {
  1460. MessageWindow.ShowMessage(message, "Logged out");
  1461. }
  1462. if (DoLogin() == ValidationStatus.VALID)
  1463. {
  1464. AfterLogin(null);
  1465. }
  1466. return true;
  1467. }
  1468. #endregion
  1469. #region Timesheets
  1470. private void RefreshTimeSheets()
  1471. {
  1472. if (App.EmployeeID == Guid.Empty)
  1473. return;
  1474. var filter = new Filter<TimeSheet>(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID);
  1475. filter = filter.And(new Filter<TimeSheet>(x => x.Confirmed).IsEqualTo(DateTime.MinValue).Or(x => x.Date).IsEqualTo(DateTime.Today));
  1476. _timesheets = new Client<TimeSheet>().Query(
  1477. filter,
  1478. Columns.None<TimeSheet>().Add(
  1479. x => x.ID,
  1480. x => x.Date,
  1481. x => x.Finish
  1482. )
  1483. );
  1484. }
  1485. private CoreTable GetTimesheet()
  1486. {
  1487. return new Client<TimeSheet>().Query(
  1488. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today)
  1489. .And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID)
  1490. .And(x => x.Finish).IsEqualTo(TimeSpan.Zero)
  1491. );
  1492. }
  1493. private bool CheckTimesheetBypass(bool message)
  1494. {
  1495. if (!ClientFactory.IsSupported<TimeSheet>())
  1496. return true;
  1497. var isClockedOn = IsClockedOn();
  1498. if (!Security.IsAllowed<CanBypassTimeBench>())
  1499. {
  1500. if (!isClockedOn)
  1501. {
  1502. if (message)
  1503. MessageBox.Show("You must clock on before opening this screen");
  1504. return false;
  1505. }
  1506. return true;
  1507. }
  1508. if (Security.IsAllowed<AutoGenerateTimesheet>())
  1509. if (!isClockedOn)
  1510. {
  1511. var ts = new TimeSheet();
  1512. ts.Date = DateTime.Today;
  1513. ts.Start = DateTime.Now.TimeOfDay;
  1514. ts.EmployeeLink.ID = App.EmployeeID;
  1515. ts.Notes = "Automatic Login from PRS Desktop";
  1516. new Client<TimeSheet>().Save(ts, "AutoLogon because Timebench Bypass is enabled", (o, e) => { });
  1517. }
  1518. return true;
  1519. }
  1520. private bool IsClockedOn()
  1521. {
  1522. RefreshTimeSheets();
  1523. if (_timesheets == null)
  1524. return false;
  1525. return _timesheets.Rows.Any(r =>
  1526. r.Get<TimeSheet, DateTime>(c => c.Date).Date == DateTime.Today && r.Get<TimeSheet, TimeSpan>(c => c.Finish) == new TimeSpan());
  1527. }
  1528. private void FinalizeAutoTimesheet()
  1529. {
  1530. if (Security.IsAllowed<AutoGenerateTimesheet>())
  1531. {
  1532. var check = new Client<TimeSheet>().Query(
  1533. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today).And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID).And(x => x.Finish)
  1534. .IsEqualTo(TimeSpan.Zero)
  1535. );
  1536. if (check.Rows.Any())
  1537. {
  1538. var ts = check.Rows.First().ToObject<TimeSheet>();
  1539. if (DateTime.Now.TimeOfDay < ts.Start.Add(new TimeSpan(0, 2, 0)))
  1540. {
  1541. new Client<TimeSheet>().Delete(ts, "Deleting Auto TimeSheet because TimeBench Bypass is enabled", (o, ex) => { });
  1542. }
  1543. else
  1544. {
  1545. ts.Finish = DateTime.Now.TimeOfDay;
  1546. new Client<TimeSheet>().Save(ts, "Clocking off Auto Timesheet because Timesheet Bypass is enabled", (o, ex) => { });
  1547. }
  1548. }
  1549. }
  1550. }
  1551. #endregion
  1552. private string CurrentPanelSlug()
  1553. {
  1554. var app = new LocalConfiguration<AppSettings>().Load();
  1555. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1556. return module.LastOrDefault()?.Replace(" ", "_").Replace("/", "") ?? "";
  1557. }
  1558. private bool ShowHelp()
  1559. {
  1560. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + CurrentPanelSlug()) { UseShellExecute = true });
  1561. return true;
  1562. }
  1563. private void Wiki_Click(object sender, RoutedEventArgs e)
  1564. {
  1565. ShowHelp();
  1566. }
  1567. private void Window_Loaded(object sender, RoutedEventArgs e)
  1568. {
  1569. }
  1570. private void UnloadWindow(CancelEventArgs? cancel)
  1571. {
  1572. PanelHost.UnloadPanel(cancel);
  1573. if (cancel?.Cancel == true)
  1574. {
  1575. return;
  1576. }
  1577. Title =
  1578. $" - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1579. if (CurrentTab is not null)
  1580. {
  1581. var border = VisualUtils.EnumChildrenOfType(CurrentTab, typeof(Border)).LastOrDefault();
  1582. if (border != null)
  1583. {
  1584. ((Border)border).Background = new SolidColorBrush(Colors.Transparent);
  1585. ((Border)border).BorderBrush = new SolidColorBrush(Colors.Transparent);
  1586. }
  1587. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  1588. if (ReportsBar is not null)
  1589. {
  1590. ReportsBar.Items.Clear();
  1591. ReportsBar.Visibility = Visibility.Collapsed;
  1592. ReportsBar.IsLauncherVisible = false;
  1593. }
  1594. var ActionBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  1595. if (ActionBar is not null)
  1596. {
  1597. ActionBar.IsLauncherVisible = false;
  1598. foreach (var module in CurrentModules)
  1599. ActionBar.Items.Remove(module);
  1600. }
  1601. }
  1602. CurrentTab = null;
  1603. CurrentButton = null;
  1604. ContentControl.Content = null;
  1605. }
  1606. private void SecondaryWindow_Click(object sender, RoutedEventArgs e)
  1607. {
  1608. var panel = PanelHost.CurrentPanel;
  1609. if (panel is null) return;
  1610. var id = Guid.NewGuid();
  1611. var window = new Tuple<string, string, double, double, double, double>(
  1612. panel.GetType().EntityName(),
  1613. PanelHost.CurrentModuleName,
  1614. Left + 100,
  1615. Top + 100,
  1616. Width - 200,
  1617. Height - 200
  1618. );
  1619. App.DatabaseSettings.SecondaryWindows[id] = window;
  1620. new LocalConfiguration<DatabaseSettings>(App.Profile).Save(App.DatabaseSettings);
  1621. SecondaryWindows[id] = new SecondaryWindow(
  1622. id,
  1623. window.Item1,
  1624. window.Item2,
  1625. window.Item3,
  1626. window.Item4,
  1627. window.Item5,
  1628. window.Item6
  1629. );
  1630. SecondaryWindows[id].Show();
  1631. }
  1632. private void RibbonWindow_Activated(object sender, EventArgs e)
  1633. {
  1634. }
  1635. private void RegisterModules(IProgress<string> progress)
  1636. {
  1637. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1638. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1639. foreach (var item in bar.Items)
  1640. Dispatcher.Invoke(() =>
  1641. {
  1642. var button = item as RibbonButton;
  1643. if (button != null && button.Label != "Refresh")
  1644. if (bar.Header.Equals("Actions"))
  1645. Modules.Register(button.Label);
  1646. });
  1647. }
  1648. #region Visibility
  1649. private void SetVisibility(FrameworkElement button, bool visible)
  1650. {
  1651. var vResult = true;
  1652. var eResult = ClientFactory.UserGuid != Guid.Empty && visible;
  1653. button.Visibility = vResult && eResult ? Visibility.Visible : Visibility.Collapsed;
  1654. if (button is RibbonButton rb)
  1655. {
  1656. CustomModules.Register(rb.Label);
  1657. rb.IsEnabled = !OutstandingDailyReports(false);
  1658. }
  1659. }
  1660. private static void SetVisibleIfEither(FrameworkElement separator, FrameworkElement[] left, FrameworkElement[] right)
  1661. {
  1662. var bLeft = false;
  1663. foreach (var button in left)
  1664. bLeft = bLeft || button.Visibility == Visibility.Visible;
  1665. var bRight = false;
  1666. foreach (var button in right)
  1667. bRight = bRight || button.Visibility == Visibility.Visible;
  1668. separator.Visibility = bLeft && bRight ? Visibility.Visible : Visibility.Collapsed;
  1669. }
  1670. private static void SetVisibleIfAny(FrameworkElement separator, params FrameworkElement[] buttons)
  1671. {
  1672. var bVisible = false;
  1673. foreach (var button in buttons)
  1674. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1675. separator.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1676. }
  1677. private static void SetTabVisibleIfAny(Fluent.RibbonTabItem tab, params FrameworkElement[] buttons)
  1678. {
  1679. var bVisible = false;
  1680. foreach (var button in buttons)
  1681. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1682. tab.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1683. }
  1684. #endregion
  1685. private static Fluent.RibbonGroupBox? FindRibbonBar(Fluent.RibbonTabItem tab, Func<Fluent.RibbonGroupBox, bool> predicate)
  1686. {
  1687. foreach (var group in tab.Groups)
  1688. {
  1689. if (group != null)
  1690. if (predicate.Invoke(group))
  1691. return group;
  1692. }
  1693. return null;
  1694. }
  1695. #region Button Event Handlers
  1696. #region Common
  1697. private void Tasks_Checked(object sender, RoutedEventArgs e)
  1698. {
  1699. //LoadWindow<KanbanPanel>((RibbonButton)sender);
  1700. LoadWindow<TaskPanel>((Fluent.Button)sender);
  1701. }
  1702. private void DataEntry_Click(object sender, RoutedEventArgs e)
  1703. {
  1704. LoadWindow<DataEntryPanel>((Fluent.Button)sender);
  1705. }
  1706. private void Attendance_Checked(object sender, RoutedEventArgs e)
  1707. {
  1708. LoadWindow<AttendancePanel>((Fluent.Button)sender);
  1709. }
  1710. #endregion
  1711. #region Quotes
  1712. private void Quotes_Checked(object sender, RoutedEventArgs e)
  1713. {
  1714. LoadWindow<QuotePanel>((Fluent.Button)sender);
  1715. }
  1716. #endregion
  1717. #region Projects
  1718. private void Jobs_Checked(object sender, RoutedEventArgs e)
  1719. {
  1720. LoadWindow<ProjectsPanel>((Fluent.Button)sender);
  1721. }
  1722. private void ProjectPlanner_Checked(object sender, RoutedEventArgs e)
  1723. {
  1724. LoadWindow<JobResourcePlannerPanel>((Fluent.Button)sender);
  1725. }
  1726. private void DesignManagement_Checked(object sender, RoutedEventArgs e)
  1727. {
  1728. LoadWindow<StagingPanel>((Fluent.Button)sender);
  1729. }
  1730. //private void Service_Checked(object sender, RoutedEventArgs e)
  1731. //{
  1732. // LoadWindow<ServicePanel>((Fluent.Button)sender);
  1733. //}
  1734. #endregion
  1735. #region Manufacturing
  1736. private void ManufacturingMenu_Checked(object sender, RoutedEventArgs e)
  1737. {
  1738. LoadWindow<ManufacturingPanel>((Fluent.Button)sender);
  1739. }
  1740. private void FactoryFloorButton_Click(object sender, RoutedEventArgs e)
  1741. {
  1742. LoadWindow<FactoryPanel>((Fluent.Button)sender);
  1743. }
  1744. #endregion
  1745. #region Logistics
  1746. private void ReadyToGoMenu_Checked(object sender, RoutedEventArgs e)
  1747. {
  1748. LoadWindow<ReadyToGoPanel>((Fluent.Button)sender);
  1749. }
  1750. private void DispatchMenu_Checked(object sender, RoutedEventArgs e)
  1751. {
  1752. LoadWindow<DispatchPanel>((Fluent.Button)sender);
  1753. }
  1754. private void Requisitions_Checked(object sender, RoutedEventArgs e)
  1755. {
  1756. LoadWindow<RequisitionPanel>((Fluent.Button)sender);
  1757. }
  1758. #endregion
  1759. #region Products
  1760. #endregion
  1761. #region Human Resources
  1762. private void Timesheets_Checked(object sender, RoutedEventArgs e)
  1763. {
  1764. LoadWindow<TimesheetPanel>((Fluent.Button)sender);
  1765. }
  1766. #endregion
  1767. #region Accounts
  1768. #endregion
  1769. #region Equipment
  1770. private void Equipment_Checked(object sender, RoutedEventArgs e)
  1771. {
  1772. LoadWindow<EquipmentPanel>((Fluent.Button)sender);
  1773. }
  1774. private void EquipmentMaintenance_Checked(object sender, RoutedEventArgs e)
  1775. {
  1776. LoadWindow<EquipmentMaintenancePanel>((Fluent.Button)sender);
  1777. }
  1778. #endregion
  1779. #region Dashboards
  1780. #endregion
  1781. private void Console_Click(object sender, RoutedEventArgs a)
  1782. {
  1783. if (_console is null)
  1784. {
  1785. _console = new DesktopConsole("Console");
  1786. _console.Closing += (o, args) => _console = null;
  1787. }
  1788. _console.Show();
  1789. }
  1790. //private void Purchases_Checked(object sender, RoutedEventArgs e)
  1791. //{
  1792. // LoadWindow(PurchasesMenu, new PurchasesPanel());
  1793. //}
  1794. private void Maps_Checked(object sender, RoutedEventArgs e)
  1795. {
  1796. LoadWindow<MapsPanel>((Fluent.Button)sender);
  1797. }
  1798. private void RefreshMenu_Click(object sender, RoutedEventArgs e)
  1799. {
  1800. PanelHost.Refresh();
  1801. }
  1802. private void UserSetup_Click(object sender, RoutedEventArgs e)
  1803. {
  1804. LoadWindow<UserPanel>((Fluent.Button)sender);
  1805. }
  1806. private void Employees_Click(object sender, RoutedEventArgs e)
  1807. {
  1808. LoadWindow<EmployeePanel>((Fluent.Button)sender);
  1809. }
  1810. private void Trackers_Click(object sender, RoutedEventArgs e)
  1811. {
  1812. LoadWindow<GPSTrackers>((Fluent.Button)sender);
  1813. }
  1814. private void DeliveredOnSiteMenu_Checked(object sender, RoutedEventArgs e)
  1815. {
  1816. LoadWindow<DeliveredOnSitePanel>((Fluent.Button)sender);
  1817. }
  1818. private void Products_Checked(object sender, RoutedEventArgs e)
  1819. {
  1820. LoadWindow<ProductsPanel>((Fluent.Button)sender);
  1821. }
  1822. private void StockLocations_Checked(object sender, RoutedEventArgs e)
  1823. {
  1824. LoadWindow<StockLocationPanel>((Fluent.Button)sender);
  1825. }
  1826. private void StockMovements_Checked(object sender, RoutedEventArgs e)
  1827. {
  1828. LoadWindow<StockMovementPanel>((Fluent.Button)sender);
  1829. }
  1830. private void StockForecastButton_Clicked(object sender, RoutedEventArgs e)
  1831. {
  1832. LoadWindow<StockForecastPanel>((Fluent.Button)sender);
  1833. }
  1834. private void ReservationManagementButton_Clicked(object sender, RoutedEventArgs e)
  1835. {
  1836. LoadWindow<ReservationManagementPanel>((Fluent.Button)sender);
  1837. }
  1838. private void KitsMasterList_Click(object sender, RoutedEventArgs e)
  1839. {
  1840. LoadWindow<KitPanel>((Fluent.Button)sender);
  1841. }
  1842. private void CostSheetsMasterList_Click(object sender, RoutedEventArgs e)
  1843. {
  1844. LoadWindow<CostSheetPanel>((Fluent.Button)sender);
  1845. }
  1846. private void LeaveRequestsButton_Click(object sender, RoutedEventArgs e)
  1847. {
  1848. LoadWindow<LeaveRequestPanel>((Fluent.Button)sender);
  1849. }
  1850. private void MeetingsButton_Click(object sender, RoutedEventArgs e)
  1851. {
  1852. LoadWindow<MeetingPanel>((Fluent.Button)sender);
  1853. }
  1854. private void OrgChartButton_Click(object sender, RoutedEventArgs e)
  1855. {
  1856. LoadWindow<OrgChartPanel>((Fluent.Button)sender);
  1857. }
  1858. private void SupplierList_Click(object sender, RoutedEventArgs e)
  1859. {
  1860. LoadWindow<SupplierPanel>((Fluent.Button)sender);
  1861. }
  1862. private void CustomerList_Click(object sender, RoutedEventArgs e)
  1863. {
  1864. LoadWindow<CustomerPanel>((Fluent.Button)sender);
  1865. }
  1866. private void CalendarButton_Click(object sender, RoutedEventArgs e)
  1867. {
  1868. LoadWindow<CalendarPanel>((Fluent.Button)sender);
  1869. }
  1870. private void EmployeePlannerButton_Click(object sender, RoutedEventArgs e)
  1871. {
  1872. LoadWindow<EmployeeResourcePlannerPanel>((Fluent.Button)sender);
  1873. }
  1874. private void EquipmentPlannerButton_Click(object sender, RoutedEventArgs e)
  1875. {
  1876. LoadWindow<EquipmentPlannerPanel>((Fluent.Button)sender);
  1877. }
  1878. private void InvoiceList_Click(object sender, RoutedEventArgs e)
  1879. {
  1880. LoadWindow<InvoicePanel>((Fluent.Button)sender);
  1881. }
  1882. private void ReceiptList_Click(object sender, RoutedEventArgs e)
  1883. {
  1884. LoadWindow<CustomerReceipts>((Fluent.Button)sender);
  1885. }
  1886. private void PaymentsList_Click(object sender, RoutedEventArgs e)
  1887. {
  1888. LoadWindow<SupplierPayments>((Fluent.Button)sender);
  1889. }
  1890. private void BillsList_Click(object sender, RoutedEventArgs e)
  1891. {
  1892. LoadWindow<SupplierBillPanel>((Fluent.Button)sender);
  1893. }
  1894. private void PurchasesList_Click(object sender, RoutedEventArgs e)
  1895. {
  1896. LoadWindow<SupplierPurchaseOrderPanel>((Fluent.Button)sender);
  1897. }
  1898. private void DeliveriesButton_Click(object sender, RoutedEventArgs e)
  1899. {
  1900. LoadWindow<DeliveryPanel>((Fluent.Button)sender);
  1901. }
  1902. private void FactoryAllocationButton_Click(object sender, RoutedEventArgs e)
  1903. {
  1904. LoadWindow<ManufacturingAllocationPanel>((Fluent.Button)sender);
  1905. }
  1906. private void Messages_Checked(object sender, RoutedEventArgs e)
  1907. {
  1908. LoadWindow<NotificationPanel>((Fluent.Button)sender);
  1909. }
  1910. private void DatabaseActivityButton_Click(object sender, RoutedEventArgs e)
  1911. {
  1912. LoadWindow<DatabaseActivityDashboard>((Fluent.Button)sender);
  1913. }
  1914. private void FactoryProductivityButton_Click(object sender, RoutedEventArgs e)
  1915. {
  1916. LoadWindow<FactoryProductivityDashboard>((Fluent.Button)sender);
  1917. }
  1918. private void TemplateAnalysisButton_Click(object sender, RoutedEventArgs e)
  1919. {
  1920. LoadWindow<ManufacturingTemplateAnalysis>((Fluent.Button)sender);
  1921. }
  1922. private void FactoryAnalysisButton_Click(object sender, RoutedEventArgs e)
  1923. {
  1924. LoadWindow<FactoryFloorAnalysis>((Fluent.Button)sender);
  1925. }
  1926. private void UserActivityButton_Click(object sender, RoutedEventArgs e)
  1927. {
  1928. LoadWindow<UserActivity>((Fluent.Button)sender);
  1929. }
  1930. private void QuickStatus_Click(object sender, RoutedEventArgs e)
  1931. {
  1932. LoadWindow<WidgetDashboard>((Fluent.Button)sender);
  1933. }
  1934. private void ConsignmentButton_Click(object sender, RoutedEventArgs e)
  1935. {
  1936. LoadWindow<ConsignmentsPanel>((Fluent.Button)sender);
  1937. }
  1938. //private void NotificationsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
  1939. //{
  1940. // if (NotificationsList.SelectedIndex < 0)
  1941. // return;
  1942. // var editors = NotificationsList.FindVisualChildren<InABox.DynamicGrid.ExtendedRichTextEditor>().ToArray();
  1943. // var selected = editors[NotificationsList.SelectedIndex];
  1944. // selected.Text = (String)selected.Tag; //NotificationsList.SelectedIndex.ToString();
  1945. //}
  1946. //private void ViewNotification_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
  1947. //{
  1948. // Notification notification = (sender as Label).Tag as Notification;
  1949. // NotificationDetails details = new NotificationDetails(notification);
  1950. // details.ShowDialog();
  1951. // ReloadNotifications();
  1952. //}
  1953. private void DailyReport_Checked(object sender, RoutedEventArgs e)
  1954. {
  1955. LoadWindow<DailyReport>((Fluent.Button)sender);
  1956. }
  1957. private void Library_Click(object sender, RoutedEventArgs e)
  1958. {
  1959. Process.Start(
  1960. new ProcessStartInfo
  1961. {
  1962. FileName = App.DatabaseSettings.LibraryLocation,
  1963. UseShellExecute = true,
  1964. Verb = "open"
  1965. }
  1966. );
  1967. }
  1968. private void SendNotificationClick(object sender, RoutedEventArgs e)
  1969. {
  1970. var form = new NotificationForm { Description = "" };
  1971. if (form.ShowDialog() == true)
  1972. ReloadNotifications();
  1973. }
  1974. private void CompanyInformation_Click(object sender, RoutedEventArgs e)
  1975. {
  1976. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  1977. if (info == null)
  1978. info = new CompanyInformation();
  1979. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  1980. }
  1981. #region Digital Forms
  1982. private void DigitalFormsFormsLibraryButton_Click(object sender, RoutedEventArgs e)
  1983. {
  1984. LoadWindow<DigitalFormsLibrary>((Fluent.Button)sender);
  1985. }
  1986. private void DigitalFormsCompletedFormsButton_Click(object sender, RoutedEventArgs e)
  1987. {
  1988. LoadWindow<CompletedFormsPanel>((Fluent.Button)sender);
  1989. }
  1990. #endregion
  1991. private void Dashboards_Checked(object sender, RoutedEventArgs e)
  1992. {
  1993. LoadWindow<UtilityDashboard>((Fluent.Button)sender);
  1994. }
  1995. private void Setup_Click(object sender, RoutedEventArgs e)
  1996. {
  1997. var tab = _ribbon.SelectedTabItem;
  1998. if (tab is null)
  1999. return;
  2000. var menu = new ContextMenu();
  2001. PanelHost.InitialiseSetupMenu(menu);
  2002. menu.IsOpen = true;
  2003. }
  2004. private void StartForm<TEntityForm, TEntity, TEntityLink>(DigitalForm form)
  2005. where TEntityForm : EntityForm<TEntity, TEntityLink, TEntityForm>, new()
  2006. where TEntity : Entity, new()
  2007. where TEntityLink : EntityLink<TEntity>, new()
  2008. {
  2009. var entityForm = new TEntityForm();
  2010. entityForm.Form.CopyFrom(form);
  2011. entityForm.Description = form.Description;
  2012. entityForm.FormStarted = DateTime.Now;
  2013. var entity = DFUtils.NewEntity<TEntityForm, TEntity, TEntityLink>(form);
  2014. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel, entity))
  2015. {
  2016. dataModel.Update(null);
  2017. }
  2018. }
  2019. private void Forms_Click(object sender, RoutedEventArgs e)
  2020. {
  2021. var select = new MultiSelectDialog<DigitalForm>(
  2022. Filter<DigitalForm>.And(
  2023. LookupFactory.DefineChildFilter<KanbanForm, DigitalForm>(Array.Empty<KanbanForm>()),
  2024. new Filter<DigitalForm>(x => x.ID).InQuery(
  2025. new Filter<EmployeeDigitalForm>(x => x.Employee.ID).IsEqualTo(App.EmployeeID),
  2026. x => x.Form.ID)),
  2027. LookupFactory.DefineChildColumns<KanbanForm, DigitalForm>()
  2028. .Add(x => x.Description),
  2029. false);
  2030. if (select.ShowDialog() == true)
  2031. {
  2032. var digitalForm = select.Data().Rows.FirstOrDefault()?.ToObject<DigitalForm>();
  2033. if (digitalForm is not null)
  2034. {
  2035. StartForm<KanbanForm, Kanban, KanbanLink>(digitalForm);
  2036. }
  2037. };
  2038. }
  2039. #endregion
  2040. private bool OutstandingDailyReports(bool refresh)
  2041. {
  2042. if (!Security.IsAllowed<CanViewDailyReports>() || Security.IsAllowed<BypassOutstandingDailyReports>())
  2043. return false;
  2044. if (refresh)
  2045. RefreshTimeSheets();
  2046. if (_timesheets == null)
  2047. return false;
  2048. return _timesheets.Rows.Any(r => r.Get<TimeSheet, DateTime>(c => c.Date).Date < DateTime.Today);
  2049. }
  2050. private void ShutDownTransport()
  2051. {
  2052. if (_transport != null)
  2053. {
  2054. _transport.OnClose -= TransportConnectionLost;
  2055. if (_transport.IsConnected())
  2056. _transport.Disconnect();
  2057. _transport = null;
  2058. }
  2059. }
  2060. private void Window_Unloaded(object sender, RoutedEventArgs e)
  2061. {
  2062. ShutDownTransport();
  2063. }
  2064. private void RibbonWindow_Closed(object sender, EventArgs e)
  2065. {
  2066. ShutDownTransport();
  2067. DisconnectRecorderNotes();
  2068. Application.Current.Shutdown();
  2069. }
  2070. //private bool _closingFromSystemMenu = false;
  2071. private void Window_Closing(object sender, CancelEventArgs e)
  2072. {
  2073. /*if (!_closingFromSystemMenu && !CoreUtils.GetVersion().Equals("???"))
  2074. {
  2075. WindowState = WindowState.Minimized;
  2076. e.Cancel = true;
  2077. return;
  2078. }*/
  2079. PanelHost.UnloadPanel(e);
  2080. if (!e.Cancel)
  2081. {
  2082. ISubPanelHost.Global.ShutdownSubPanels(e);
  2083. }
  2084. if (e.Cancel)
  2085. {
  2086. return;
  2087. }
  2088. App.IsClosing = true;
  2089. FinalizeAutoTimesheet();
  2090. if (!CoreUtils.GetVersion().Equals("???"))
  2091. scheduler.Stop();
  2092. CurrentTab = null;
  2093. UpdateRibbonColors();
  2094. if (!CoreUtils.GetVersion().Equals("???"))
  2095. if (station.ID != Guid.Empty)
  2096. ExecuteLogout();
  2097. ShutDownTransport();
  2098. }
  2099. #region Notifications + Heartbeat
  2100. private void ReceiveNotification(Notification notification)
  2101. {
  2102. if (Security.CanView<Notification>())
  2103. {
  2104. Notifications.AddNotification(notification);
  2105. }
  2106. foreach(var panel in Panels.OfType<NotificationPanel>())
  2107. {
  2108. panel.AddNotification(notification);
  2109. }
  2110. }
  2111. private void Notifications_Tick(object? sender, EventArgs e)
  2112. {
  2113. if (ClientFactory.UserGuid != Guid.Empty)
  2114. {
  2115. try
  2116. {
  2117. ReloadNotifications();
  2118. }
  2119. catch (Exception err)
  2120. {
  2121. Logger.Send(LogType.Error, ClientFactory.UserID,
  2122. string.Format("Exception in Notifications_Tick:ReloadNotifications() {0}\n{1}", err.Message, err.StackTrace));
  2123. }
  2124. Heartbeat();
  2125. try
  2126. {
  2127. CheckIsLoggedOn();
  2128. }
  2129. catch (Exception err2)
  2130. {
  2131. Logger.Send(LogType.Error, ClientFactory.UserID,
  2132. string.Format("Exception in Notifications_Tick:CheckIsLoggedOn() {0}\n{1}", err2.Message, err2.StackTrace));
  2133. }
  2134. }
  2135. //else
  2136. //{
  2137. // Logger.Send(LogType.Information, ClientFactory.UserID, "Notifications_Tick: ClientFactory.UserGuid is empty");
  2138. //}
  2139. }
  2140. private void CheckIsLoggedOn()
  2141. {
  2142. if (CoreUtils.GetVersion().Equals("???"))
  2143. return;
  2144. var bLogout = false;
  2145. if (!Security.IsAllowed<CanBypassTimeBench>())
  2146. if (!IsClockedOn())
  2147. {
  2148. Logger.Send(LogType.Information, ClientFactory.UserID, "User is no longer clocked in!");
  2149. bLogout = true;
  2150. Dispatcher.Invoke(() => { Logout(); });
  2151. }
  2152. if (!bLogout)
  2153. new Client<Login>().Query(
  2154. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  2155. Columns.None<Login>().Add(x => x.StationID),
  2156. null,
  2157. CoreRange.All,
  2158. (o, e) =>
  2159. {
  2160. if (e is RemoteException remote)
  2161. {
  2162. if (remote.Status == StatusCode.Unauthenticated)
  2163. {
  2164. Logger.Send(LogType.Information, ClientFactory.UserID, "User has been logged out");
  2165. Dispatcher.Invoke(() =>
  2166. {
  2167. Logout("You have been logged out due to inactivity");
  2168. });
  2169. }
  2170. else
  2171. {
  2172. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error in CheckIsLoggedOn(): {CoreUtils.FormatException(remote)}");
  2173. }
  2174. }
  2175. else if (e is not null)
  2176. {
  2177. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error in CheckIsLoggedOn(): {CoreUtils.FormatException(e)}");
  2178. }
  2179. else if (o is not null)
  2180. {
  2181. var row = o.Rows.FirstOrDefault();
  2182. if (row == null)
  2183. {
  2184. station.ID = Guid.Empty;
  2185. new Client<Login>().Save(station, "", (o1, e1) => { });
  2186. }
  2187. else if (!row.Get<Login, string>(c => c.StationID).Equals(station.StationID))
  2188. {
  2189. Logger.Send(LogType.Information, ClientFactory.UserID, "User logged in somewhere else!");
  2190. bLogout = true;
  2191. Dispatcher.Invoke(() => { Logout(); });
  2192. }
  2193. }
  2194. }
  2195. );
  2196. }
  2197. private void Heartbeat()
  2198. {
  2199. //Task.Run(() =>
  2200. //{
  2201. try
  2202. {
  2203. bool IsClockedOn = this.IsClockedOn();
  2204. if (IsClockedOn)
  2205. {
  2206. if ((_kanbantrackingassignment != null) && (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay))
  2207. {
  2208. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2209. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2210. }
  2211. if (Security.IsAllowed<MonitorApplicationWindows>())
  2212. {
  2213. if (ActivityHistory == null)
  2214. ActivityHistory = new LocalConfiguration<DailyActivityHistory>().Load();
  2215. var appname = OpenWindowGetter.GetActiveWindowProcess();
  2216. var title = OpenWindowGetter.GetActiveWindowTitle();
  2217. ActivityHistory.Activities[DateTime.Now] = (!string.IsNullOrWhiteSpace(appname) ? appname.Trim() + " - " : "") + title;
  2218. new LocalConfiguration<DailyActivityHistory>().Save(ActivityHistory);
  2219. }
  2220. }
  2221. PanelHost.Heartbeat();
  2222. foreach(var window in SecondaryWindows.Values)
  2223. {
  2224. window.Heartbeat();
  2225. }
  2226. }
  2227. catch (Exception err)
  2228. {
  2229. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Exception in Heartbeat: {0}\n{1}", err.Message, err.StackTrace));
  2230. }
  2231. //});
  2232. }
  2233. private void Notifications_Changed(object sender)
  2234. {
  2235. if (Notifications.IsActive)
  2236. {
  2237. Notifications.Visibility = Visibility.Visible;
  2238. DockingGrid.ColumnDefinitions[1].Width = new GridLength(4, GridUnitType.Pixel);
  2239. DockingGrid.ColumnDefinitions[2].Width = Equals(0.0, DockingGrid.ColumnDefinitions[2].Width.Value)
  2240. ? new GridLength(300, GridUnitType.Pixel)
  2241. : DockingGrid.ColumnDefinitions[2].Width;
  2242. }
  2243. else
  2244. {
  2245. Notifications.Visibility = Visibility.Collapsed;
  2246. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  2247. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  2248. }
  2249. }
  2250. private void ReloadNotifications()
  2251. {
  2252. if (Security.CanView<Notification>())
  2253. Notifications.Refresh();
  2254. if (!NotificationsWatchDog.IsEnabled)
  2255. {
  2256. //Logger.Send(LogType.Information, ClientFactory.UserID, "Enabling Heartbeat");
  2257. NotificationsWatchDog.IsEnabled = true;
  2258. }
  2259. }
  2260. #endregion
  2261. private void RibbonWindow_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  2262. {
  2263. PanelHost.IncrementTrackingModuleClick();
  2264. }
  2265. private void RibbonWindow_PreviewKeyUp(object sender, KeyEventArgs e)
  2266. {
  2267. PanelHost.IncrementTrackingModuleKey();
  2268. }
  2269. #region Recording
  2270. //private IntPtr myHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  2271. //{
  2272. // switch (msg)
  2273. // {
  2274. // case 0x100:
  2275. // if (_subject != null)
  2276. // {
  2277. // _recorder.Stop();
  2278. // pausestarted = DateTime.Now;
  2279. // _subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2280. // }
  2281. // break;
  2282. // default:
  2283. // messages.TryGetValue(msg, out int value);
  2284. // messages[msg] = value + 1;
  2285. // break;
  2286. // }
  2287. // return IntPtr.Zero;
  2288. //}
  2289. private void RecordScreenButton_Click(object sender, RoutedEventArgs e)
  2290. {
  2291. ToggleRecording();
  2292. }
  2293. private bool ToggleRecording()
  2294. {
  2295. if (!Security.IsAllowed<CanRecordScreen>())
  2296. return true;
  2297. if (_recorder is null)
  2298. {
  2299. var windowInteropHelper = new WindowInteropHelper(this);
  2300. var screen = Screen.FromHandle(windowInteropHelper.Handle);
  2301. _screenleft = screen.WorkingArea.Left;
  2302. _screentop = screen.WorkingArea.Top;
  2303. _screenwidth = screen.WorkingArea.Width;
  2304. _screenheight = screen.WorkingArea.Height;
  2305. //VIDEO_WIDTH = _screenwidth;
  2306. //VIDEO_HEIGHT = _screenheight;
  2307. //SetupJPEGEncoder();
  2308. messages.Clear();
  2309. _bitmaps.Clear();
  2310. ConnectToRecordNotes();
  2311. StartAudio();
  2312. _recorder = new DispatcherTimer();
  2313. _recorder.Tick += (timer, args) => { TakeScreenShot(); };
  2314. _recorder.Interval = TimeSpan.FromMilliseconds(1000 / FRAMES_PER_SECOND);
  2315. _recorder.Start();
  2316. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsBitmapImage();
  2317. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2318. RecordingNotesButton.Visibility = Visibility.Visible;
  2319. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2320. AudioRecordingButton.Visibility = Visibility.Visible;
  2321. }
  2322. else
  2323. {
  2324. using (new WaitCursor())
  2325. {
  2326. StopRecording();
  2327. _recorder.Stop();
  2328. _recorder = null;
  2329. DisconnectRecorderNotes();
  2330. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  2331. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2332. RecordingNotesButton.Visibility = Visibility.Hidden;
  2333. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2334. AudioRecordingButton.Visibility = Visibility.Hidden;
  2335. var filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos),
  2336. string.Format("PRS Screen Recording {0:yyyy-MM-dd hh-mm-ss-ff}.avi", DateTime.Now));
  2337. ProcessScreenShots(filename);
  2338. }
  2339. }
  2340. return true;
  2341. }
  2342. private void StopRecording()
  2343. {
  2344. try
  2345. {
  2346. _audio?.StopRecording();
  2347. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2348. }
  2349. catch (Exception e)
  2350. {
  2351. Logger.Send(LogType.Error, "", string.Format("Unable to stop Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2352. }
  2353. }
  2354. private void StartAudio()
  2355. {
  2356. _audioMuted = true;
  2357. _audioStream = new MemoryStream();
  2358. _audio = new WaveIn
  2359. {
  2360. DeviceNumber = 0,
  2361. WaveFormat = new WaveFormat(44100, 16, 2)
  2362. };
  2363. _audio.DataAvailable += (o, e) =>
  2364. {
  2365. var buf = _audioMuted ? new byte[e.BytesRecorded] : e.Buffer;
  2366. _audioStream.Write(buf, 0, e.BytesRecorded);
  2367. };
  2368. try
  2369. {
  2370. _audio.StartRecording();
  2371. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2372. }
  2373. catch (Exception e)
  2374. {
  2375. Logger.Send(LogType.Error, "", string.Format("Unable to start Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2376. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2377. }
  2378. }
  2379. private bool ToggleRecordingAudio()
  2380. {
  2381. if (!Security.IsAllowed<CanRecordScreen>())
  2382. return true;
  2383. if (_recorder != null)
  2384. {
  2385. _audioMuted = !_audioMuted;
  2386. AudioRecordingStatus.Source = _audioMuted
  2387. ? PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage()
  2388. : PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2389. }
  2390. return true;
  2391. }
  2392. private void DisconnectRecorderNotes()
  2393. {
  2394. if (_client != null)
  2395. {
  2396. _client.WriteAsync("QUIT");
  2397. _client.StopAsync();
  2398. _client = null;
  2399. }
  2400. }
  2401. private void ConnectToRecordNotes()
  2402. {
  2403. var filename = Debugger.IsAttached
  2404. ? "c:\\development\\comal\\prsrecordingnotes\\bin\\debug\\prsrecordingnotes.exe"
  2405. : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "recordingnotes", "prsrecordingnotes.exe");
  2406. Logger.Send(LogType.Information, "", "Recording Notes: " + filename);
  2407. _recordingnotes = Process.Start(filename);
  2408. //PipeSecurity sec = new System.IO.Pipes.PipeSecurity();
  2409. //sec.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));
  2410. _client = new PipeServer<string>("PRSScreenRecorder", formatter:new BinaryFormatter()); //, sec);
  2411. _client.ClientConnected += (o, args) => args.Connection.WriteAsync("Connected to PRSScreenRecorder");
  2412. _client.MessageReceived += (o, args) =>
  2413. {
  2414. if (string.Equals(args.Message, "RESUME"))
  2415. Dispatcher.Invoke(() =>
  2416. {
  2417. _audio?.StartRecording();
  2418. totalpauses += DateTime.Now - pausestarted;
  2419. _recorder?.Start();
  2420. Activate();
  2421. Focus();
  2422. });
  2423. };
  2424. _client.StartAsync();
  2425. }
  2426. private bool ShowRecordingNotes()
  2427. {
  2428. if (_recorder != null)
  2429. {
  2430. _audio?.StopRecording();
  2431. _recorder.Stop();
  2432. pausestarted = DateTime.Now;
  2433. _client?.WriteAsync("EDIT");
  2434. //_subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2435. }
  2436. return true;
  2437. }
  2438. private void TakeScreenShot()
  2439. {
  2440. using (var bmp = new ScreenCapture().CaptureScreen(_screenleft, _screentop, _screenwidth, _screenheight))
  2441. {
  2442. var cursor = PointToScreen(Mouse.GetPosition(this));
  2443. using (var g = Graphics.FromImage(bmp))
  2444. {
  2445. var brush = new SolidBrush(System.Drawing.Color.FromArgb(128, 255, 255, 0));
  2446. g.FillEllipse(brush, new RectangleF((float)cursor.X - 25F, (float)cursor.Y - 25F, 50F, 50F));
  2447. var pen = new Pen(System.Drawing.Color.Black, 0.75F);
  2448. g.DrawLine(pen, (float)cursor.X - 10F, (float)cursor.Y, (float)cursor.X + 10F, (float)cursor.Y);
  2449. g.DrawLine(pen, (float)cursor.X, (float)cursor.Y - 10F, (float)cursor.X, (float)cursor.Y + 10F);
  2450. }
  2451. var key = DateTime.Now - totalpauses;
  2452. using (var reduced = ReduceBitmap(bmp, VIDEO_WIDTH, VIDEO_HEIGHT))
  2453. {
  2454. var ms = new MemoryStream();
  2455. reduced.Save(ms, ImageFormat.Png);
  2456. ms.Position = 0;
  2457. _bitmaps[key] = ms;
  2458. }
  2459. }
  2460. }
  2461. public Bitmap ReduceBitmap(Bitmap original, int reducedWidth, int reducedHeight)
  2462. {
  2463. var reduced = new Bitmap(reducedWidth, reducedHeight);
  2464. using (var dc = Graphics.FromImage(reduced))
  2465. {
  2466. // Figure out the ratio
  2467. var ratioX = (double)reducedWidth / original.Width;
  2468. var ratioY = (double)reducedHeight / original.Height;
  2469. // use whichever multiplier is smaller
  2470. var ratio = ratioX < ratioY ? ratioX : ratioY;
  2471. // now we can get the new height and width
  2472. var newHeight = Convert.ToInt32(original.Height * ratio);
  2473. var newWidth = Convert.ToInt32(original.Width * ratio);
  2474. // Now calculate the X,Y position of the upper-left corner
  2475. // (one of these will always be zero)
  2476. var posX = Convert.ToInt32((reducedWidth - original.Width * ratio) / 2);
  2477. var posY = Convert.ToInt32((reducedHeight - original.Height * ratio) / 2);
  2478. dc.InterpolationMode = InterpolationMode.HighQualityBicubic;
  2479. dc.Clear(System.Drawing.Color.Black); // white padding
  2480. //dc.DrawImage(original, posX, posY, newWidth, newHeight);
  2481. dc.DrawImage(original, new Rectangle(posX, posY, newWidth, newHeight), new Rectangle(0, 0, original.Width, original.Height),
  2482. GraphicsUnit.Pixel);
  2483. }
  2484. return reduced;
  2485. }
  2486. public static byte[] BitmapToByteArray(Bitmap bitmap, int width, int height)
  2487. {
  2488. // and buffer of appropriate size for storing its bits
  2489. var buffer = new byte[width * height * 4];
  2490. var pixelFormat = PixelFormat.Format32bppRgb;
  2491. // Now copy bits from bitmap to buffer
  2492. var bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);
  2493. //Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2494. Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2495. bitmap.UnlockBits(bits);
  2496. return buffer;
  2497. }
  2498. private void ProcessScreenShots(string filename)
  2499. {
  2500. if (!_bitmaps.Any() || _audioStream is null)
  2501. return;
  2502. Progress.Show("Saving Video");
  2503. var framRate = 10;
  2504. using (var writer = new AviWriter(filename))
  2505. {
  2506. writer.FramesPerSecond = framRate;
  2507. writer.EmitIndex1 = true;
  2508. _audioStream.Position = 0;
  2509. var audio = writer.AddAudioStream(2);
  2510. //audio.WriteBlock(_audioStream.GetBuffer(), 0, (int)_audioStream.Length);
  2511. //File.WriteAllBytes(Path.ChangeExtension(filename, "wav"), _audioStream.GetBuffer());
  2512. var audioByteRate = audio.BitsPerSample / 8 * audio.ChannelCount * audio.SamplesPerSecond;
  2513. var audioBlockSize = (int)(audioByteRate / writer.FramesPerSecond);
  2514. var audioBuffer = new byte[audioBlockSize];
  2515. _audioStream.Position = 0;
  2516. var encoder = new MJpegWpfVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT, 50);
  2517. var stream = writer.AddEncodingVideoStream(encoder, true, VIDEO_WIDTH, VIDEO_HEIGHT);
  2518. //var encoder = new SharpAvi.Codecs.UncompressedVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT);
  2519. //var stream = writer.AddEncodingVideoStream(encoder,true,VIDEO_WIDTH, VIDEO_HEIGHT);
  2520. //stream.Codec = CodecIds.Uncompressed;
  2521. //stream.BitsPerPixel = BitsPerPixel.Bpp16;
  2522. IEnumerable<DateTime> keys = _bitmaps.Keys.OrderBy(x => x);
  2523. var start = keys.First();
  2524. var end = keys.Last();
  2525. for (var cur = start; cur <= end; cur = cur + TimeSpan.FromMilliseconds(100))
  2526. {
  2527. Progress.SetMessage(string.Format("Processing ({0:F2} complete)",
  2528. (cur - start).TotalSeconds * 100.0F / (end - start).TotalSeconds));
  2529. var key = keys.LastOrDefault(x => x <= cur);
  2530. if (_bitmaps.ContainsKey(key))
  2531. {
  2532. var frame = (Image.FromStream(_bitmaps[key]) as Bitmap)!;
  2533. //frame.RotateFlip(RotateFlipType.RotateNoneFlipY);
  2534. var buf = BitmapToByteArray(frame, stream.Width, stream.Height);
  2535. stream.WriteFrame(true, buf, 0, buf.Length);
  2536. if (_audioStream.Position < _audioStream.Length)
  2537. {
  2538. var bytes = _audioStream.Read(audioBuffer, 0, audioBlockSize);
  2539. audio.WriteBlock(audioBuffer, 0, bytes);
  2540. }
  2541. }
  2542. }
  2543. writer.Close();
  2544. //foreach (var key in _bitmaps.Keys)
  2545. // File.Delete(_bitmaps[key]);
  2546. }
  2547. Progress.SetMessage("Transcoding");
  2548. //var inputFile = new MediaFile { Filename = filename };
  2549. //var outputFile = new MediaFile { Filename = Path.ChangeExtension(filename, "mp4") };
  2550. //using (var engine = new Engine())
  2551. //{
  2552. // //engine.ConvertProgressEvent += ConvertProgressEvent;
  2553. // engine.Convert(inputFile, outputFile);
  2554. //}
  2555. Progress.Close();
  2556. var dirName = Path.GetDirectoryName(filename);
  2557. if (dirName is not null)
  2558. {
  2559. var startInfo = new ProcessStartInfo(dirName);
  2560. startInfo.Verb = "open";
  2561. startInfo.UseShellExecute = true;
  2562. Process.Start(startInfo);
  2563. //MessageBox.Show("Recording Saved");
  2564. }
  2565. }
  2566. private void VideoRecordingButton_Click(object sender, RoutedEventArgs e)
  2567. {
  2568. ToggleRecording();
  2569. }
  2570. private void AudioRecordingButton_Click(object sender, RoutedEventArgs e)
  2571. {
  2572. ToggleRecordingAudio();
  2573. }
  2574. private void RecordingNotesButton_Click(object sender, RoutedEventArgs e)
  2575. {
  2576. ShowRecordingNotes();
  2577. }
  2578. #endregion
  2579. public static void ActivateWindow(Window window)
  2580. {
  2581. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2582. var threadId1 = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
  2583. var threadId2 = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
  2584. if (threadId1 != threadId2)
  2585. {
  2586. AttachThreadInput(threadId1, threadId2, true);
  2587. SetForegroundWindow(hwnd);
  2588. AttachThreadInput(threadId1, threadId2, false);
  2589. }
  2590. else
  2591. {
  2592. SetForegroundWindow(hwnd);
  2593. }
  2594. }
  2595. private static IntPtr GetForegroundWindow()
  2596. {
  2597. var active = GetActiveWindow();
  2598. var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => new WindowInteropHelper(x).Handle == active);
  2599. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2600. return hwnd;
  2601. }
  2602. [DllImport("user32.dll", SetLastError = true)]
  2603. private static extern IntPtr SetForegroundWindow(IntPtr hWnd);
  2604. [DllImport("user32.dll")]
  2605. private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
  2606. [DllImport("user32.dll")]
  2607. private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
  2608. [DllImport("user32.dll")]
  2609. private static extern IntPtr GetActiveWindow();
  2610. #region Check For Updates
  2611. private string GetUpdateLocation()
  2612. {
  2613. if (App.DatabaseSettings.DatabaseType == DatabaseType.Networked)
  2614. {
  2615. if(ClientFactory.ClientType == typeof(RestClient<>))
  2616. {
  2617. string url = "";
  2618. //var domain = App.DatabaseSettings.URL.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).Last();
  2619. //var port = App.DatabaseSettings.Port;
  2620. var domain = ClientFactory.Parameters?.FirstOrDefault()?.ToString() ?? "";
  2621. domain = domain.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? "";
  2622. if (!String.IsNullOrWhiteSpace(domain))
  2623. {
  2624. try
  2625. {
  2626. var client = new HttpClient { BaseAddress = new Uri($"https://{domain}") };
  2627. client.GetAsync("operations").Wait();
  2628. url = $"https://{domain}";
  2629. }
  2630. catch (Exception)
  2631. {
  2632. url = $"http://{domain}";
  2633. }
  2634. }
  2635. return url;
  2636. }
  2637. else
  2638. {
  2639. return "";
  2640. }
  2641. }
  2642. else
  2643. return Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update");
  2644. }
  2645. private string GetLatestVersion(string location)
  2646. {
  2647. return Client.Version();
  2648. }
  2649. private string GetReleaseNotes(string location)
  2650. {
  2651. return Client.ReleaseNotes();
  2652. }
  2653. private byte[]? GetInstaller(string location)
  2654. {
  2655. return Client.Installer();
  2656. }
  2657. private void CheckForUpdates()
  2658. {
  2659. Update.CheckForUpdates(
  2660. GetUpdateLocation, GetLatestVersion, GetReleaseNotes, GetInstaller, null, App.AutoUpdateSettings.Elevated, "PRSDesktopSetup.exe");
  2661. }
  2662. #endregion
  2663. #region Modules + Reports
  2664. public void ClearActions()
  2665. {
  2666. foreach (var module in CurrentModules)
  2667. {
  2668. if (module.Parent is Fluent.RibbonGroupBox bar)
  2669. bar.Items.Remove(module);
  2670. }
  2671. CurrentModules.Clear();
  2672. }
  2673. public void ClearReports()
  2674. {
  2675. if (CurrentTab is not null)
  2676. {
  2677. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  2678. if (ReportsBar is not null)
  2679. {
  2680. ReportsBar.Visibility = Security.IsAllowed<CanPrintReports>() ? Visibility.Visible : Visibility.Collapsed;
  2681. ReportsBar.Items.Clear();
  2682. }
  2683. }
  2684. }
  2685. public void CreateReport(PanelAction action)
  2686. {
  2687. if (CurrentTab is null)
  2688. return;
  2689. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  2690. if (ReportsBar is not null)
  2691. {
  2692. var button = new Fluent.Button
  2693. {
  2694. Header = action.Caption,
  2695. LargeIcon = action.Image.AsBitmapImage(),
  2696. MinWidth = 60
  2697. };
  2698. if (action.Menu is not null)
  2699. {
  2700. button.ContextMenu = action.Menu;
  2701. }
  2702. button.Click += (o, e) =>
  2703. {
  2704. action.Execute();
  2705. };
  2706. ReportsBar.Items.Add(button);
  2707. }
  2708. }
  2709. private NullConverter<Visibility>? _vis = null;
  2710. public void CreatePanelAction(PanelAction action)
  2711. {
  2712. if (CurrentTab is null)
  2713. return;
  2714. if (_vis == null)
  2715. {
  2716. _vis = new();
  2717. _vis.Converting += (o, e) =>
  2718. {
  2719. };
  2720. }
  2721. var Actions = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  2722. if (Actions is not null)
  2723. {
  2724. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  2725. {
  2726. var sep = new RibbonSeparator();
  2727. CurrentModules.Add(sep);
  2728. Actions.Items.Add(sep);
  2729. }
  2730. if (action.OnPopulate != null)
  2731. {
  2732. Fluent.DropDownButton button = null;
  2733. if (action.OnExecute != null)
  2734. {
  2735. button = new Fluent.SplitButton();
  2736. ((Fluent.SplitButton)button).Click += (o, e) => action.Execute();
  2737. }
  2738. else
  2739. button = new Fluent.DropDownButton();
  2740. button.MinWidth = 60;
  2741. button.DataContext = action;
  2742. button.DropDownOpened += (sender, args) => { button.ItemsSource = CreateMenuItems(action); };
  2743. button.Bind<PanelAction, String>(Fluent.DropDownButton.HeaderProperty, x => x.Caption, null);
  2744. button.Bind<PanelAction, Bitmap?>(Fluent.DropDownButton.LargeIconProperty, x => x.Image,
  2745. new BitmapToBitmapImageConverter());
  2746. button.Bind<PanelAction, ContextMenu?>(ContextMenuProperty, x => x.Menu);
  2747. button.Bind<PanelAction, bool>(IsEnabledProperty, x => x.IsEnabled);
  2748. button.Bind<PanelAction, Visibility>(Fluent.DropDownButton.VisibilityProperty, x => x.Visibility, _vis);
  2749. Actions.Items.Add(button);
  2750. CurrentModules.Add(button);
  2751. }
  2752. else
  2753. {
  2754. var button = new Fluent.Button()
  2755. {
  2756. MinWidth = 60,
  2757. DataContext = action
  2758. };
  2759. button.Bind<PanelAction, String>(Fluent.Button.HeaderProperty, x => x.Caption, null);
  2760. button.Bind<PanelAction, Bitmap?>(Fluent.Button.LargeIconProperty, x => x.Image,
  2761. new BitmapToBitmapImageConverter());
  2762. button.Bind<PanelAction, ContextMenu?>(Fluent.Button.ContextMenuProperty, x => x.Menu);
  2763. button.Bind<PanelAction, bool>(Fluent.Button.IsEnabledProperty, x => x.IsEnabled);
  2764. button.Bind<PanelAction, Visibility>(Fluent.Button.VisibilityProperty, x => x.Visibility, _vis);
  2765. button.Click += (o, e) => action.Execute();
  2766. Actions.Items.Add(button);
  2767. CurrentModules.Add(button);
  2768. }
  2769. }
  2770. }
  2771. private static ObservableCollection<MenuItem> CreateMenuItems(PanelAction action)
  2772. {
  2773. var items = new ObservableCollection<MenuItem>();
  2774. var entries = action.Populate();
  2775. if (entries != null)
  2776. {
  2777. foreach (var entry in entries)
  2778. {
  2779. var item = new Fluent.MenuItem()
  2780. {
  2781. Header = entry.Caption,
  2782. DataContext = entry.Data,
  2783. Icon = entry.Image?.AsBitmapImage()
  2784. };
  2785. item.Click += (o, eventArgs) => entry.Execute();
  2786. items.Add(item);
  2787. }
  2788. }
  2789. return items;
  2790. }
  2791. #endregion
  2792. #region Tracking Kanban
  2793. private void SelectTask_Click(object sender, RoutedEventArgs e)
  2794. {
  2795. ContextMenu menu = new ContextMenu();
  2796. MenuItem others = new MenuItem() { Header = "Other Tasks" };
  2797. using (new WaitCursor())
  2798. {
  2799. var kanbans = new Client<KanbanSubscriber>().Query(
  2800. new Filter<KanbanSubscriber>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
  2801. .And(x => x.Kanban.Completed).IsEqualTo(DateTime.MinValue)
  2802. .And(x => x.Kanban.Closed).IsEqualTo(DateTime.MinValue),
  2803. Columns.None<KanbanSubscriber>().Add(x => x.Kanban.ID)
  2804. .Add(x => x.Kanban.Number)
  2805. .Add(x => x.Kanban.Title)
  2806. .Add(x => x.Assignee),
  2807. new SortOrder<KanbanSubscriber>(x => x.Kanban.Number, SortDirection.Ascending)
  2808. );
  2809. foreach (var row in kanbans.Rows)
  2810. {
  2811. CreateTaskMenu(row.Get<KanbanSubscriber, bool>(c => c.Assignee) ? menu.Items : others.Items,
  2812. String.Format("{0} {1}",
  2813. row.Get<KanbanSubscriber, int>(c => c.Kanban.Number),
  2814. row.Get<KanbanSubscriber, String>(c => c.Kanban.Title)),
  2815. row.Get<KanbanSubscriber, Guid>(c => c.Kanban.ID)
  2816. );
  2817. }
  2818. menu.Items.Add(new Separator());
  2819. menu.Items.Add(others);
  2820. menu.Items.Add(new Separator());
  2821. CreateTaskMenu(menu.Items, "(No Task Selected)", Guid.Empty);
  2822. }
  2823. menu.IsOpen = true;
  2824. }
  2825. private Assignment? _kanbantrackingassignment = null;
  2826. private void SetTrackingKanban(Guid kanbanID, string header)
  2827. {
  2828. SelectedTaskName.Content = header;
  2829. var createNewAssignment = false;
  2830. if (_kanbantrackingassignment is not null)
  2831. {
  2832. if (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay)
  2833. {
  2834. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2835. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2836. }
  2837. // Update Existing Kanban
  2838. if (kanbanID == Guid.Empty)
  2839. _kanbantrackingassignment = null;
  2840. else if (_kanbantrackingassignment.Task.ID != kanbanID)
  2841. {
  2842. createNewAssignment = true;
  2843. }
  2844. }
  2845. else if (kanbanID != Guid.Empty)
  2846. {
  2847. createNewAssignment = true;
  2848. }
  2849. if (createNewAssignment)
  2850. {
  2851. _kanbantrackingassignment = new Assignment();
  2852. _kanbantrackingassignment.Task.ID = kanbanID;
  2853. _kanbantrackingassignment.EmployeeLink.ID = App.EmployeeID;
  2854. _kanbantrackingassignment.Title = header;
  2855. _kanbantrackingassignment.Date = DateTime.Today;
  2856. _kanbantrackingassignment.Actual.Start = DateTime.Now.TimeOfDay;
  2857. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay.Add(new TimeSpan(0, 2, 0));
  2858. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2859. }
  2860. }
  2861. private void ClearTrackingKanban()
  2862. => SetTrackingKanban(Guid.Empty, "(No Task Selected)");
  2863. private void CreateTaskMenu(ItemCollection items, String title, Guid id)
  2864. {
  2865. var item = new MenuItem()
  2866. {
  2867. Header = title,
  2868. Tag = id
  2869. };
  2870. item.Click += (o, args) =>
  2871. {
  2872. if (o is not MenuItem menu) return;
  2873. SetTrackingKanban((Guid)item.Tag, (menu.Header as string) ?? "");
  2874. };
  2875. items.Add(item);
  2876. }
  2877. #endregion
  2878. private void DockPanelBorder_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
  2879. {
  2880. if (sender is not Border border || !border.IsVisible)
  2881. return;
  2882. var dock = border.Child is IDockPanel panel ? panel : border.Child?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  2883. if (dock is null)
  2884. return;
  2885. dock.Refresh();
  2886. }
  2887. private void DockPanel_OnIsActiveChanged(object? sender, EventArgs e)
  2888. {
  2889. if (sender is not LayoutAnchorable layout)
  2890. return;
  2891. var content = layout.Content as DependencyObject;
  2892. var dock = content is IDockPanel panel ? panel : content?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  2893. if (dock is null)
  2894. return;
  2895. if (layout.IsActive && layout.IsVisible)
  2896. dock.Refresh();
  2897. }
  2898. private void _ribbon_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  2899. {
  2900. e.Handled = true;
  2901. }
  2902. #region Backstage Functions
  2903. private enum DatabaseConfigurationResult
  2904. {
  2905. RestartRequired,
  2906. RestartNotRequired,
  2907. Cancel
  2908. }
  2909. private DatabaseConfigurationResult ShowDatabaseConfiguration()
  2910. {
  2911. DatabaseConfigurationResult result;
  2912. var config = new DataBaseConfiguration();
  2913. if (config.ShowDialog() == true)
  2914. {
  2915. var newsettings = new LocalConfiguration<DatabaseSettings>(App.Profile).Load();
  2916. if (newsettings.RestartRequired(App.DatabaseSettings))
  2917. {
  2918. result = DatabaseConfigurationResult.RestartRequired;
  2919. }
  2920. else
  2921. {
  2922. result = DatabaseConfigurationResult.RestartNotRequired;
  2923. }
  2924. if ((newsettings.DatabaseType == DatabaseType.Standalone) && (newsettings.ColorScheme != App.DatabaseSettings.ColorScheme))
  2925. {
  2926. App.DatabaseSettings.ColorScheme = newsettings.ColorScheme;
  2927. ApplyColorScheme();
  2928. }
  2929. }
  2930. else
  2931. {
  2932. result = DatabaseConfigurationResult.Cancel;
  2933. }
  2934. return result;
  2935. }
  2936. private void DatabaseSettings_OnClick(object sender, RoutedEventArgs e)
  2937. {
  2938. switch (ShowDatabaseConfiguration())
  2939. {
  2940. case DatabaseConfigurationResult.RestartRequired:
  2941. MessageBox.Show("Please restart the application to apply these changes!");
  2942. break;
  2943. }
  2944. }
  2945. private void CompanyInformation_OnClick(object sender, RoutedEventArgs e)
  2946. {
  2947. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  2948. if (info == null)
  2949. info = new CompanyInformation();
  2950. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  2951. }
  2952. private void SecurityDefaultsButton_OnClick(object sender, RoutedEventArgs e)
  2953. {
  2954. var window = new GlobalTokenWindow();
  2955. window.ShowDialog();
  2956. Security.Reset();
  2957. }
  2958. private void SystemLogsButton_OnClick(object sender, RoutedEventArgs e)
  2959. {
  2960. var logfile = CoreUtils.GetLogFile();
  2961. if (File.Exists(logfile))
  2962. {
  2963. var startInfo = new ProcessStartInfo("notepad.exe", logfile);
  2964. startInfo.Verb = "open";
  2965. startInfo.UseShellExecute = true;
  2966. Process.Start(startInfo);
  2967. }
  2968. else
  2969. {
  2970. MessageBox.Show(logfile + " does not exist!");
  2971. }
  2972. }
  2973. private void DocumentTypeList_OnClick(object sender, RoutedEventArgs e)
  2974. {
  2975. var list = new MasterList(typeof(DocumentType));
  2976. list.ShowDialog();
  2977. }
  2978. private void EditDetailsButton_OnClick(object sender, RoutedEventArgs e)
  2979. {
  2980. var employee = new Client<Employee>().Query(
  2981. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid))
  2982. .Rows.FirstOrDefault()?.ToObject<Employee>();
  2983. var item = new MyDetailsConfiguration(employee);
  2984. item.User = ClientFactory.UserGuid;
  2985. var buttons = new DynamicEditorButtons();
  2986. buttons.Add("Change Password", null, item, (sender, item) =>
  2987. {
  2988. var details = (item as MyDetailsConfiguration)!;
  2989. var changePassword = new ChangePassword(details.User);
  2990. if (changePassword.ShowDialog() == true && changePassword.Password != null)
  2991. {
  2992. var newUser = new User();
  2993. newUser.ID = details.User;
  2994. ChangePassword.ChangeUserPassword(newUser, changePassword.Password);
  2995. new Client<User>().Save(newUser, "Changed Password");
  2996. MessageBox.Show("Password changed!");
  2997. }
  2998. });
  2999. var editor = new DynamicEditorForm(typeof(MyDetailsConfiguration), buttons: buttons);
  3000. if (employee == null)
  3001. {
  3002. editor.OnFormCustomiseEditor += (sender, items, column, editor) =>
  3003. {
  3004. editor.Editable = Editable.Disabled;
  3005. };
  3006. }
  3007. editor.Items = new BaseObject[] { item };
  3008. if (editor.ShowDialog() == true)
  3009. {
  3010. if (employee != null)
  3011. {
  3012. item.SaveTo(employee);
  3013. new Client<Employee>().Save(employee, "Edited by user");
  3014. }
  3015. }
  3016. }
  3017. private void LogoutButton_OnClick(object sender, RoutedEventArgs e)
  3018. {
  3019. Logout();
  3020. }
  3021. private void LoginButton_OnClick(object sender, RoutedEventArgs e)
  3022. {
  3023. if (DoLogin() == ValidationStatus.VALID)
  3024. AfterLogin(null);
  3025. }
  3026. private void ExitButton_OnClick(object sender, RoutedEventArgs e)
  3027. {
  3028. //_closingFromSystemMenu = true;
  3029. Close();
  3030. }
  3031. #endregion
  3032. private void Issues_Click(object sender, RoutedEventArgs e)
  3033. {
  3034. try
  3035. {
  3036. IssuesWindow.Execute();
  3037. }
  3038. catch(Exception err)
  3039. {
  3040. MessageWindow.ShowError("Could not load issues.", err);
  3041. }
  3042. }
  3043. }