MainWindow.xaml.cs 125 KB

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