MainWindow.xaml.cs 125 KB

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