MainWindow.xaml.cs 126 KB

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