MainWindow.xaml.cs 125 KB

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