MainWindow.xaml.cs 125 KB

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