MainWindow.xaml.cs 129 KB

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