MainWindow.xaml.cs 130 KB

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