MainWindow.xaml.cs 130 KB

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