MainWindow.xaml.cs 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.Drawing.Drawing2D;
  7. using System.Drawing.Imaging;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net.Http;
  11. using System.Reflection;
  12. using System.Runtime.InteropServices;
  13. using System.Threading.Tasks;
  14. using System.Windows;
  15. using System.Windows.Controls;
  16. using System.Windows.Forms;
  17. using System.Windows.Input;
  18. using System.Windows.Interop;
  19. using System.Windows.Media;
  20. using System.Windows.Threading;
  21. using AvalonDock.Layout;
  22. using Comal.Classes;
  23. using Comal.Stores;
  24. using Comal.TaskScheduler.Shared;
  25. using H.Pipes;
  26. using InABox.Clients;
  27. using InABox.Configuration;
  28. using InABox.Core;
  29. using InABox.Database;
  30. using InABox.Database.SQLite;
  31. using InABox.DynamicGrid;
  32. using InABox.Mail;
  33. using InABox.Core.Reports;
  34. using InABox.IPC;
  35. using InABox.Rpc;
  36. using InABox.Scripting;
  37. using InABox.WPF;
  38. using 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;
  48. using Syncfusion.Windows.Tools.Controls;
  49. using Activity = Comal.Classes.Activity;
  50. using Application = System.Windows.Application;
  51. using ButtonBase = System.Windows.Controls.Primitives.ButtonBase;
  52. using Color = System.Windows.Media.Color;
  53. using ColorConverter = System.Windows.Media.ColorConverter;
  54. using Control = System.Windows.Controls.Control;
  55. using Image = System.Drawing.Image;
  56. using KeyEventArgs = System.Windows.Input.KeyEventArgs;
  57. using MessageBox = System.Windows.MessageBox;
  58. using Pen = System.Drawing.Pen;
  59. using PixelFormat = System.Drawing.Imaging.PixelFormat;
  60. using Role = Comal.Classes.Role;
  61. using SortDirection = InABox.Core.SortDirection;
  62. using PRSDesktop.Components.Spreadsheet;
  63. using InABox.Wpf.Reports;
  64. using Comal.Classes.SecurityDescriptors;
  65. namespace PRSDesktop
  66. {
  67. /// <summary>
  68. /// Interaction logic for Main.xaml
  69. /// </summary>
  70. public partial class MainWindow : IPanelHost
  71. {
  72. //private const int WM_LBUTTONDOWN = 0x201;
  73. private static PipeServer<string>? _client;
  74. private IRpcClientTransport? _transport;
  75. private WaveIn? _audio;
  76. private bool _audioMuted;
  77. private MemoryStream? _audioStream;
  78. private readonly Dictionary<DateTime, Stream> _bitmaps = new();
  79. private Console? _console;
  80. private Dictionary<DateTime, Tuple<Rectangle, string>> _notes = new();
  81. //Dictionary<Type, IBasePanel> Panels = new Dictionary<Type, IBasePanel>();
  82. private DispatcherTimer? _recorder;
  83. private Process? _recordingnotes;
  84. private int _screenheight = 720;
  85. private int _screenleft;
  86. private int _screentop;
  87. private int _screenwidth = 1280;
  88. private readonly Dictionary<Guid, SecondaryWindow> _secondarywindows = new();
  89. private CoreTable? _timesheets;
  90. private DailyActivityHistory? ActivityHistory;
  91. private readonly List<Control> CurrentModules = new();
  92. private IBasePanel? CurrentPanel;
  93. private int CurrentPanel_Clicks;
  94. private int CurrentPanel_Keys;
  95. private string CurrentPanel_Label = "";
  96. private DateTime CurrentPanel_Ticks = DateTime.MinValue;
  97. private Fluent.RibbonTabItem? CurrentTab;
  98. private Fluent.Button? CurrentButton;
  99. private readonly int FRAMES_PER_SECOND = 10;
  100. private DatabaseType DatabaseType;
  101. private readonly Dictionary<int, int> messages = new();
  102. private readonly DispatcherTimer NotificationsWatchDog;
  103. private DateTime pausestarted = DateTime.MinValue;
  104. private readonly Scheduler scheduler = new() { Interval = new TimeSpan(0, 5, 0) };
  105. // We use a Guid for the StationID rather than an IP or Mac address
  106. // because we want true single-instance restriction. Using either of
  107. // the above allows for two instances on the once machine, and thus
  108. // double-counting in the Heartbeat() function
  109. private Login station = new() { StationID = Guid.NewGuid().ToString() };
  110. private TimeSpan totalpauses = new(0);
  111. private readonly int VIDEO_HEIGHT = 1080;
  112. private readonly int VIDEO_WIDTH = 1920;
  113. public MainWindow()
  114. {
  115. NotificationsWatchDog = new DispatcherTimer { IsEnabled = false };
  116. NotificationsWatchDog.Tick += Notifications_Tick;
  117. NotificationsWatchDog.Interval = new TimeSpan(0, 2, 0);
  118. ClientFactory.PushHandlers.AddHandler<Notification>(ReceiveNotification);
  119. ClientFactory.RegisterMailer(EmailType.IMAP, typeof(IMAPMailer));
  120. ClientFactory.RegisterMailer(EmailType.Exchange, typeof(ExchangeMailer));
  121. ClientFactory.OnLog += (type, userid, message, parameters) => Logger.Send(LogType.Information, ClientFactory.UserID, message, parameters);
  122. ClientFactory.OnRequestError += ClientFactory_OnRequestError;
  123. HotKeyManager.Initialize();
  124. HotKeyManager.RegisterHotKey(Key.F1, ShowHelp);
  125. HotKeyManager.RegisterHotKey(Key.F5, ToggleRecording);
  126. HotKeyManager.RegisterHotKey(Key.F6, ShowRecordingNotes);
  127. HotKeyManager.RegisterHotKey(Key.F4, ToggleRecordingAudio);
  128. var settings = App.DatabaseSettings;
  129. bool dbConnected;
  130. DatabaseType = settings.DatabaseType;
  131. switch (DatabaseType)
  132. {
  133. case DatabaseType.Standalone:
  134. ClientFactory.SetClientType(typeof(LocalClient<>), Platform.Wpf, CoreUtils.GetVersion());
  135. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  136. DbFactory.Logo = App.DatabaseSettings.Logo;
  137. dbConnected = true;
  138. break;
  139. case DatabaseType.Networked:
  140. if (App.DatabaseSettings.Protocol == SerializerProtocol.RPC)
  141. {
  142. //new RPC stuff (temporary disabled - for enabling when RPC is ready)
  143. _transport = new RpcClientSocketTransport(App.DatabaseSettings.URLs);
  144. _transport.OnClose += TransportConnectionLost;
  145. dbConnected = _transport.Connect();
  146. ClientFactory.SetClientType(typeof(RpcClient<>), Platform.Wpf, CoreUtils.GetVersion(),
  147. _transport);
  148. }
  149. else
  150. {
  151. var url = RestClient<User>.Ping(App.DatabaseSettings.URLs, out DatabaseInfo info);
  152. ClientFactory.SetClientType(typeof(RestClient<>), Platform.Wpf, CoreUtils.GetVersion(), url, true);
  153. dbConnected = true;
  154. }
  155. break;
  156. case DatabaseType.Local:
  157. //new RPC stuff (temporary disabled - for enabling when RPC is ready)
  158. var pipename = DatabaseServerProperties.GetPipeName(App.DatabaseSettings.LocalServerName, true);
  159. _transport = new RpcClientPipeTransport(pipename);
  160. _transport.OnClose += TransportConnectionLost;
  161. dbConnected = _transport.Connect();
  162. ClientFactory.SetClientType(typeof(RpcClient<>), Platform.Wpf, CoreUtils.GetVersion(), _transport );
  163. //ClientFactory.SetClientType(typeof(IPCClient<>), Platform.Wpf, CoreUtils.GetVersion(),
  164. // DatabaseServerProperties.GetPipeName(App.DatabaseSettings.LocalServerName, false));
  165. //dbConnected = true;
  166. break;
  167. default:
  168. throw new Exception($"Invalid database type {DatabaseType}");
  169. }
  170. InitializeComponent();
  171. if (!dbConnected)
  172. {
  173. switch (DoConnectionFailed())
  174. {
  175. case ConnectionFailedResult.Quit:
  176. Close();
  177. return;
  178. case ConnectionFailedResult.Restart:
  179. App.ShouldRestart = true;
  180. Close();
  181. return;
  182. case ConnectionFailedResult.Ok:
  183. // Do nothing
  184. break;
  185. }
  186. }
  187. ThemeManager.BaseColor = Colors.CornflowerBlue;
  188. Progress.DisplayImage = PRSDesktop.Resources.splash_small.AsBitmapImage();
  189. try
  190. {
  191. var dbInfo = new Client<User>().Info();
  192. ThemeManager.BaseColor = (Color)ColorConverter.ConvertFromString(dbInfo.ColorScheme);
  193. if (dbInfo.Logo?.Any() == true)
  194. using (var ms = new MemoryStream(dbInfo.Logo))
  195. {
  196. Progress.DisplayImage = new Bitmap(ms).AsBitmapImage();
  197. }
  198. }
  199. catch
  200. {
  201. }
  202. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  203. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  204. SecondaryWindowStatus.Source = PRSDesktop.Resources.target.AsGrayScale().AsBitmapImage();
  205. ConsoleStatus.Source = PRSDesktop.Resources.view.AsGrayScale().AsBitmapImage();
  206. SelectTask.Source = PRSDesktop.Resources.uparrow.Invert().AsBitmapImage();
  207. Title = $"{(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  208. CheckForUpdates();
  209. Exception? startupException = null;
  210. ValidationStatus? loginStatus = null;
  211. Progress.ShowModal("Loading PRS", progress =>
  212. {
  213. DynamicGridUtils.PreviewReport = (t, m) => { ReportUtils.PreviewReport(t, m, false, Security.IsAllowed<CanDesignReports>()); };
  214. DynamicGridUtils.PrintMenu = (e, s, m, p) => { ReportUtils.PrintMenu(e, s, m, Security.IsAllowed<CanDesignReports>(), p); };
  215. ImportFactory.Register(typeof(ExcelImporter<>), "Excel File", "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm");
  216. FormUtils.Register();
  217. Logger.Send(LogType.Information, "", "Registering Classes");
  218. progress.Report("Registering Classes");
  219. var tasks = new List<Task>
  220. {
  221. Task.Run(() => CoreUtils.RegisterClasses(typeof(KanbanGrid).Assembly)),
  222. Task.Run(() => CoreUtils.RegisterClasses()),
  223. Task.Run(() => ComalUtils.RegisterClasses()),
  224. Task.Run(() => PRSSharedUtils.RegisterClasses()),
  225. Task.Run(() => ReportUtils.RegisterClasses()),
  226. Task.Run(() => ConfigurationUtils.RegisterClasses()),
  227. Task.Run(() => DynamicGridUtils.RegisterClasses()),
  228. Task.Run(() =>
  229. {
  230. ScriptDocument.DefaultAssemblies.AddRange(
  231. Assembly.Load("RoslynPad.Roslyn.Windows"),
  232. Assembly.Load("RoslynPad.Editor.Windows"),
  233. typeof(Control).Assembly,
  234. typeof(MessageBox).Assembly,
  235. typeof(SolidColorBrush).Assembly
  236. );
  237. ScriptDocument.Initialize();
  238. }),
  239. Task.Run(() => DatabaseUpdateScripts.RegisterScripts())
  240. };
  241. Task.WaitAll(tasks.ToArray());
  242. progress.Report("Configuring Application");
  243. RegisterModules(progress);
  244. if (DatabaseType == DatabaseType.Standalone)
  245. {
  246. progress.Report("Starting local database...");
  247. try
  248. {
  249. StartLocalDatabase(progress);
  250. }
  251. catch (Exception err)
  252. {
  253. startupException = new Exception(
  254. string.Format(
  255. "Unable to open database ({0})\n\n{1}\n\n{2}",
  256. App.DatabaseSettings.FileName,
  257. err.Message,
  258. err.StackTrace
  259. )
  260. );
  261. }
  262. }
  263. });
  264. if (startupException != null)
  265. MessageBox.Show(startupException.Message);
  266. if (DoLogin(App.DatabaseSettings.Autologin) == ValidationStatus.VALID)
  267. {
  268. AfterLogin();
  269. }
  270. ProfileName.Content = App.Profile;
  271. URL.Content = GetDatabaseConnectionDescription();
  272. Progress.ShowModal("Starting Up", progress =>
  273. {
  274. if (loginStatus == ValidationStatus.VALID && DatabaseType == DatabaseType.Standalone)
  275. {
  276. progress.Report("Starting Scheduler");
  277. scheduler.Start();
  278. }
  279. });
  280. }
  281. #region Connection Management
  282. private string GetDatabaseConnectionDescription()
  283. {
  284. return DatabaseType switch
  285. {
  286. #if RPC
  287. DatabaseType.Networked => (ClientFactory.Parameters?.FirstOrDefault() as RpcClientSocketTransport)?.Host,
  288. #else
  289. DatabaseType.Networked => ClientFactory.Parameters?.FirstOrDefault() as string,
  290. #endif
  291. DatabaseType.Standalone => App.DatabaseSettings?.FileName,
  292. DatabaseType.Local => App.DatabaseSettings?.LocalServerName,
  293. _ => ""
  294. } ?? "";
  295. }
  296. /// <summary>
  297. /// Reconnect to the server.
  298. /// </summary>
  299. /// <returns><see langword="true"/> if connection was successful.</returns>
  300. private bool Reconnect()
  301. {
  302. if (_transport != null)
  303. {
  304. return _transport.Connect();
  305. }
  306. Logger.Send(LogType.Error, ClientFactory.UserID, "Trying to reconnect without a transport set.");
  307. return true; // Returning true so we don't get stuck in infinite loops in exceptional circumstances.
  308. }
  309. private enum ConnectionFailedResult
  310. {
  311. Quit,
  312. Restart,
  313. Ok
  314. }
  315. /// <summary>
  316. /// To be called when initial connection to the server has failed; asks the user if they want to retry,
  317. /// change the database settings, or simply quit PRS.
  318. /// </summary>
  319. /// <returns>The action to take next.</returns>
  320. /// <exception cref="Exception"></exception>
  321. private ConnectionFailedResult DoConnectionFailed()
  322. {
  323. bool connected = false;
  324. while (!connected)
  325. {
  326. var connectionFailedWindow = new ConnectionFailed();
  327. connectionFailedWindow.ShowDialog();
  328. var reconnect = false;
  329. switch (connectionFailedWindow.Result)
  330. {
  331. case ConnectionFailedWindowResult.OpenDatabaseConfiguration:
  332. var result = ShowDatabaseConfiguration();
  333. switch (result)
  334. {
  335. case DatabaseConfigurationResult.RestartRequired:
  336. var shouldRestart = MessageBox.Show(
  337. "A restart is required to apply these changes. Do you wish to restart now?",
  338. "Restart?",
  339. MessageBoxButton.YesNo);
  340. if (shouldRestart == MessageBoxResult.Yes)
  341. {
  342. return ConnectionFailedResult.Restart;
  343. }
  344. else
  345. {
  346. reconnect = true;
  347. }
  348. break;
  349. case DatabaseConfigurationResult.RestartNotRequired:
  350. reconnect = true;
  351. break;
  352. case DatabaseConfigurationResult.Cancel:
  353. reconnect = true;
  354. break;
  355. default:
  356. throw new Exception($"Invalid enum result {result}");
  357. }
  358. break;
  359. case ConnectionFailedWindowResult.RetryConnection:
  360. reconnect = true;
  361. break;
  362. case ConnectionFailedWindowResult.Quit:
  363. return ConnectionFailedResult.Quit;
  364. default:
  365. throw new Exception($"Invalid enum result {connectionFailedWindow.Result}");
  366. }
  367. if (!reconnect)
  368. {
  369. return ConnectionFailedResult.Quit;
  370. }
  371. connected = Reconnect();
  372. }
  373. return ConnectionFailedResult.Ok;
  374. }
  375. private void TransportConnectionLost(IRpcTransport transport, RpcTransportCloseArgs e)
  376. {
  377. if ((transport is IRpcClientTransport client))
  378. {
  379. Dispatcher.Invoke(() =>
  380. {
  381. var success = Progress.ShowModal("Reconnecting", "Exit PRS", (progress, ct) =>
  382. {
  383. try
  384. {
  385. DateTime lost = DateTime.Now;
  386. while (!client.IsConnected() && !ct.IsCancellationRequested)
  387. {
  388. progress.Report($"Connection lost - ({(DateTime.Now - lost):hh\\:mm})");
  389. try
  390. {
  391. Logger.Send(LogType.Error, ClientFactory.UserID, "Reconnecting - ({0:hh\\:mm})", DateTime.Now - lost);
  392. client.Connect(ct);
  393. if (client.IsConnected())
  394. break;
  395. }
  396. catch (System.Exception e1)
  397. {
  398. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnect Failed: {e1.Message}");
  399. }
  400. }
  401. if (client.IsConnected())
  402. {
  403. ClientFactory.Validate(ClientFactory.SessionID);
  404. }
  405. }
  406. catch (Exception e)
  407. {
  408. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnect Failed: {e.Message}");
  409. }
  410. });
  411. if (!success)
  412. {
  413. Close();
  414. }
  415. });
  416. }
  417. }
  418. #endregion
  419. private bool _loggingOut = false;
  420. private void ClientFactory_OnRequestError(RequestException e)
  421. {
  422. if (e.Status == StatusCode.Unauthenticated)
  423. {
  424. switch (e.Method)
  425. {
  426. case RequestMethod.Query:
  427. case RequestMethod.Save:
  428. case RequestMethod.Delete:
  429. case RequestMethod.MultiQuery:
  430. case RequestMethod.MultiSave:
  431. case RequestMethod.MultiDelete:
  432. if (!_loggingOut)
  433. {
  434. Dispatcher.InvokeAsync(() =>
  435. {
  436. _loggingOut = true;
  437. try
  438. {
  439. Logout(null, true);
  440. }
  441. finally
  442. {
  443. _loggingOut = false;
  444. }
  445. });
  446. }
  447. break;
  448. default:
  449. break;
  450. }
  451. }
  452. }
  453. private void ApplyColorScheme()
  454. {
  455. Color baseColor;
  456. try
  457. {
  458. baseColor = (Color)ColorConverter.ConvertFromString(App.DatabaseSettings.ColorScheme);
  459. }
  460. catch
  461. {
  462. baseColor = Colors.CornflowerBlue;
  463. }
  464. ThemeManager.BaseColor = baseColor;
  465. BaseDynamicGrid.SelectionBackground = ThemeManager.SelectionBackgroundBrush;
  466. BaseDynamicGrid.SelectionForeground = ThemeManager.SelectionForegroundBrush;
  467. BaseDynamicGrid.FilterBackground = ThemeManager.FilterBackgroundBrush;
  468. //_ribbon.Background = new SolidColorBrush(Colors.White);
  469. //_ribbon.BackStageColor = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  470. ////_ribbon.BackStage.Background = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  471. ////_ribbon.BackStage.Foreground = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Foreground);
  472. UpdateRibbonColors();
  473. CurrentPanel?.Refresh();
  474. }
  475. #region Configuration
  476. /*
  477. protected override void OnSourceInitialized(EventArgs e)
  478. {
  479. base.OnSourceInitialized(e);
  480. var source = PresentationSource.FromVisual(this) as HwndSource;
  481. source?.AddHook(WndProc);
  482. }
  483. private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  484. {
  485. var message = (App.Message)msg;
  486. switch (message)
  487. {
  488. case App.Message.Maximise:
  489. WindowState = WindowState.Maximized;
  490. break;
  491. }
  492. return IntPtr.Zero;
  493. }*/
  494. private interface ISetupActionItem
  495. {
  496. }
  497. private class SetupActionItem : ISetupActionItem
  498. {
  499. public string Name { get; set; }
  500. public Action Action { get; set; }
  501. public Bitmap? Image { get; set; }
  502. public Type? SecurityToken { get; set; }
  503. public Func<bool>? CanView { get; set; }
  504. public SetupActionItem(string name, Action action, Bitmap? image)
  505. {
  506. Name = name;
  507. Action = action;
  508. Image = image;
  509. }
  510. public bool IsVisible() => (SecurityToken == null || Security.IsAllowed(SecurityToken)) && (CanView == null || CanView());
  511. public SetupActionItem SetSecurityToken<T>() where T : ISecurityDescriptor, new()
  512. {
  513. SecurityToken = typeof(T);
  514. return this;
  515. }
  516. public SetupActionItem SetCanView<T>() where T : Entity
  517. {
  518. return SetSecurityToken<AutoSecurityDescriptor<T, CanView<T>>>();
  519. }
  520. }
  521. private class SetupSeparator : ISetupActionItem { }
  522. private Dictionary<Fluent.RibbonTabItem, List<ISetupActionItem>> SetupActions = new();
  523. private List<ISetupActionItem> GetSetupActionList(Fluent.RibbonTabItem tab)
  524. {
  525. if (!SetupActions.TryGetValue(tab, out var list))
  526. {
  527. list = new();
  528. SetupActions[tab] = list;
  529. }
  530. return list;
  531. }
  532. private SetupActionItem AddSetupAction(List<ISetupActionItem> list, string header, Action action, Bitmap? image)
  533. {
  534. var item = new SetupActionItem(header, action, image);
  535. list.Add(item);
  536. return item;
  537. }
  538. private SetupActionItem AddSetupAction(Fluent.RibbonTabItem tab, string header, Action action, Bitmap? image)
  539. => AddSetupAction(GetSetupActionList(tab), header, action, image);
  540. private SetupActionItem? AddSetupAction(Fluent.RibbonTabItem tab, string header, Action action, Bitmap? image, bool canView)
  541. {
  542. if (!canView)
  543. return null;
  544. return AddSetupAction(tab, header, action, image);
  545. }
  546. private SetupSeparator AddSetupSeparator(List<ISetupActionItem> list)
  547. {
  548. var separator = new SetupSeparator();
  549. list.Add(separator);
  550. return separator;
  551. }
  552. private SetupSeparator AddSetupSeparator(Fluent.RibbonTabItem tab)
  553. => AddSetupSeparator(GetSetupActionList(tab));
  554. private void AddSetupModulesAndReports(Fluent.RibbonTabItem tab)
  555. {
  556. AddSetupSeparator(tab);
  557. AddSetupAction(tab, "Custom Modules", ManageModules, PRSDesktop.Resources.script).SetSecurityToken<CanCustomiseModules>();
  558. AddSetupAction(tab, "Reports", ManageReports, PRSDesktop.Resources.printer).SetSecurityToken<CanDesignReports>();
  559. AddSetupAction(tab, "Email Templates", ManageEmailTemplates, PRSDesktop.Resources.email).SetSecurityToken<CanDesignReports>();
  560. }
  561. private void ConfigureMainScreen()
  562. {
  563. SetupScreen();
  564. var bMaps = Security.CanView<Equipment>()
  565. || Security.CanView<Job>()
  566. || Security.CanView<TimeSheet>()
  567. || Security.CanView<GPSTracker>();
  568. Progress.ShowModal(
  569. new ProgressSection("Configuring Main Screen", SetupMainScreen),
  570. new ProgressSection("Configuring Quotes Screen", () => SetupQuotesTab(bMaps)),
  571. new ProgressSection("Configuring Projects", () => SetupProjectsTab(bMaps)),
  572. new ProgressSection("Configuring Manufacturing", () => SetupManufacturingTab(bMaps)),
  573. new ProgressSection("Configuring Logistics", () => SetupLogisticsTab(bMaps)),
  574. new ProgressSection("Configuring Products", () => SetupProductsTab(bMaps)),
  575. new ProgressSection("Configuring Human Resources", () => SetupHumanResourcesTab(bMaps)),
  576. new ProgressSection("Configuring Accounts", () => SetupAccountsTab(bMaps)),
  577. new ProgressSection("Configuring Equipment", () => SetupEquipmentTab(bMaps)),
  578. new ProgressSection("Configuring Dashboards", () => SetupDashboardsTab(bMaps)),
  579. new ProgressSection("Configuring System Modules", SetupSystemModules)
  580. );
  581. }
  582. private void SetupScreen()
  583. {
  584. var button = _ribbon.FindVisualChildren<Fluent.DropDownButton>().FirstOrDefault();
  585. if (button != null)
  586. button.Visibility = Visibility.Collapsed;
  587. if (ClientFactory.UserGuid == Guid.Empty)
  588. _ribbonRow.Height = new GridLength(30, GridUnitType.Pixel);
  589. else
  590. _ribbonRow.Height = new GridLength(1, GridUnitType.Auto);
  591. SetupActions.Clear();
  592. }
  593. private void SetupMainScreen()
  594. {
  595. ReportUtils.ExportDefinitions.Clear();
  596. ReportUtils.ExportDefinitions.AddRange(AddTemplateDefinitions());
  597. //DockManager.SidePanelSize = OutstandingDailyReports(false) ? 0.00F : 30.00F;
  598. // Notifications Area
  599. SetVisibility(SendNotification, Security.CanView<Notification>());
  600. SetVisibility(Notifications, Security.CanView<Notification>());
  601. SetVisibility(TaskTracking, Security.IsAllowed<CanTrackTasksInDailyReport>());
  602. UserID.Content = ClientFactory.UserID;
  603. if (ClientFactory.PasswordExpiration != DateTime.MinValue)
  604. {
  605. var timeUntilExpiration = ClientFactory.PasswordExpiration - DateTime.Now;
  606. if (timeUntilExpiration.Days < 14)
  607. {
  608. PasswordExpiryNotice.Content = $"Password will expire in {timeUntilExpiration.Days} days!";
  609. PasswordExpiryNotice.Visibility = Visibility.Visible;
  610. }
  611. else
  612. {
  613. PasswordExpiryNotice.Visibility = Visibility.Collapsed;
  614. }
  615. }
  616. }
  617. private void SetupSystemModules()
  618. {
  619. SetVisibility(CompanyInformation, Security.CanView<CompanyInformation>());
  620. SetVisibleIfAny(BackstageSeparator0, CompanyInformation);
  621. SetVisibility(SecurityDefaultsButton,
  622. ClientFactory.IsSupported<GlobalSecurityToken>() && Security.IsAllowed<CanCustomiseSecurityDefaults>());
  623. SetVisibleIfAny(BackstageSeparator1, SecurityDefaultsButton);
  624. BackstageSeparator1a.Visibility = Visibility.Visible;
  625. SystemLogsButton.Visibility = Visibility.Visible;
  626. SetVisibility(DocumentTypeList, ClientFactory.IsSupported<DocumentType>() && Security.IsAllowed<CanViewDocumentTypes>());
  627. SetVisibility(DocumentList, ClientFactory.IsSupported<Document>() && Security.IsAllowed<CanViewDocumentList>());
  628. SetVisibility(QAFormSetupButton,
  629. ClientFactory.IsSupported<DigitalForm>() && Security.IsAllowed<CanAdministerDigitalFormsLibrary>());
  630. SetVisibleIfAny(BackstageSeparator2, DocumentTypeList, DocumentList, QAFormSetupButton);
  631. SetVisibility(VideoRecordingButton, Security.IsAllowed<CanRecordScreen>());
  632. LogoutButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  633. LoginButton.Visibility = ClientFactory.UserGuid != Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  634. EditDetailsButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  635. SetupDock<CanViewContactsDock>(ContactDock, Contacts);
  636. SetupDock<CanViewJobDock>(JobDock, Jobs);
  637. SetupDock<CanViewConsignmentDock>(ConsignmentDock, Consignments);
  638. SetupDock<CanViewDeliveryDock>(DeliveryDock, Deliveries);
  639. SetupDock<CanViewProductDock>(ProductLookupDock, ProductLookup);
  640. SetupDock<CanViewDigitalFormsDock>(DigitalFormsDock, DigitalForms);
  641. _ribbon.InvalidateArrange();
  642. }
  643. private void SetupDashboardsTab(bool bMaps)
  644. {
  645. if (!Security.IsAllowed<ViewDesktopDashboardsTab>())
  646. return;
  647. SetVisibility(DashboardsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  648. SetVisibility(DashboardMessagesButton, Security.CanView<Notification>());
  649. SetVisibility(DashboardsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  650. SetVisibility(DashboardsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  651. SetVisibility(DashboardsMapButton, bMaps);
  652. SetVisibility(DashboardsDailyReportButton,
  653. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  654. SetVisibility(FactoryProductivityButton,
  655. ClientFactory.IsSupported<ManufacturingHistory>()
  656. && Security.IsAllowed<CanViewFactoryKPIs>()
  657. && Security.IsAllowed<ViewDesktopFactoryKPIsDashboard>());
  658. SetVisibility(TemplateAnalysisButton,
  659. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>()
  660. && Security.IsAllowed<CanViewTemplateAnalysis>()
  661. && Security.IsAllowed<ViewDesktopTemplateAnalysisDashboard>());
  662. SetVisibility(FactoryAnalysisButton,
  663. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>()
  664. && Security.IsAllowed<CanViewFactoryAnalysis>()
  665. && Security.IsAllowed<ViewDesktopFactoryAnalysisDashboard>());
  666. SetVisibility(DatabaseActivityButton,
  667. ClientFactory.IsSupported<UserTracking>()
  668. && Security.IsAllowed<CanViewDatabaseActivity>()
  669. && Security.IsAllowed<ViewDesktopDatabaseActivityDashboard>());
  670. SetVisibility(UserActivityButton, ClientFactory.IsSupported<ModuleTracking>()
  671. && Security.IsAllowed<CanViewUserActivity>()
  672. && Security.IsAllowed<ViewDesktopUserActivityDashboard>());
  673. SetVisibility(DigitalFormsButton, Security.IsAllowed<CanViewDigitalFormsDashbaord>() && Security.IsAllowed<ViewDesktopDigitalFormsDashboard>());
  674. SetVisibility(QuickStatusButton, Security.IsAllowed<CanViewQuickStatus>() && Security.IsAllowed<ViewDesktopQuickStatusDashboard>());
  675. SetVisibleIfEither(DashboardsTaskSeparator,
  676. new FrameworkElement[]
  677. {
  678. DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton, DashboardsAttendanceButton,
  679. DashboardsMapButton,
  680. DashboardsDailyReportButton
  681. },
  682. new FrameworkElement[]
  683. {
  684. FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton,
  685. DigitalFormsButton, QuickStatusButton
  686. });
  687. SetVisibleIfAny(DashboardsActions, DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton,
  688. DashboardsAttendanceButton, DashboardsDailyReportButton, FactoryProductivityButton, TemplateAnalysisButton,
  689. FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton, DigitalFormsButton, QuickStatusButton);
  690. //DashboardsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  691. //DashboardsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  692. AddSetupModulesAndReports(DashboardsTab);
  693. SetVisibleIfAny(DashboardsTab, FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton,
  694. DatabaseActivityButton,
  695. UserActivityButton, DigitalFormsButton, QuickStatusButton);
  696. }
  697. private void SetupEquipmentTab(bool bMaps)
  698. {
  699. if (!Security.IsAllowed<ViewDesktopEquipmentTab>())
  700. return;
  701. SetVisibility(EquipmentDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  702. SetVisibility(EquipmentMessagesButton, Security.CanView<Notification>());
  703. SetVisibility(EquipmentTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  704. SetVisibility(EquipmentAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  705. SetVisibility(EquipmentMapButton, bMaps);
  706. SetVisibility(EquipmentDailyReportButton,
  707. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  708. SetVisibility(EquipmentButton, ClientFactory.IsSupported<Equipment>()
  709. && Security.CanView<Equipment>()
  710. && Security.IsAllowed<ViewDesktopEquipmentListScreen>());
  711. SetVisibleIfEither(EquipmentTaskSeparator,
  712. new FrameworkElement[]
  713. {
  714. EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton, EquipmentAttendanceButton, EquipmentMapButton,
  715. EquipmentDailyReportButton
  716. }, new FrameworkElement[] { EquipmentButton });
  717. SetVisibleIfAny(EquipmentActions, EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton,
  718. EquipmentAttendanceButton, EquipmentDailyReportButton, EquipmentButton);
  719. SetVisibility(TrackersMasterList, Security.CanView<GPSTracker>() && Security.IsAllowed<ViewDesktopGPSTrackersScreen>());
  720. AddSetupAction(EquipmentTab, "Tracker Types", TrackerTypes_Click, PRSDesktop.Resources.milestone,
  721. Security.CanView<GPSTrackerType>());
  722. AddSetupAction(EquipmentTab, "Stickers", Stickers_Click, PRSDesktop.Resources.barcode,
  723. Security.CanView<WebSticker>());
  724. AddSetupAction(EquipmentTab, "Digital Keys", DigitalKeys_Click, PRSDesktop.Resources.key,
  725. Security.CanView<DigitalKey>());
  726. AddSetupAction(EquipmentTab, "Equipment Groups", EquipmentGroupList_Click, PRSDesktop.Resources.specifications,
  727. Security.CanView<EquipmentGroup>());
  728. //EquipmentActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  729. //EquipmentReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  730. AddSetupModulesAndReports(EquipmentTab);
  731. SetTabVisibleIfAny(EquipmentTab, EquipmentButton, TrackersMasterList);
  732. }
  733. private void SetupAccountsTab(bool bMaps)
  734. {
  735. if (!Security.IsAllowed<ViewDesktopAccountsTab>())
  736. return;
  737. SetVisibility(AccountsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  738. SetVisibility(AccountsMessagesButton, Security.CanView<Notification>());
  739. SetVisibility(AccountsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  740. SetVisibility(AccountsDataButton, Security.IsAllowed<CanViewDataEntryPanel>());
  741. SetVisibility(AccountsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  742. SetVisibility(AccountsMapButton, bMaps);
  743. SetVisibility(AccountsDailyReportButton,
  744. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  745. SetVisibility(CustomerList, ClientFactory.IsSupported<Customer>()
  746. && Security.CanView<Customer>()
  747. && Security.IsAllowed<ViewDesktopCustomersScreen>());
  748. SetVisibility(InvoiceList, ClientFactory.IsSupported<Invoice>()
  749. && Security.CanView<Invoice>()
  750. && Security.IsAllowed<ViewDesktopInvoicesScreen>());
  751. SetVisibility(ReceiptList, ClientFactory.IsSupported<Receipt>()
  752. && Security.CanView<Receipt>()
  753. && Security.IsAllowed<ViewDesktopReceiptsScreen>());
  754. SetVisibility(SupplierList, ClientFactory.IsSupported<Supplier>()
  755. && Security.CanView<Supplier>()
  756. && Security.IsAllowed<ViewDesktopSuppliersScreen>());
  757. SetVisibility(PurchasesList, ClientFactory.IsSupported<PurchaseOrder>()
  758. && Security.CanView<PurchaseOrder>()
  759. && Security.IsAllowed<ViewDesktopPurchaseOrdersScreen>());
  760. SetVisibility(BillsList, ClientFactory.IsSupported<Bill>()
  761. && Security.CanView<Bill>()
  762. && Security.IsAllowed<ViewDesktopBillsScreen>());
  763. SetVisibility(PaymentsList, ClientFactory.IsSupported<Payment>()
  764. && Security.CanView<Payment>()
  765. && Security.IsAllowed<ViewDesktopPaymentsScreen>());
  766. SetVisibleIfEither(AccountsTaskSeparator1,
  767. new FrameworkElement[]
  768. {
  769. AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton, AccountsAttendanceButton, AccountsMapButton,
  770. AccountsDailyReportButton
  771. }, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList });
  772. SetVisibleIfEither(AccountsTaskSeparator2, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList },
  773. new FrameworkElement[] { SupplierList, PurchasesList, BillsList, PaymentsList });
  774. SetVisibleIfAny(AccountsActions, AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton,
  775. AccountsAttendanceButton,
  776. AccountsDailyReportButton, CustomerList, InvoiceList, ReceiptList, SupplierList, PurchasesList, BillsList, PaymentsList);
  777. AddSetupAction(AccountsTab, "Contact Types", ContactTypeList_Click, PRSDesktop.Resources.contacttype,
  778. ClientFactory.IsSupported<Contact>() && Security.CanView<ContactType>());
  779. AddSetupAction(AccountsTab, "Tax Codes", TaxCodeList_Click, PRSDesktop.Resources.taxcode,
  780. ClientFactory.IsSupported<GLCode>() && Security.CanView<TaxCode>());
  781. AddSetupAction(AccountsTab, "Receipt Types", ReceiptTypeList_Click, PRSDesktop.Resources.receipt,
  782. ClientFactory.IsSupported<GLCode>() && Security.CanView<ReceiptType>());
  783. AddSetupAction(AccountsTab, "Payment Types", PaymentTypeList_Click, PRSDesktop.Resources.payment,
  784. ClientFactory.IsSupported<GLCode>() && Security.CanView<PaymentType>());
  785. AddSetupAction(AccountsTab, "Cost Centres", CostCentresList_Click, PRSDesktop.Resources.costcentre,
  786. ClientFactory.IsSupported<CostCentre>() && Security.CanView<CostCentre>());
  787. AddSetupAction(AccountsTab, "GL Codes", GLCodesList_Click, PRSDesktop.Resources.glcode,
  788. ClientFactory.IsSupported<GLCode>() && Security.CanView<GLCode>());
  789. AddSetupAction(AccountsTab, "Purchase Order Categories", PurchaseOrderCategoriesButton_Click, PRSDesktop.Resources.service,
  790. ClientFactory.IsSupported<PurchaseOrderCategory>() && Security.CanView<PurchaseOrderCategory>());
  791. //AccountsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  792. //AccountsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  793. AddSetupSeparator(AccountsTab);
  794. AddSetupAction(AccountsTab, "Customer Spreadsheet Templates", () => ViewSpreadsheetTemplates<Customer>(), PRSDesktop.Resources.box,
  795. Security.CanView<CustomerSpreadsheet>());
  796. AddSetupAction(AccountsTab, "Supplier Spreadsheet Templates", () => ViewSpreadsheetTemplates<Supplier>(), PRSDesktop.Resources.box,
  797. Security.CanView<SupplierSpreadsheet>());
  798. AddSetupModulesAndReports(AccountsTab);
  799. SetTabVisibleIfAny(AccountsTab, CustomerList, InvoiceList, ReceiptList, SupplierList, PurchasesList, BillsList, PaymentsList);
  800. }
  801. private void SetupHumanResourcesTab(bool bMaps)
  802. {
  803. if (!Security.IsAllowed<ViewDesktopHumanResourcesTab>())
  804. return;
  805. SetVisibility(HumanResourcesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  806. SetVisibility(HumanResourcesMessagesButton, Security.CanView<Notification>());
  807. SetVisibility(HumanResourcesTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  808. SetVisibility(HumanResourcesAttendanceButton,
  809. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  810. SetVisibility(HumanResourcesMapButton, bMaps);
  811. SetVisibility(HumanResourcesDailyReportButton,
  812. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  813. SetVisibility(CalendarButton, Security.CanView<Assignment>() && Security.IsAllowed<ViewDesktopCalendarScreen>());
  814. SetVisibility(EmployeePlannerButton, Security.CanView<Assignment>() && Security.IsAllowed<ViewDesktopEmployeePlannerScreen>());
  815. SetVisibility(TimesheetsButton, Security.CanView<TimeSheet>() && Security.IsAllowed<ViewDesktopStaffTimeSheetsScreen>());
  816. SetVisibility(LeaveRequestsButton, Security.CanView<LeaveRequest>() && Security.IsAllowed<ViewDesktopLeaveRequestsScreen>());
  817. SetVisibility(OrgChartButton,
  818. ClientFactory.IsSupported<Employee>()
  819. && (
  820. Security.IsAllowed<CanViewOrgChartByEmployee>()
  821. || Security.IsAllowed<CanViewOrgChartByPosition>()
  822. || Security.IsAllowed<CanViewOrgChartByRole>()
  823. )
  824. && Security.IsAllowed<ViewDesktopOrgChartScreen>()
  825. );
  826. SetVisibility(MeetingsButton, Security.IsAllowed<ViewDesktopMeetingsScreen>());
  827. SetVisibleIfEither(HumanResourcesTaskSeparator,
  828. new FrameworkElement[]
  829. {
  830. HumanResourcesDashboardButton, HumanResourcesMessagesButton, HumanResourcesTaskButton, HumanResourcesAttendanceButton,
  831. HumanResourcesMapButton, HumanResourcesDailyReportButton
  832. }, new FrameworkElement[] { CalendarButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton });
  833. SetVisibleIfAny(HumanResourcesActions, HumanResourcesDashboardButton, HumanResourcesTaskButton,
  834. HumanResourcesAttendanceButton,
  835. HumanResourcesDailyReportButton, CalendarButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton);
  836. SetVisibility(UsersButton, Security.CanView<User>() && Security.IsAllowed<ViewDesktopUserAccountsScreen>());
  837. SetVisibility(EmployeesButton, Security.CanView<Employee>() && Security.IsAllowed<ViewDesktopEmployeeListScreen>());
  838. AddSetupAction(HumanResourcesTab, "Security Groups", SecurityGroupsButton_Click, PRSDesktop.Resources.securitygroup,
  839. Security.CanView<SecurityGroup>());
  840. AddSetupSeparator(HumanResourcesTab);
  841. AddSetupAction(HumanResourcesTab, "Employee Groups", GroupsSetup_Click, PRSDesktop.Resources.employees,
  842. Security.CanView<EmployeeGroup>());
  843. AddSetupAction(HumanResourcesTab, "Positions", PositionsSetup_Click, PRSDesktop.Resources.position,
  844. Security.CanView<EmployeePosition>());
  845. AddSetupAction(HumanResourcesTab, "Roles", RolesSetup_Click, PRSDesktop.Resources.employeerole,
  846. Security.CanView<EmployeeRole>());
  847. AddSetupAction(HumanResourcesTab, "Teams", EmployeeTeamsButton_Click, PRSDesktop.Resources.team,
  848. Security.CanView<EmployeeTeam>());
  849. AddSetupAction(HumanResourcesTab, "Activities", ActivityMenu_Click, PRSDesktop.Resources.quality,
  850. Security.CanView<Activity>());
  851. AddSetupAction(HumanResourcesTab, "Qualifications", QualificationMenu_Click, PRSDesktop.Resources.certificate,
  852. Security.CanView<Qualification>());
  853. AddSetupAction(HumanResourcesTab, "Rosters", RosterMenu_Click, PRSDesktop.Resources.assignments,
  854. Security.CanView<EmployeeRoster>());
  855. AddSetupSeparator(HumanResourcesTab);
  856. // AddSetupAction(HumanResourcesTab, "Rosters", RostersButton_Click, PRSDesktop.Resources.attendance,
  857. // Security.CanView<Roster>());
  858. AddSetupAction(HumanResourcesTab, "Overtime Rules", OvertimeRulesButton_Click, PRSDesktop.Resources.overtime,
  859. Security.CanView<OvertimeRule>());
  860. AddSetupAction(HumanResourcesTab, "Overtime", OvertimeButton_Click, PRSDesktop.Resources.overtime,
  861. Security.CanView<Overtime>());
  862. AddSetupAction(HumanResourcesTab, "Standard Leave", StandardLeaveButton_Click, PRSDesktop.Resources.fireworks,
  863. Security.CanView<StandardLeave>());
  864. SetVisibleIfEither(HumanResourcesSetupSeparator1,
  865. new FrameworkElement[] { CalendarButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton },
  866. new FrameworkElement[] { UsersButton, EmployeesButton });
  867. //HumanResourcesActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  868. //HumanResourcesReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  869. AddSetupSeparator(HumanResourcesTab);
  870. AddSetupAction(HumanResourcesTab, "Spreadsheet Templates", () => ViewSpreadsheetTemplates<Employee>(), PRSDesktop.Resources.box,
  871. Security.CanView<EmployeeSpreadsheet>());
  872. AddSetupModulesAndReports(HumanResourcesTab);
  873. SetTabVisibleIfAny(HumanResourcesTab, CalendarButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton, UsersButton, EmployeesButton);
  874. }
  875. private void SetupProductsTab(bool bMaps)
  876. {
  877. if (!Security.IsAllowed<ViewDesktopProductManagementTab>())
  878. return;
  879. SetVisibility(ProductsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  880. SetVisibility(ProductsMessagesButton, Security.CanView<Notification>());
  881. SetVisibility(ProductsTaskButton, Security.CanView<Kanban>());
  882. SetVisibility(ProductsAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  883. SetVisibility(ProductsMapButton, bMaps);
  884. SetVisibility(ProductsDailyReportButton,
  885. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  886. SetVisibility(ProductsMasterList, Security.CanView<Product>() && Security.IsAllowed<ViewDesktopProductListScreen>());
  887. SetVisibility(StockLocationList, Security.CanView<StockLocation>() && Security.IsAllowed<ViewDesktopStockLocationsScreen>());
  888. SetVisibility(StockMovementList, Security.CanView<StockMovement>() && Security.IsAllowed<ViewDesktopStockMovementsScreen>());
  889. SetVisibility(StockSummaryButton, Security.CanView<Product>()
  890. && Security.CanView<JobMaterial>()
  891. && Security.IsAllowed<ViewDesktopStockForecastScreen>());
  892. SetVisibility(ReservationManagementButton, Security.IsAllowed<ViewDesktopReservationManagementScreen>());
  893. SetVisibleIfEither(ProductsTaskSeparator,
  894. new FrameworkElement[]
  895. {
  896. ProductsDashboardButton, ProductsMessagesButton, ProductsTaskButton, ProductsAttendanceButton, ProductsMapButton,
  897. ProductsDailyReportButton
  898. }, new FrameworkElement[] { ProductsMasterList, StockLocationList, StockMovementList, StockSummaryButton });
  899. SetVisibleIfAny(ProductActions, ProductsMasterList, StockLocationList, StockMovementList, StockSummaryButton);
  900. AddSetupAction(ProductTab, "Product Dimensions", ProductDimensionUnitsList_Click, PRSDesktop.Resources.unitofmeasure,
  901. Security.CanView<ProductDimensionUnit>());
  902. AddSetupAction(ProductTab, "Product Groups", ProductGroupsList_Click, PRSDesktop.Resources.productgroup,
  903. Security.CanView<ProductGroup>());
  904. AddSetupAction(ProductTab, "Product Styles", ProductStylesList_Click, PRSDesktop.Resources.palette,
  905. Security.CanView<ProductStyle>());
  906. AddSetupAction(ProductTab, "Stock Areas", StockAreasList_Click, PRSDesktop.Resources.rack,
  907. Security.CanView<StockArea>());
  908. AddSetupAction(ProductTab, "Stock Warehouses", StockWarehouseList_Click, PRSDesktop.Resources.factorysetup,
  909. Security.CanView<StockWarehouse>());
  910. AddSetupSeparator(ProductTab);
  911. AddSetupAction(ProductTab, "Spreadsheet Templates", () => ViewSpreadsheetTemplates<Product>(), PRSDesktop.Resources.box,
  912. Security.CanView<ProductSpreadsheet>());
  913. AddSetupModulesAndReports(ProductTab);
  914. SetTabVisibleIfAny(ProductTab, ProductActions);
  915. }
  916. private void SetupLogisticsTab(bool bMaps)
  917. {
  918. if (!Security.IsAllowed<ViewDesktopLogisticsTab>())
  919. return;
  920. SetVisibility(LogisticsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  921. SetVisibility(LogisticsMessagesButton, Security.CanView<Notification>());
  922. SetVisibility(LogisticsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  923. SetVisibility(LogisticsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  924. SetVisibility(LogisticsMapButton, bMaps);
  925. SetVisibility(LogisticsDailyReportButton,
  926. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  927. SetVisibility(ReadyToGoItemsButton,
  928. ClientFactory.IsSupported<DeliveryItem>()
  929. && Security.IsAllowed<CanViewLogisticsReadyToGo>()
  930. && Security.IsAllowed<ViewDesktopReadyToGoScreen>());
  931. SetVisibility(DispatchButton, Security.CanView<Shipment>()
  932. && Security.CanView<DeliveryItem>()
  933. && Security.IsAllowed<ViewDesktopRackListScreen>());
  934. SetVisibility(RequisitionsButton, Security.CanView<Requisition>() && Security.IsAllowed<ViewDesktopSiteRequisitionsScreen>());
  935. SetVisibility(DeliveriesButton, Security.IsAllowed<CanViewDeliveriesModule>() && Security.IsAllowed<ViewDesktopDeliveriesScren>());
  936. SetVisibility(DeliveredItemsButton,
  937. ClientFactory.IsSupported<DeliveryItem>()
  938. && Security.IsAllowed<CanViewDeliveredOnSite>()
  939. && Security.IsAllowed<ViewDesktopDeliveredOnSiteScreen>());
  940. SetVisibility(ConsignmentButton, Security.CanView<Consignment>() && Security.IsAllowed<ViewDesktopIncomingConsignmentsScreen>());
  941. SetVisibleIfEither(LogisticsTaskSeparator1,
  942. new FrameworkElement[]
  943. {
  944. LogisticsDashboardButton, LogisticsMessagesButton, LogisticsTaskButton, LogisticsAttendanceButton, LogisticsMapButton,
  945. LogisticsDailyReportButton
  946. },
  947. new FrameworkElement[]
  948. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton });
  949. SetVisibleIfEither(LogisticsTaskSeparator2,
  950. new FrameworkElement[]
  951. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton },
  952. new FrameworkElement[] { ConsignmentButton });
  953. AddSetupAction(LogisticsTab, "Delivery Types", DeliveryTypesButton_Click, PRSDesktop.Resources.truck,
  954. Security.CanView<ConsignmentType>());
  955. AddSetupAction(LogisticsTab, "Consignment Types", ConsignmentTypesButton_Click, PRSDesktop.Resources.service,
  956. Security.CanView<DeliveryType>());
  957. //LogisticsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  958. //LogisticsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  959. AddSetupModulesAndReports(LogisticsTab);
  960. SetTabVisibleIfAny(LogisticsTab, DispatchButton, RequisitionsButton, DeliveriesButton, ReadyToGoItemsButton,
  961. DeliveredItemsButton,
  962. ConsignmentButton);
  963. }
  964. private void SetupManufacturingTab(bool bMaps)
  965. {
  966. if (!Security.IsAllowed<ViewDesktopManufacturingTab>())
  967. return;
  968. SetVisibility(ManufacturingDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  969. SetVisibility(ManufacturingMessagesButton, Security.CanView<Notification>());
  970. SetVisibility(ManufacturingTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  971. SetVisibility(ManufacturingAttendanceButton,
  972. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  973. SetVisibility(ManufacturingMapButton, bMaps);
  974. SetVisibility(ManufacturingDailyReportButton,
  975. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  976. SetVisibility(FactoryStatusButton,
  977. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket>()
  978. && Security.IsAllowed<CanViewFactoryStatus>()
  979. && Security.IsAllowed<ViewDesktopManufacturingStatusScreen>());
  980. SetVisibility(FactoryAllocationButton,
  981. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket, ManufacturingPacketStage>()
  982. && Security.IsAllowed<CanViewFactoryAllocation>()
  983. && Security.IsAllowed<ViewDesktopFactoryAllocationScreen>());
  984. //SetVisibility(FactoryScheduleButton, ClientFactory.IsSupported<Booking>() && ClientFactory.IsEnabled<>());
  985. SetVisibility(FactoryFloorButton,
  986. ClientFactory.IsSupported<ManufacturingPacket>()
  987. && Security.IsAllowed<CanViewFactoryFloor>()
  988. && Security.IsAllowed<ViewDesktopFactoryFloorScreen>());
  989. //SetVisibility(FactoryReadyButton, ClientFactory.IsSupported<ManufacturingPacket>() && Security.IsAllowed<CanViewFactoryReadyToGo>());
  990. SetVisibleIfEither(ManufacturingTaskSeparator,
  991. new FrameworkElement[]
  992. {
  993. ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton, ManufacturingAttendanceButton,
  994. ManufacturingMapButton, ManufacturingDailyReportButton
  995. }, new FrameworkElement[] { FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton /* , FactoryReadyButton */ });
  996. SetVisibleIfAny(ManufacturingActions, ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton,
  997. ManufacturingAttendanceButton, ManufacturingDailyReportButton, FactoryStatusButton, FactoryAllocationButton,
  998. FactoryFloorButton);
  999. AddSetupAction(ManufacturingTab, "Factory Settings", FactorySetup_Click, PRSDesktop.Resources.factorysetup,
  1000. ClientFactory.IsSupported<ManufacturingFactory>() && Security.IsAllowed<CanViewFactorySettings>());
  1001. AddSetupAction(ManufacturingTab, "Manufacturing Templates", TemplateSetup_Click, PRSDesktop.Resources.template,
  1002. Security.CanView<ManufacturingTemplate>());
  1003. AddSetupAction(ManufacturingTab, "Manufacturing Trolleys", TrolleySetup_Click, PRSDesktop.Resources.trolley,
  1004. Security.CanView<ManufacturingTrolley>());
  1005. AddSetupAction(ManufacturingTab, "Lost Time Types", LostTimeSetup_Click, PRSDesktop.Resources.smiley,
  1006. Security.CanView<ManufacturingLostTime>());
  1007. //ManufacturingActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  1008. //ManufacturingReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  1009. AddSetupModulesAndReports(ManufacturingTab);
  1010. SetTabVisibleIfAny(ManufacturingTab, FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton);
  1011. }
  1012. private void SetupProjectsTab(bool bMaps)
  1013. {
  1014. if (!Security.IsAllowed<ViewDesktopProjectsTab>())
  1015. return;
  1016. SetVisibility(ProjectsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  1017. SetVisibility(ProjectMessagesButton, Security.CanView<Notification>());
  1018. SetVisibility(ProjectTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  1019. SetVisibility(ProjectAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  1020. SetVisibility(ProjectsMapButton, bMaps);
  1021. SetVisibility(ProjectDailyReportButton,
  1022. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  1023. SetVisibility(ProjectsButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopProjectsScreen>());
  1024. SetVisibility(ServiceButton, false);
  1025. SetVisibility(ProjectPlannerButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopProjectPlannerScreen>());
  1026. SetVisibility(DesignManagementButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopDesignManagementScreen>());
  1027. SetVisibleIfEither(ProjectTaskSeparator,
  1028. new FrameworkElement[]
  1029. {
  1030. ProjectsDashboardButton, ProjectMessagesButton, ProjectTaskButton, ProjectAttendanceButton, ProjectsMapButton,
  1031. ProjectDailyReportButton
  1032. }, new FrameworkElement[] { QuotesButton, ProjectsButton, ServiceButton, ProjectPlannerButton });
  1033. AddSetupAction(ProjectsTab, "Job Statuses", JobStatusButton_Click, PRSDesktop.Resources.view,
  1034. Security.CanView<JobStatus>());
  1035. AddSetupAction(ProjectsTab, "Document MileStones", JobDocumentMileStoneButton_OnClick, PRSDesktop.Resources.revision,
  1036. true);
  1037. //AddSetupAction(ProjectsTab, "Document Tags", JobDocumentTagButton_OnClick, PRSDesktop.Resources.checklist,
  1038. // true);
  1039. AddSetupAction(ProjectsTab, "Financial Statuses", FinancialStatusButton_Click, PRSDesktop.Resources.view,
  1040. Security.CanView<JobFinancial>());
  1041. AddSetupAction(ProjectsTab, "Drawing Templates", DrawingTemplatesButton_Click, PRSDesktop.Resources.doc_misc,
  1042. true);
  1043. AddSetupSeparator(ProjectsTab);
  1044. AddSetupAction(ProjectsTab, "Spreadsheet Templates", () => ViewSpreadsheetTemplates<Job>(), PRSDesktop.Resources.box,
  1045. Security.CanView<JobSpreadsheet>());
  1046. AddSetupSeparator(ProjectsTab);
  1047. AddSetupAction(ProjectsTab, "Manufacturing Watermarks", ViewWaterMarks, PRSDesktop.Resources.design,
  1048. Security.IsAllowed<CanConfigureFactoryFloor>());
  1049. AddSetupAction(ProjectsTab, "Setout Groups", ViewSetoutGroups, PRSDesktop.Resources.draw,
  1050. Security.IsAllowed<CanConfigureFactoryFloor>());
  1051. AddSetupModulesAndReports(ProjectsTab);
  1052. //ProjectsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  1053. //ProjectReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  1054. SetTabVisibleIfAny(ProjectsTab, ProjectsButton, ServiceButton, ProjectPlannerButton);
  1055. }
  1056. private void SetupQuotesTab(bool bMaps)
  1057. {
  1058. if (!Security.IsAllowed<ViewDesktopQuotesTab>())
  1059. return;
  1060. SetVisibility(QuotesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  1061. SetVisibility(QuotesMessagesButton, Security.CanView<Notification>());
  1062. SetVisibility(QuotesTaskButton, Security.IsAllowed<CanViewTasks>());
  1063. SetVisibility(QuotesAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  1064. SetVisibility(QuotesMapButton, bMaps);
  1065. SetVisibility(QuotesDailyReportButton,
  1066. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  1067. SetVisibility(QuotesButton, Security.CanView<Quote>() && Security.IsAllowed<ViewDesktopQuotesScreen>());
  1068. SetVisibility(KitsMasterList, Security.CanView<Kit>() && Security.IsAllowed<ViewDesktopProductKitsScreen>());
  1069. SetVisibility(CostSheetsMasterList, Security.CanView<CostSheet>() && Security.IsAllowed<ViewDesktopCostSheetsScreen>());
  1070. SetVisibleIfEither(QuotesTaskSeparator,
  1071. new FrameworkElement[]
  1072. {
  1073. QuotesDashboardButton, QuotesMessagesButton, QuotesTaskButton, QuotesAttendanceButton, QuotesMapButton,
  1074. QuotesDailyReportButton
  1075. }, new FrameworkElement[] { QuotesButton });
  1076. SetVisibleIfEither(QuotesActionSeparator, new FrameworkElement[] { QuotesButton },
  1077. new FrameworkElement[] { KitsMasterList, CostSheetsMasterList });
  1078. SetVisibleIfAny(QuotesActions, QuotesButton, KitsMasterList, CostSheetsMasterList);
  1079. AddSetupAction(QuotesTab, "Status Codes", QuoteStatusButton_Click, PRSDesktop.Resources.quotestatus,
  1080. ClientFactory.IsSupported<Quote>() && Security.IsAllowed<CanModifyQuoteStatuses>());
  1081. AddSetupAction(QuotesTab, "Design Sections", QuoteDesignSectionButton_Click, PRSDesktop.Resources.design,
  1082. Security.CanView<QuoteDesignSection>());
  1083. AddSetupSeparator(QuotesTab);
  1084. AddSetupAction(QuotesTab, "Kit Conditions", KitConditionList_Click, PRSDesktop.Resources.kitcondition,
  1085. Security.CanView<KitCondition>());
  1086. AddSetupAction(QuotesTab, "Kit Formulae", KitFormulaeList_Click, PRSDesktop.Resources.kitformula,
  1087. Security.CanView<KitFormula>());
  1088. AddSetupAction(QuotesTab, "Cost Sheet Types", CostSheetTypeList_Click, PRSDesktop.Resources.costsheettype,
  1089. Security.CanView<CostSheetType>());
  1090. AddSetupAction(QuotesTab, "Cost Sheet Brands", CostSheetBrandList_Click, PRSDesktop.Resources.costsheetbrand,
  1091. Security.CanView<CostSheetBrand>());
  1092. AddSetupAction(QuotesTab, "Cost Sheet Sections", CostSheetSectionList_Click, PRSDesktop.Resources.costsheetsection,
  1093. Security.CanView<CostSheetSection>());
  1094. AddSetupSeparator(QuotesTab);
  1095. AddSetupAction(QuotesTab, "Symbols", QuoteDiagramSymbols_Checked, PRSDesktop.Resources.pencil,
  1096. Security.CanView<QuoteDiagramSymbol>());
  1097. AddSetupAction(QuotesTab, "Symbol Types", QuoteDiagramSymbolTypes_Checked, PRSDesktop.Resources.attachment,
  1098. Security.CanView<QuoteDiagramSymbol>());
  1099. AddSetupAction(QuotesTab, "Dimension Types", QuoteTakeOffUnits_Click, PRSDesktop.Resources.box,
  1100. Security.CanView<QuoteTakeOffUnit>());
  1101. AddSetupSeparator(QuotesTab);
  1102. AddSetupAction(QuotesTab, "Spreadsheet Templates", ViewSpreadsheetTemplates<Quote>, PRSDesktop.Resources.box,
  1103. Security.CanView<QuoteSpreadsheet>());
  1104. AddSetupModulesAndReports(QuotesTab);
  1105. SetTabVisibleIfAny(QuotesTab, QuotesActions);
  1106. }
  1107. private void ViewSpreadsheetTemplates<TEntity>() where TEntity : Entity
  1108. {
  1109. SpreadsheetTemplateGrid grid = new SpreadsheetTemplateGrid();
  1110. grid.AppliesTo = typeof(TEntity);
  1111. grid.Refresh(true, true);
  1112. DynamicContentDialog dlg = new DynamicContentDialog(grid, false);
  1113. dlg.Title = $"{typeof(TEntity).EntityName().Split(".").Last()} Spreadsheet Templates";
  1114. dlg.ShowDialog();
  1115. }
  1116. private IEnumerable<ReportExportDefinition> AddTemplateDefinitions()
  1117. {
  1118. if (CurrentPanel == null)
  1119. return new List<ReportExportDefinition>() { new ReportExportDefinition("Email Report", PRSDesktop.Resources.email, ReportExportType.PDF,
  1120. EmailUtils.DoEmailReport)};
  1121. else
  1122. return EmailUtils.CreateTemplateDefinitions(CurrentPanel.DataModel(Selection.None));
  1123. }
  1124. private void SetupDock<TSecurityDescriptor>(LayoutAnchorable layout, IDockPanel dock)
  1125. where TSecurityDescriptor : ISecurityDescriptor, new()
  1126. {
  1127. if (Security.IsAllowed<TSecurityDescriptor>())
  1128. {
  1129. if (!DockGroup.Children.Any(x => x == layout))
  1130. {
  1131. DockGroup.Children.Add(layout);
  1132. }
  1133. if (layout.IsVisible && (ClientFactory.UserGuid != Guid.Empty))
  1134. dock.Setup();
  1135. }
  1136. else
  1137. {
  1138. DockGroup.RemoveChild(layout);
  1139. }
  1140. }
  1141. private void LoadApplicationState()
  1142. {
  1143. if (ClientFactory.UserGuid != Guid.Empty)
  1144. {
  1145. _ribbon.IsCollapsed = false;
  1146. if (OutstandingDailyReports(false))
  1147. {
  1148. MessageBox.Show("There are outstanding Daily Reports that must be filled out before continuing!" +
  1149. "\n\nAccess to PRS is restricted until this is corrected.",
  1150. "Outstanding Reports"
  1151. );
  1152. var dailyReportPanel = LoadWindow<DailyReport>(ProjectDailyReportButton);
  1153. dailyReportPanel.OnTimeSheetConfirmed += e =>
  1154. {
  1155. if (!OutstandingDailyReports(true))
  1156. {
  1157. ConfigureMainScreen();
  1158. LoadApplicationState();
  1159. }
  1160. };
  1161. return;
  1162. }
  1163. using (new WaitCursor())
  1164. {
  1165. _ribbon.IsCollapsed = false;
  1166. LoadInitialWindow();
  1167. }
  1168. }
  1169. }
  1170. private void LoadInitialWindow()
  1171. {
  1172. var app = new LocalConfiguration<AppSettings>().Load();
  1173. if (app.Settings.ContainsKey("CurrentPanel"))
  1174. {
  1175. try
  1176. {
  1177. var bFound = false;
  1178. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1179. if (module.Length == 2)
  1180. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1181. {
  1182. if (String.Equals(tab.Header, module.First()))
  1183. {
  1184. _ribbon.SelectedTabItem = tab;
  1185. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1186. {
  1187. foreach (var item in bar.Items)
  1188. {
  1189. var button = item as Fluent.Button;
  1190. if (button != null && String.Equals(button.Header, module.Last()))
  1191. {
  1192. bFound = true;
  1193. button.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
  1194. break;
  1195. }
  1196. }
  1197. if (bFound)
  1198. break;
  1199. }
  1200. }
  1201. if (bFound)
  1202. break;
  1203. }
  1204. }
  1205. catch (Exception e)
  1206. {
  1207. MessageBox.Show(string.Format("Unable to Load {0}!\n\n{1}\n{2}", app.Settings["CurrentPanel"], e.Message, e.StackTrace));
  1208. }
  1209. }
  1210. }
  1211. private void _ribbon_OnLoaded(object sender, RoutedEventArgs e)
  1212. {
  1213. _ribbon.SelectedTabItem = CurrentTab;
  1214. }
  1215. private void LoadSecondaryWindows()
  1216. {
  1217. if (ClientFactory.UserGuid != Guid.Empty)
  1218. {
  1219. var windows = App.DatabaseSettings.SecondaryWindows;
  1220. foreach (var key in windows.Keys.ToArray())
  1221. {
  1222. _secondarywindows[key] = new SecondaryWindow(
  1223. key,
  1224. windows[key].Item1,
  1225. windows[key].Item2,
  1226. windows[key].Item3,
  1227. windows[key].Item4,
  1228. windows[key].Item5,
  1229. windows[key].Item6
  1230. );
  1231. _secondarywindows[key].Closed += (o, e) => { _secondarywindows.Remove(key); };
  1232. _secondarywindows[key].Show();
  1233. }
  1234. }
  1235. else
  1236. {
  1237. foreach (var key in _secondarywindows.Keys.ToArray())
  1238. {
  1239. App.IsClosing = true;
  1240. _secondarywindows[key].Close();
  1241. App.IsClosing = false;
  1242. }
  1243. }
  1244. }
  1245. private Fluent.RibbonTabItem GetTabItem(FrameworkElement? sender)
  1246. {
  1247. if (sender == null)
  1248. throw new Exception("No Tab Found!");
  1249. if (sender is Fluent.RibbonTabItem)
  1250. return (Fluent.RibbonTabItem)sender;
  1251. return GetTabItem(sender.Parent as FrameworkElement);
  1252. }
  1253. private T? LoadWindow<T>(Fluent.Button sender) where T : class, IBasePanel, new()
  1254. {
  1255. return LoadWindow<T>(sender, new CancelEventArgs());
  1256. }
  1257. private T? LoadWindow<T>(Fluent.Button sender, CancelEventArgs cancel) where T : class, IBasePanel, new()
  1258. {
  1259. using (new WaitCursor())
  1260. {
  1261. UnloadWindow(cancel);
  1262. if (cancel.Cancel)
  1263. {
  1264. return null;
  1265. }
  1266. CurrentTab = GetTabItem(sender);
  1267. CurrentButton = sender;
  1268. //CurrentButton.IsSelected = true;
  1269. UpdateRibbonColors();
  1270. var panel = new T();
  1271. CurrentPanel = panel;
  1272. ReportUtils.ExportDefinitions.Clear();
  1273. ReportUtils.ExportDefinitions.AddRange(AddTemplateDefinitions());
  1274. InitializePanelProperties(panel);
  1275. CurrentPanel.IsReady = false;
  1276. CurrentPanel.Setup();
  1277. CurrentPanel.IsReady = true;
  1278. CurrentPanel.OnUpdateDataModel += (s, m) =>
  1279. {
  1280. ReloadModules(s, m);
  1281. ReloadReports(s, m);
  1282. };
  1283. CurrentPanel_Label = sender.Header?.ToString() ?? "";
  1284. CurrentPanel_Ticks = DateTime.Now;
  1285. ContentControl.Content = CurrentPanel;
  1286. Title =
  1287. $"{CurrentPanel_Label} - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1288. if (sender != null)
  1289. {
  1290. var model = CurrentPanel.DataModel(Selection.None);
  1291. var section = CurrentPanel.SectionName;
  1292. ReloadModules(section, model);
  1293. ReloadReports(section, model);
  1294. }
  1295. CurrentPanel.Refresh();
  1296. if (CurrentPanel is NotificationPanel)
  1297. {
  1298. Logger.Send(LogType.Information, ClientFactory.UserID, "Disabling Heartbeat");
  1299. NotificationsWatchDog.IsEnabled = false;
  1300. Notifications.Visibility = Visibility.Collapsed;
  1301. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  1302. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  1303. }
  1304. else
  1305. {
  1306. ReloadNotifications();
  1307. }
  1308. if (sender != null)
  1309. {
  1310. var settings = new LocalConfiguration<AppSettings>().Load();
  1311. var module = string.Format("{0} / {1}", CurrentTab?.Header, sender.Header);
  1312. if (!settings.Settings.ContainsKey("CurrentPanel") || module != settings.Settings["CurrentPanel"])
  1313. {
  1314. settings.Settings["CurrentPanel"] = module;
  1315. try
  1316. {
  1317. new LocalConfiguration<AppSettings>().Save(settings);
  1318. }
  1319. catch (Exception e)
  1320. {
  1321. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1322. }
  1323. }
  1324. }
  1325. //stopwatch.Stop();
  1326. //Logger.Send(LogType.Information, ClientFactory.UserID, String.Format("Loading {0} to took {1} ms", sender != null ? sender.Label : module, stopwatch.ElapsedMilliseconds));
  1327. return panel;
  1328. }
  1329. }
  1330. private void UpdateRibbonColors()
  1331. {
  1332. foreach (var tab in _ribbon.Tabs)
  1333. {
  1334. bool bFound = false;
  1335. foreach (var grp in tab.Groups)
  1336. {
  1337. foreach (var btn in grp.Items)
  1338. {
  1339. if (btn is Fluent.Button fluentbutton)
  1340. {
  1341. bFound = bFound || (btn == CurrentButton);
  1342. fluentbutton.Background = (btn == CurrentButton) ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1343. fluentbutton.Foreground = (btn == CurrentButton) ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1344. }
  1345. }
  1346. tab.Background = bFound ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1347. tab.Foreground = bFound ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1348. }
  1349. }
  1350. }
  1351. private static void StartLocalDatabase(IProgress<string> progress)
  1352. {
  1353. var dirName = Path.GetDirectoryName(App.DatabaseSettings.FileName);
  1354. if (!Directory.Exists(dirName) && dirName != null)
  1355. Directory.CreateDirectory(dirName);
  1356. var FileName = App.DatabaseSettings.FileName;
  1357. var Exists = File.Exists(FileName);
  1358. progress.Report("Configuring Stores");
  1359. DbFactory.Stores = CoreUtils.TypeList(
  1360. new[]
  1361. {
  1362. typeof(DocumentStore).Assembly,
  1363. typeof(EquipmentStore).Assembly
  1364. },
  1365. myType =>
  1366. myType.IsClass
  1367. && !myType.IsAbstract
  1368. && !myType.IsGenericType
  1369. && myType.GetInterfaces().Contains(typeof(IStore))
  1370. ).ToArray();
  1371. DbFactory.Provider = new SQLiteProvider(App.DatabaseSettings.FileName);
  1372. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  1373. DbFactory.Logo = App.DatabaseSettings.Logo;
  1374. progress.Report("Starting Local Database");
  1375. DbFactory.Start();
  1376. progress.Report("Checking Database");
  1377. var users = DbFactory.Provider.Load<User>();
  1378. if (!users.Any())
  1379. {
  1380. var user = new User { UserID = "ADMIN", Password = "admin" };
  1381. DbFactory.Provider.Save(user);
  1382. var employee = DbFactory.Provider.Load(new Filter<Employee>(x => x.Code).IsEqualTo("ADMIN")).FirstOrDefault();
  1383. employee ??= new Employee { Code = "ADMIN", Name = "Administrator Account" };
  1384. employee.UserLink.ID = user.ID;
  1385. DbFactory.Provider.Save(employee);
  1386. }
  1387. StoreUtils.GoogleAPIKey = App.DatabaseSettings.GoogleAPIKey;
  1388. Job.JobNumberPrefix = App.DatabaseSettings.JobPrefix;
  1389. PurchaseOrder.PONumberPrefix = App.DatabaseSettings.PurchaseOrderPrefix;
  1390. }
  1391. #endregion
  1392. #region Login Management
  1393. private ValidationStatus? DoLogin(bool autoLogin)
  1394. {
  1395. ValidationStatus? result = null;
  1396. if (autoLogin)
  1397. {
  1398. if (App.DatabaseSettings.LoginType == LoginType.UserID)
  1399. {
  1400. try
  1401. {
  1402. result = ClientFactory.Validate(App.DatabaseSettings.UserID, App.DatabaseSettings.Password);
  1403. }
  1404. catch (Exception e)
  1405. {
  1406. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error connecting to server: {CoreUtils.FormatException(e)}");
  1407. MessageBox.Show("Error connecting to server.\nPlease check the server URL and port number.");
  1408. result = null;
  1409. }
  1410. if (result == ValidationStatus.INVALID)
  1411. {
  1412. MessageBox.Show("Unable to Login with User ID: " + App.DatabaseSettings.UserID);
  1413. }
  1414. }
  1415. }
  1416. if (result != ValidationStatus.VALID)
  1417. {
  1418. var login = new PinLogin(CoreUtils.GetVersion(), result ?? ValidationStatus.INVALID);
  1419. if (login.ShowDialog() == true)
  1420. {
  1421. result = ValidationStatus.VALID;
  1422. }
  1423. }
  1424. return result ?? ValidationStatus.INVALID;
  1425. }
  1426. /// <summary>
  1427. /// To be called after <see cref="DoLogin(bool)"/> and if a valid login session exists. Configures the main screen and loads the windows.
  1428. /// </summary>
  1429. private void AfterLogin()
  1430. {
  1431. LoadCurrentEmployee();
  1432. if (CheckTimesheetBypass(true))
  1433. {
  1434. UpdateCurrentLogin();
  1435. }
  1436. else
  1437. {
  1438. MessageBox.Show("You must clock on before logging in to PRS!");
  1439. ClientFactory.InvalidateUser();
  1440. App.EmployeeID = Guid.Empty;
  1441. App.EmployeeName = "";
  1442. App.EmployeeEmail = "";
  1443. }
  1444. ApplyColorScheme();
  1445. ConfigureMainScreen();
  1446. LoadApplicationState();
  1447. LoadSecondaryWindows();
  1448. //if (_ribbon.Menu.IsVisible)
  1449. //{
  1450. // _ribbon.;
  1451. //}
  1452. }
  1453. /// <summary>
  1454. /// 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.
  1455. /// </summary>
  1456. private void UpdateCurrentLogin()
  1457. {
  1458. if (CoreUtils.GetVersion().Equals("???"))
  1459. return;
  1460. // Register this station with the Server
  1461. // Later on, the heartbeat will check to make sure
  1462. // that the StationID hasn't changed. If it has,
  1463. // then we've logged in somewhere else and we'll
  1464. // drop out of this station
  1465. var curr = new Client<Login>().Query(
  1466. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  1467. null
  1468. ).Rows.FirstOrDefault();
  1469. if (curr != null)
  1470. {
  1471. var c = curr.ToObject<Login>();
  1472. c.StationID = station.StationID;
  1473. station = c;
  1474. }
  1475. else
  1476. {
  1477. station.User.ID = ClientFactory.UserGuid;
  1478. station.TimeStamp = DateTime.Now;
  1479. }
  1480. new Client<Login>().Save(station, "", (o, e) => { });
  1481. }
  1482. private void LoadCurrentEmployee()
  1483. {
  1484. var me = new Client<Employee>().Query(
  1485. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid),
  1486. new Columns<Employee>(x => x.ID).Add(x => x.Email).Add(x => x.Name)
  1487. );
  1488. App.EmployeeID = me.Rows.FirstOrDefault()?.Get<Employee, Guid>(x => x.ID) ?? Guid.Empty;
  1489. App.EmployeeName = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Name) ?? "";
  1490. App.EmployeeEmail = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Email) ?? "";
  1491. }
  1492. private void ExecuteLogout()
  1493. {
  1494. new Client<Login>().Delete(station, "");
  1495. station.ID = Guid.Empty;
  1496. App.EmployeeID = Guid.Empty;
  1497. App.EmployeeName = "";
  1498. App.EmployeeEmail = "";
  1499. }
  1500. /// <summary>
  1501. /// Logs the user out and unloads windows
  1502. /// </summary>
  1503. /// <param name="message">A message to display as the reason for logging out, or <c>null</c> for no message.</param>
  1504. private bool Logout(string? message = null, bool force = false)
  1505. {
  1506. // 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,
  1507. // all the queries that get called here will throw exceptions and thus break our system, failing to log out.
  1508. try
  1509. {
  1510. FinalizeAutoTimesheet();
  1511. }
  1512. catch
  1513. {
  1514. if (!force) throw;
  1515. }
  1516. // Try to unload the window;
  1517. try
  1518. {
  1519. UnloadWindow(null);
  1520. if (DatabaseType == DatabaseType.Standalone && !CoreUtils.GetVersion().Equals("???"))
  1521. scheduler.Stop();
  1522. }
  1523. catch
  1524. {
  1525. if (!force) throw;
  1526. }
  1527. // Next, try to set things to being empty
  1528. try
  1529. {
  1530. if (!CoreUtils.GetVersion().Equals("???"))
  1531. if (station.ID != Guid.Empty)
  1532. {
  1533. ExecuteLogout();
  1534. }
  1535. ClearTrackingKanban();
  1536. }
  1537. catch
  1538. {
  1539. if (!force) throw;
  1540. }
  1541. ClientFactory.InvalidateUser();
  1542. ConfigureMainScreen();
  1543. LoadSecondaryWindows();
  1544. if (message != null)
  1545. {
  1546. MessageBox.Show(message);
  1547. }
  1548. if (DoLogin(false) == ValidationStatus.VALID)
  1549. {
  1550. AfterLogin();
  1551. }
  1552. return true;
  1553. }
  1554. #endregion
  1555. #region Timesheets
  1556. private void RefreshTimeSheets()
  1557. {
  1558. if (App.EmployeeID == Guid.Empty)
  1559. return;
  1560. var filter = new Filter<TimeSheet>(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID);
  1561. filter = filter.And(new Filter<TimeSheet>(x => x.Confirmed).IsEqualTo(DateTime.MinValue).Or(x => x.Date).IsEqualTo(DateTime.Today));
  1562. _timesheets = new Client<TimeSheet>().Query(
  1563. filter,
  1564. new Columns<TimeSheet>(
  1565. x => x.ID,
  1566. x => x.Date,
  1567. x => x.Finish
  1568. )
  1569. );
  1570. }
  1571. private CoreTable GetTimesheet()
  1572. {
  1573. return new Client<TimeSheet>().Query(
  1574. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today)
  1575. .And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID)
  1576. .And(x => x.Finish).IsEqualTo(TimeSpan.Zero)
  1577. );
  1578. }
  1579. private bool CheckTimesheetBypass(bool message)
  1580. {
  1581. if (!ClientFactory.IsSupported<TimeSheet>())
  1582. return true;
  1583. var isClockedOn = IsClockedOn();
  1584. if (!Security.IsAllowed<CanBypassTimeBench>())
  1585. {
  1586. if (!isClockedOn)
  1587. {
  1588. if (message)
  1589. MessageBox.Show("You must clock on before opening this screen");
  1590. return false;
  1591. }
  1592. return true;
  1593. }
  1594. if (Security.IsAllowed<AutoGenerateTimesheet>())
  1595. if (!isClockedOn)
  1596. {
  1597. var ts = new TimeSheet();
  1598. ts.Date = DateTime.Today;
  1599. ts.Start = DateTime.Now.TimeOfDay;
  1600. ts.EmployeeLink.ID = App.EmployeeID;
  1601. ts.Notes = "Automatic Login from PRS Desktop";
  1602. new Client<TimeSheet>().Save(ts, "AutoLogon because Timebench Bypass is enabled", (o, e) => { });
  1603. }
  1604. return true;
  1605. }
  1606. private bool IsClockedOn()
  1607. {
  1608. RefreshTimeSheets();
  1609. if (_timesheets == null)
  1610. return false;
  1611. return _timesheets.Rows.Any(r =>
  1612. r.Get<TimeSheet, DateTime>(c => c.Date).Date == DateTime.Today && r.Get<TimeSheet, TimeSpan>(c => c.Finish) == new TimeSpan());
  1613. }
  1614. #endregion
  1615. private string CurrentPanelSlug()
  1616. {
  1617. var app = new LocalConfiguration<AppSettings>().Load();
  1618. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1619. return module.LastOrDefault()?.Replace(" ", "_").Replace("/", "") ?? "";
  1620. }
  1621. private bool ShowHelp()
  1622. {
  1623. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + CurrentPanelSlug()) { UseShellExecute = true });
  1624. return true;
  1625. }
  1626. private void Wiki_Click(object sender, RoutedEventArgs e)
  1627. {
  1628. ShowHelp();
  1629. }
  1630. private void Window_Loaded(object sender, RoutedEventArgs e)
  1631. {
  1632. }
  1633. private void UnloadWindow(CancelEventArgs? cancel)
  1634. {
  1635. if (CurrentPanel != null)
  1636. {
  1637. Heartbeat(DateTime.Now - CurrentPanel_Ticks, true);
  1638. try
  1639. {
  1640. CurrentPanel.Shutdown(cancel);
  1641. if (cancel?.Cancel == true)
  1642. {
  1643. return;
  1644. }
  1645. }
  1646. catch (Exception e)
  1647. {
  1648. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Error in UnloadWindow(): {0}\n{1}", e.Message, e.StackTrace));
  1649. }
  1650. CurrentPanel_Ticks = DateTime.MinValue;
  1651. CurrentPanel_Label = "";
  1652. CurrentPanel_Clicks = 0;
  1653. CurrentPanel_Keys = 0;
  1654. Title =
  1655. $"{CurrentPanel_Label} - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1656. if (CurrentTab != null)
  1657. {
  1658. var border = VisualUtils.EnumChildrenOfType(CurrentTab, typeof(Border)).LastOrDefault();
  1659. if (border != null)
  1660. {
  1661. ((Border)border).Background = new SolidColorBrush(Colors.Transparent);
  1662. ((Border)border).BorderBrush = new SolidColorBrush(Colors.Transparent);
  1663. }
  1664. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  1665. if (ReportsBar is not null)
  1666. {
  1667. ReportsBar.Items.Clear();
  1668. ReportsBar.Visibility = Visibility.Collapsed;
  1669. ReportsBar.IsLauncherVisible = false;
  1670. }
  1671. var ActionBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  1672. if (ActionBar is not null)
  1673. {
  1674. ActionBar.IsLauncherVisible = false;
  1675. foreach (var module in CurrentModules)
  1676. ActionBar.Items.Remove(module);
  1677. }
  1678. }
  1679. }
  1680. CurrentTab = null;
  1681. CurrentButton = null;
  1682. CurrentPanel = null;
  1683. ContentControl.Content = null;
  1684. }
  1685. private void SecondaryWindow_Click(object sender, RoutedEventArgs e)
  1686. {
  1687. if (CurrentPanel == null)
  1688. return;
  1689. var id = Guid.NewGuid();
  1690. var window = new Tuple<string, string, double, double, double, double>(
  1691. CurrentPanel.GetType().EntityName(),
  1692. CurrentPanel_Label,
  1693. Left + 100,
  1694. Top + 100,
  1695. Width - 200,
  1696. Height - 200
  1697. );
  1698. App.DatabaseSettings.SecondaryWindows[id] = window;
  1699. new LocalConfiguration<DatabaseSettings>(App.Profile).Save(App.DatabaseSettings);
  1700. _secondarywindows[id] = new SecondaryWindow(
  1701. id,
  1702. window.Item1,
  1703. window.Item2,
  1704. window.Item3,
  1705. window.Item4,
  1706. window.Item5,
  1707. window.Item6
  1708. );
  1709. _secondarywindows[id].Show();
  1710. }
  1711. private void RibbonWindow_Activated(object sender, EventArgs e)
  1712. {
  1713. }
  1714. private void RegisterModules(IProgress<string> progress)
  1715. {
  1716. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1717. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1718. foreach (var item in bar.Items)
  1719. Dispatcher.Invoke(() =>
  1720. {
  1721. var button = item as RibbonButton;
  1722. if (button != null && button.Label != "Refresh")
  1723. if (bar.Header.Equals("Actions"))
  1724. Modules.Register(button.Label);
  1725. });
  1726. //foreach (var item in _ribbon.BackStage.Items)
  1727. //{
  1728. // BackStageCommandButton button = item as BackStageCommandButton;
  1729. // if ((button != null) && (button.Header != "Log Out") && (button.Header != "Exit"))
  1730. // SecurityFactory.Register("System", button.Header, String.Format("System: Configure {0}", button.Header));
  1731. //}
  1732. }
  1733. private void SetVisibility(FrameworkElement button, bool visible)
  1734. {
  1735. var vResult = true;
  1736. var eResult = ClientFactory.UserGuid != Guid.Empty && visible;
  1737. button.Visibility = vResult && eResult ? Visibility.Visible : Visibility.Collapsed;
  1738. if (button is RibbonButton rb)
  1739. {
  1740. CustomModules.Register(rb.Label);
  1741. rb.IsEnabled = !OutstandingDailyReports(false);
  1742. }
  1743. }
  1744. private void SetVisibleIfEither(FrameworkElement separator, FrameworkElement[] left, FrameworkElement[] right)
  1745. {
  1746. var bLeft = false;
  1747. foreach (var button in left)
  1748. bLeft = bLeft || button.Visibility == Visibility.Visible;
  1749. var bRight = false;
  1750. foreach (var button in right)
  1751. bRight = bRight || button.Visibility == Visibility.Visible;
  1752. separator.Visibility = bLeft && bRight ? Visibility.Visible : Visibility.Collapsed;
  1753. }
  1754. private void SetVisibleIfAny(FrameworkElement separator, params FrameworkElement[] buttons)
  1755. {
  1756. var bVisible = false;
  1757. foreach (var button in buttons)
  1758. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1759. separator.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1760. }
  1761. private void SetTabVisibleIfAny(Fluent.RibbonTabItem tab, params FrameworkElement[] buttons)
  1762. {
  1763. var bVisible = false;
  1764. foreach (var button in buttons)
  1765. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1766. bVisible = bVisible || (SetupActions.GetValueOrDefault(tab)?.Count(x => x is SetupActionItem) ?? 0) > 3;
  1767. tab.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1768. }
  1769. private Fluent.RibbonGroupBox? FindRibbonBar(Fluent.RibbonTabItem tab, Func<Fluent.RibbonGroupBox, bool> predicate)
  1770. {
  1771. foreach (var group in tab.Groups)
  1772. {
  1773. if (group != null)
  1774. if (predicate.Invoke(group))
  1775. return group;
  1776. }
  1777. return null;
  1778. }
  1779. //private Style tabselected = null;
  1780. //private Style tabunselected = null;
  1781. //private Style Getstyle(bool selected)
  1782. //{
  1783. // if (tabunselected == null)
  1784. // {
  1785. // tabunselected = new Style(typeof(TabButton));
  1786. // Setter st1 = new Setter(TabButton.BackgroundProperty, new SolidColorBrush(Colors.Transparent));
  1787. // tabunselected.Setters.Add(st1);
  1788. // }
  1789. // if (tabselected == null)
  1790. // {
  1791. // tabselected = new Style(typeof(TabButton));
  1792. // Setter st1 = new Setter(TabButton.BackgroundProperty, new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0x9E, 0xDA, 0x11)));
  1793. // tabselected.Setters.Add(st1);
  1794. // }
  1795. // return selected ? tabselected : tabunselected;
  1796. //}
  1797. #region Button Event Handlers
  1798. private void DataEntry_Click(object sender, RoutedEventArgs e)
  1799. {
  1800. LoadWindow<DataEntryPanel>((Fluent.Button)sender);
  1801. }
  1802. private void Console_Click(object sender, RoutedEventArgs a)
  1803. {
  1804. if (_console is null)
  1805. {
  1806. _console = new Console();
  1807. _console.Closing += (o, args) => _console = null;
  1808. }
  1809. _console.Show();
  1810. }
  1811. private void Quotes_Checked(object sender, RoutedEventArgs e)
  1812. {
  1813. LoadWindow<QuotePanel>((Fluent.Button)sender);
  1814. }
  1815. private void Jobs_Checked(object sender, RoutedEventArgs e)
  1816. {
  1817. LoadWindow<JobPanel>((Fluent.Button)sender);
  1818. }
  1819. private void ProjectPlanner_Checked(object sender, RoutedEventArgs e)
  1820. {
  1821. LoadWindow<JobResourcePlannerPanel>((Fluent.Button)sender);
  1822. }
  1823. private void DesignManagement_Checked(object sender, RoutedEventArgs e)
  1824. {
  1825. LoadWindow<StagingPanel>((Fluent.Button)sender);
  1826. }
  1827. private void Service_Checked(object sender, RoutedEventArgs e)
  1828. {
  1829. MessageBox.Show("Not Implemented");
  1830. //LoadWindow<JobPanel>((RibbonButton)sender);
  1831. }
  1832. private void Tasks_Checked(object sender, RoutedEventArgs e)
  1833. {
  1834. //LoadWindow<KanbanPanel>((RibbonButton)sender);
  1835. LoadWindow<TaskPanel>((Fluent.Button)sender);
  1836. }
  1837. private void ManufacturingMenu_Checked(object sender, RoutedEventArgs e)
  1838. {
  1839. LoadWindow<ManufacturingPanel>((Fluent.Button)sender);
  1840. }
  1841. // private void Schedule_Checked(object sender, RoutedEventArgs e)
  1842. // {
  1843. // LoadWindow<SchedulePanel>((RibbonButton)sender);
  1844. // }
  1845. private void FactoryFloorButton_Click(object sender, RoutedEventArgs e)
  1846. {
  1847. LoadWindow<FactoryPanel>((Fluent.Button)sender);
  1848. }
  1849. private void DispatchMenu_Checked(object sender, RoutedEventArgs e)
  1850. {
  1851. LoadWindow<DispatchPanel>((Fluent.Button)sender);
  1852. }
  1853. private void ReadyToGoMenu_Checked(object sender, RoutedEventArgs e)
  1854. {
  1855. LoadWindow<ReadyToGoPanel>((Fluent.Button)sender);
  1856. }
  1857. private void Equipment_Checked(object sender, RoutedEventArgs e)
  1858. {
  1859. LoadWindow<EquipmentPanel>((Fluent.Button)sender);
  1860. }
  1861. private void Requisitions_Checked(object sender, RoutedEventArgs e)
  1862. {
  1863. LoadWindow<RequisitionPanel>((Fluent.Button)sender);
  1864. }
  1865. //private void Purchases_Checked(object sender, RoutedEventArgs e)
  1866. //{
  1867. // LoadWindow(PurchasesMenu, new PurchasesPanel());
  1868. //}
  1869. private void Timesheets_Checked(object sender, RoutedEventArgs e)
  1870. {
  1871. LoadWindow<TimesheetPanel>((Fluent.Button)sender);
  1872. }
  1873. private void Attendance_Checked(object sender, RoutedEventArgs e)
  1874. {
  1875. LoadWindow<AttendancePanel>((Fluent.Button)sender);
  1876. }
  1877. private void Maps_Checked(object sender, RoutedEventArgs e)
  1878. {
  1879. LoadWindow<MapsPanel>((Fluent.Button)sender);
  1880. }
  1881. private void FactorySetup_Click()
  1882. {
  1883. var list = new MasterList(typeof(ManufacturingFactory));
  1884. list.ShowDialog();
  1885. }
  1886. private void TemplateSetup_Click()
  1887. {
  1888. var list = new MasterList(typeof(ManufacturingTemplate), "Factory.Name", null, true);
  1889. list.ShowDialog();
  1890. }
  1891. private void RefreshMenu_Click(object sender, RoutedEventArgs e)
  1892. {
  1893. if (CurrentPanel != null)
  1894. CurrentPanel.Refresh();
  1895. }
  1896. private void MenuItem_Click(object sender, RoutedEventArgs e)
  1897. {
  1898. }
  1899. private void QuoteStatusButton_Click()
  1900. {
  1901. var list = new MasterList(typeof(QuoteStatus));
  1902. list.ShowDialog();
  1903. }
  1904. private void QuoteDesignSectionButton_Click()
  1905. {
  1906. var list = new MasterList(typeof(QuoteDesignSection));
  1907. list.ShowDialog();
  1908. }
  1909. private void JobStatusButton_Click()
  1910. {
  1911. var list = new MasterList(typeof(JobStatus));
  1912. list.ShowDialog();
  1913. }
  1914. private void FinancialStatusButton_Click()
  1915. {
  1916. var list = new MasterList(typeof(JobFinancialStatus));
  1917. list.ShowDialog();
  1918. }
  1919. private void DrawingTemplatesButton_Click()
  1920. {
  1921. var list = new MasterList(typeof(DrawingTemplate));
  1922. list.ShowDialog();
  1923. }
  1924. private void ViewWaterMarks()
  1925. {
  1926. var list = new MasterList(typeof(StagingManufacturingWatermark));
  1927. list.ShowDialog();
  1928. }
  1929. private void ViewSetoutGroups()
  1930. {
  1931. var list = new MasterList(typeof(SetoutGroup));
  1932. list.ShowDialog();
  1933. }
  1934. private void RolesSetup_Click()
  1935. {
  1936. var list = new MasterList(typeof(Role));
  1937. list.ShowDialog();
  1938. }
  1939. private void GroupsSetup_Click()
  1940. {
  1941. var list = new MasterList(typeof(EmployeeGroup));
  1942. list.ShowDialog();
  1943. }
  1944. private void PositionsSetup_Click()
  1945. {
  1946. var list = new MasterList(typeof(EmployeePosition));
  1947. list.ShowDialog();
  1948. }
  1949. private void UserSetup_Click(object sender, RoutedEventArgs e)
  1950. {
  1951. LoadWindow<UserPanel>((Fluent.Button)sender);
  1952. //MasterList list = new MasterList(typeof(User));
  1953. //list.ShowDialog();
  1954. }
  1955. private void Employees_Click(object sender, RoutedEventArgs e)
  1956. {
  1957. LoadWindow<EmployeePanel>((Fluent.Button)sender);
  1958. //MasterList list = new MasterList(typeof(Employee));
  1959. //list.ShowDialog();
  1960. }
  1961. private void Customers_Click(object sender, RoutedEventArgs e)
  1962. {
  1963. var list = new MasterList(typeof(Customer));
  1964. list.ShowDialog();
  1965. }
  1966. private void Stickers_Click()
  1967. {
  1968. var list = new MasterList(typeof(WebSticker));
  1969. list.ShowDialog();
  1970. }
  1971. private void Trackers_Click(object sender, RoutedEventArgs e)
  1972. {
  1973. LoadWindow<GPSTrackers>((Fluent.Button)sender);
  1974. //MasterList list = new MasterList(typeof(GPSTracker));
  1975. //list.ShowDialog();
  1976. }
  1977. private void TrackerTypes_Click()
  1978. {
  1979. var list = new MasterList(typeof(GPSTrackerType));
  1980. list.ShowDialog();
  1981. }
  1982. private void DigitalKeys_Click()
  1983. {
  1984. var list = new MasterList(typeof(DigitalKey));
  1985. list.ShowDialog();
  1986. }
  1987. private void SupplierMenu_Click(object sender, RoutedEventArgs e)
  1988. {
  1989. var list = new MasterList(typeof(Supplier));
  1990. list.ShowDialog();
  1991. }
  1992. private void DeliveredOnSiteMenu_Checked(object sender, RoutedEventArgs e)
  1993. {
  1994. LoadWindow<DeliveredOnSitePanel>((Fluent.Button)sender);
  1995. }
  1996. private void DatabaseScripts_Click(object sender, RoutedEventArgs e)
  1997. {
  1998. var list = new MasterList(typeof(Script), "Section", null, true);
  1999. list.ShowDialog();
  2000. }
  2001. private void WebTemplates_Click(object sender, RoutedEventArgs e)
  2002. {
  2003. MasterList list = new MasterList(typeof(WebTemplate), null, null, true);
  2004. list.ShowDialog();
  2005. }
  2006. private void ActivityMenu_Click()
  2007. {
  2008. var list = new MasterList(typeof(Activity));
  2009. list.ShowDialog();
  2010. }
  2011. private void QualificationMenu_Click()
  2012. {
  2013. var list = new MasterList(typeof(Qualification));
  2014. list.ShowDialog();
  2015. }
  2016. private void RosterMenu_Click()
  2017. {
  2018. var list = new MasterList(typeof(EmployeeRoster));
  2019. list.ShowDialog();
  2020. }
  2021. private void Reports_LauncherClick(object sender, RoutedEventArgs e)
  2022. {
  2023. }
  2024. private void Products_Checked(object sender, RoutedEventArgs e)
  2025. {
  2026. LoadWindow<ProductsPanel>((Fluent.Button)sender);
  2027. }
  2028. private void StockLocations_Checked(object sender, RoutedEventArgs e)
  2029. {
  2030. LoadWindow<StockLocationPanel>((Fluent.Button)sender);
  2031. }
  2032. private void StockMovements_Checked(object sender, RoutedEventArgs e)
  2033. {
  2034. LoadWindow<StockMovementPanel>((Fluent.Button)sender);
  2035. }
  2036. private void StockSummaryButton_Clicked(object sender, RoutedEventArgs e)
  2037. {
  2038. LoadWindow<StockSummaryPanel>((Fluent.Button)sender);
  2039. }
  2040. private void ReservationManagementButton_Clicked(object sender, RoutedEventArgs e)
  2041. {
  2042. LoadWindow<JobRequisitionsPanel>((Fluent.Button)sender);
  2043. }
  2044. private void KitsMasterList_Click(object sender, RoutedEventArgs e)
  2045. {
  2046. LoadWindow<KitPanel>((Fluent.Button)sender);
  2047. }
  2048. private void CostSheetsMasterList_Click(object sender, RoutedEventArgs e)
  2049. {
  2050. LoadWindow<CostSheetPanel>((Fluent.Button)sender);
  2051. }
  2052. private void LeaveRequestsButton_Click(object sender, RoutedEventArgs e)
  2053. {
  2054. LoadWindow<LeaveRequestPanel>((Fluent.Button)sender);
  2055. }
  2056. private void MeetingsButton_Click(object sender, RoutedEventArgs e)
  2057. {
  2058. LoadWindow<MeetingPanel>((Fluent.Button)sender);
  2059. }
  2060. private void OrgChartButton_Click(object sender, RoutedEventArgs e)
  2061. {
  2062. LoadWindow<OrgChartPanel>((Fluent.Button)sender);
  2063. }
  2064. private void EquipmentGroupList_Click()
  2065. {
  2066. var list = new MasterList(typeof(EquipmentGroup));
  2067. list.ShowDialog();
  2068. }
  2069. private void KitConditionList_Click()
  2070. {
  2071. var list = new MasterList(typeof(KitCondition));
  2072. list.ShowDialog();
  2073. }
  2074. //private void KitGroupList_Click(object sender, RoutedEventArgs e)
  2075. //{
  2076. // MasterList list = new MasterList(typeof(KitGroup));
  2077. // list.ShowDialog();
  2078. //}
  2079. private void KitFormulaeList_Click()
  2080. {
  2081. var list = new MasterList(typeof(KitFormula));
  2082. list.ShowDialog();
  2083. }
  2084. private void CustomFields_Click(object sender, RoutedEventArgs e)
  2085. {
  2086. var list = new MasterList(typeof(CustomProperty), "Class", null, true);
  2087. list.ShowDialog();
  2088. }
  2089. private void CostSheetTypeList_Click()
  2090. {
  2091. var list = new MasterList(typeof(CostSheetType));
  2092. list.ShowDialog();
  2093. }
  2094. private void CostSheetBrandList_Click()
  2095. {
  2096. var list = new MasterList(typeof(CostSheetBrand));
  2097. list.ShowDialog();
  2098. }
  2099. private void CostSheetSectionList_Click()
  2100. {
  2101. var list = new MasterList(typeof(CostSheetSection));
  2102. list.ShowDialog();
  2103. }
  2104. private void ProductDimensionUnitsList_Click()
  2105. {
  2106. var list = new MasterList(typeof(ProductDimensionUnit));
  2107. list.ShowDialog();
  2108. }
  2109. private void SupplierList_Click(object sender, RoutedEventArgs e)
  2110. {
  2111. LoadWindow<SupplierPanel>((Fluent.Button)sender);
  2112. }
  2113. private void CustomerList_Click(object sender, RoutedEventArgs e)
  2114. {
  2115. LoadWindow<CustomerPanel>((Fluent.Button)sender);
  2116. }
  2117. private void ProductGroupsList_Click()
  2118. {
  2119. var list = new MasterList(typeof(ProductGroup));
  2120. list.ShowDialog();
  2121. }
  2122. private void ProductStylesList_Click()
  2123. {
  2124. var list = new MasterList(typeof(ProductStyle));
  2125. list.ShowDialog();
  2126. }
  2127. private void StockAreasList_Click()
  2128. {
  2129. var list = new MasterList(typeof(StockArea));
  2130. list.ShowDialog();
  2131. }
  2132. private void CostCentresList_Click()
  2133. {
  2134. var list = new MasterList(typeof(CostCentre));
  2135. list.ShowDialog();
  2136. }
  2137. private void GLCodesList_Click()
  2138. {
  2139. var list = new MasterList(typeof(GLCode));
  2140. list.ShowDialog();
  2141. }
  2142. private void CalendarButton_Click(object sender, RoutedEventArgs e)
  2143. {
  2144. LoadWindow<CalendarPanel>((Fluent.Button)sender);
  2145. }
  2146. private void EmployeePlannerButton_Click(object sender, RoutedEventArgs e)
  2147. {
  2148. LoadWindow<EmployeeResourcePlannerPanel>((Fluent.Button)sender);
  2149. }
  2150. private void InvoiceList_Click(object sender, RoutedEventArgs e)
  2151. {
  2152. LoadWindow<InvoicePanel>((Fluent.Button)sender);
  2153. }
  2154. private void ReceiptList_Click(object sender, RoutedEventArgs e)
  2155. {
  2156. LoadWindow<CustomerReceipts>((Fluent.Button)sender);
  2157. }
  2158. private void PaymentsList_Click(object sender, RoutedEventArgs e)
  2159. {
  2160. LoadWindow<SupplierPayments>((Fluent.Button)sender);
  2161. }
  2162. private void BillsList_Click(object sender, RoutedEventArgs e)
  2163. {
  2164. LoadWindow<SupplierBillPanel>((Fluent.Button)sender);
  2165. }
  2166. private void PurchasesList_Click(object sender, RoutedEventArgs e)
  2167. {
  2168. LoadWindow<SupplierPurchaseOrderPanel>((Fluent.Button)sender);
  2169. }
  2170. private void ReceiptTypeList_Click()
  2171. {
  2172. var list = new MasterList(typeof(ReceiptType));
  2173. list.ShowDialog();
  2174. }
  2175. private void PaymentTypeList_Click()
  2176. {
  2177. var list = new MasterList(typeof(PaymentType));
  2178. list.ShowDialog();
  2179. }
  2180. private void TaxCodeList_Click()
  2181. {
  2182. var list = new MasterList(typeof(TaxCode));
  2183. list.ShowDialog();
  2184. }
  2185. private void ContactTypeList_Click()
  2186. {
  2187. var list = new MasterList(typeof(ContactType));
  2188. list.ShowDialog();
  2189. }
  2190. private void EmployeeTeamsButton_Click()
  2191. {
  2192. var list = new MasterList(typeof(Team));
  2193. list.ShowDialog();
  2194. }
  2195. // private void RostersButton_Click()
  2196. // {
  2197. // var list = new MasterList(typeof(Roster));
  2198. // list.ShowDialog();
  2199. // }
  2200. private void OvertimeRulesButton_Click()
  2201. {
  2202. var list = new MasterList(typeof(OvertimeRule));
  2203. list.ShowDialog();
  2204. }
  2205. private void OvertimeButton_Click()
  2206. {
  2207. var list = new MasterList(typeof(Overtime));
  2208. list.ShowDialog();
  2209. }
  2210. private void StandardLeaveButton_Click()
  2211. {
  2212. var list = new MasterList(typeof(StandardLeave));
  2213. list.ShowDialog();
  2214. }
  2215. private void SecurityGroupsButton_Click()
  2216. {
  2217. var list = new MasterList(typeof(SecurityGroup));
  2218. list.ShowDialog();
  2219. Security.Reset();
  2220. }
  2221. private void ImportDatabase_Click(object sender, RoutedEventArgs e)
  2222. {
  2223. Utility.DuplicateDatabase();
  2224. }
  2225. private void DeliveriesButton_Click(object sender, RoutedEventArgs e)
  2226. {
  2227. LoadWindow<DeliveryPanel>((Fluent.Button)sender);
  2228. }
  2229. private void TaskTypesButton_OnClick(object sender, RoutedEventArgs e)
  2230. {
  2231. var list = new MasterList(typeof(KanbanType));
  2232. list.ShowDialog();
  2233. }
  2234. private void TrolleySetup_Click()
  2235. {
  2236. var list = new MasterList(typeof(ManufacturingTrolley));
  2237. list.ShowDialog();
  2238. }
  2239. private void LostTimeSetup_Click()
  2240. {
  2241. var list = new MasterList(typeof(ManufacturingLostTime));
  2242. list.ShowDialog();
  2243. }
  2244. private void FactoryAllocationButton_Click(object sender, RoutedEventArgs e)
  2245. {
  2246. LoadWindow<ManufacturingAllocationPanel>((Fluent.Button)sender);
  2247. }
  2248. private void Messages_Checked(object sender, RoutedEventArgs e)
  2249. {
  2250. LoadWindow<NotificationPanel>((Fluent.Button)sender);
  2251. }
  2252. private void DatabaseActivityButton_Click(object sender, RoutedEventArgs e)
  2253. {
  2254. LoadWindow<DatabaseActivityDashboard>((Fluent.Button)sender);
  2255. }
  2256. private void FactoryProductivityButton_Click(object sender, RoutedEventArgs e)
  2257. {
  2258. LoadWindow<FactoryProductivityDashboard>((Fluent.Button)sender);
  2259. }
  2260. private void TemplateAnalysisButton_Click(object sender, RoutedEventArgs e)
  2261. {
  2262. LoadWindow<ManufacturingTemplateAnalysis>((Fluent.Button)sender);
  2263. }
  2264. private void FactoryAnalysisButton_Click(object sender, RoutedEventArgs e)
  2265. {
  2266. LoadWindow<FactoryFloorAnalysis>((Fluent.Button)sender);
  2267. }
  2268. private void UserActivityButton_Click(object sender, RoutedEventArgs e)
  2269. {
  2270. LoadWindow<UserActivity>((Fluent.Button)sender);
  2271. }
  2272. private void DigitalFormsButton_Click(object sender, RoutedEventArgs e)
  2273. {
  2274. LoadWindow<QADashboard>((Fluent.Button)sender);
  2275. }
  2276. private void QuickStatus_Click(object sender, RoutedEventArgs e)
  2277. {
  2278. LoadWindow<WidgetDashboard>((Fluent.Button)sender);
  2279. }
  2280. private void ConsignmentButton_Click(object sender, RoutedEventArgs e)
  2281. {
  2282. LoadWindow<ConsignmentsPanel>((Fluent.Button)sender);
  2283. }
  2284. private void ConsignmentTypesButton_Click()
  2285. {
  2286. var list = new MasterList(typeof(ConsignmentType));
  2287. list.ShowDialog();
  2288. }
  2289. private void PurchaseOrderCategoriesButton_Click()
  2290. {
  2291. var list = new MasterList(typeof(PurchaseOrderCategory));
  2292. list.ShowDialog();
  2293. }
  2294. private void DeliveryTypesButton_Click()
  2295. {
  2296. var list = new MasterList(typeof(DeliveryType));
  2297. list.ShowDialog();
  2298. }
  2299. private void ConfigureModules_Click(object sender, RoutedEventArgs e)
  2300. {
  2301. var window = new ModuleConfigurationWindow(DbFactory.Provider.URL);
  2302. if (window.ShowDialog() == true)
  2303. MessageBox.Show("These changes will be applied when the database is restarted!");
  2304. }
  2305. //private void NotificationsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
  2306. //{
  2307. // if (NotificationsList.SelectedIndex < 0)
  2308. // return;
  2309. // var editors = NotificationsList.FindVisualChildren<InABox.DynamicGrid.ExtendedRichTextEditor>().ToArray();
  2310. // var selected = editors[NotificationsList.SelectedIndex];
  2311. // selected.Text = (String)selected.Tag; //NotificationsList.SelectedIndex.ToString();
  2312. //}
  2313. //private void ViewNotification_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
  2314. //{
  2315. // Notification notification = (sender as Label).Tag as Notification;
  2316. // NotificationDetails details = new NotificationDetails(notification);
  2317. // details.ShowDialog();
  2318. // ReloadNotifications();
  2319. //}
  2320. private void DailyReport_Checked(object sender, RoutedEventArgs e)
  2321. {
  2322. LoadWindow<DailyReport>((Fluent.Button)sender);
  2323. }
  2324. private void Library_Click(object sender, RoutedEventArgs e)
  2325. {
  2326. Process.Start(
  2327. new ProcessStartInfo
  2328. {
  2329. FileName = App.DatabaseSettings.LibraryLocation,
  2330. UseShellExecute = true,
  2331. Verb = "open"
  2332. }
  2333. );
  2334. }
  2335. private void SendNotificationClick(object sender, RoutedEventArgs e)
  2336. {
  2337. var form = new NotificationForm { Description = "" };
  2338. if (form.ShowDialog() == true)
  2339. ReloadNotifications();
  2340. }
  2341. private void CompanyInformation_Click(object sender, RoutedEventArgs e)
  2342. {
  2343. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  2344. if (info == null)
  2345. info = new CompanyInformation();
  2346. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  2347. }
  2348. private void StockWarehouseList_Click()
  2349. {
  2350. var list = new MasterList(typeof(StockWarehouse));
  2351. list.ShowDialog();
  2352. }
  2353. private void Dashboards_Checked(object sender, RoutedEventArgs e)
  2354. {
  2355. LoadWindow<UtilityDashboard>((Fluent.Button)sender);
  2356. }
  2357. private void QuoteDiagramSymbols_Checked()
  2358. {
  2359. var list = new MasterList(typeof(QuoteDiagramSymbol), "Section.Name");
  2360. list.ShowDialog();
  2361. QuoteDiagramSymbolCache.Refresh();
  2362. }
  2363. private void QuoteDiagramSymbolTypes_Checked()
  2364. {
  2365. var list = new MasterList(typeof(QuoteDiagramSymbolSection));
  2366. list.ShowDialog();
  2367. QuoteDiagramSymbolCache.Refresh();
  2368. }
  2369. private void QuoteTakeOffUnits_Click()
  2370. {
  2371. var list = new MasterList(typeof(QuoteTakeOffUnit));
  2372. list.ShowDialog();
  2373. }
  2374. private void JobDocumentMileStoneButton_OnClick()
  2375. {
  2376. var list = new MasterList(typeof(JobDocumentSetMileStoneType));
  2377. list.ShowDialog();
  2378. }
  2379. // private void JobDocumentTagButton_OnClick()
  2380. // {
  2381. // var list = new MasterList(typeof(JobDocumentSetTag));
  2382. // list.ShowDialog();
  2383. // }
  2384. private void Setup_Click(object sender, RoutedEventArgs e)
  2385. {
  2386. var tab = _ribbon.SelectedTabItem;
  2387. if (tab is null)
  2388. return;
  2389. var items = new List<ISetupActionItem>();
  2390. if (SetupActions.TryGetValue(tab, out var actions))
  2391. {
  2392. foreach (var action in actions)
  2393. {
  2394. items.Add(action);
  2395. }
  2396. }
  2397. if (PanelSetupActions.Any())
  2398. {
  2399. AddSetupSeparator(items);
  2400. foreach (var action in PanelSetupActions)
  2401. {
  2402. items.Add(action);
  2403. }
  2404. }
  2405. items = items.Where(x => x is not SetupActionItem setup || setup.IsVisible()).ToList();
  2406. var menu = new ContextMenu();
  2407. for (var i = 0; i < items.Count; ++i)
  2408. {
  2409. var item = items[i];
  2410. if (item is SetupActionItem setupAction)
  2411. {
  2412. menu.AddItem(setupAction.Name, setupAction.Image, setupAction.Action);
  2413. }
  2414. else if (item is SetupSeparator && i > 0 && i < items.Count - 1)
  2415. {
  2416. var last = items[i - 1];
  2417. if (last is not SetupSeparator)
  2418. menu.AddSeparator();
  2419. }
  2420. }
  2421. if (CurrentPanel?.GetType().HasInterface(typeof(IPropertiesPanel<>)) == true && Security.IsAllowed<CanConfigurePanels>())
  2422. {
  2423. menu.AddItem("Configure Panel", PRSDesktop.Resources.edit, ConfigurePanel_Click);
  2424. }
  2425. if (menu.Items.Count == 0)
  2426. {
  2427. menu.AddItem("No Items", null, null, false);
  2428. }
  2429. menu.IsOpen = true;
  2430. }
  2431. private void InitializePanelProperties(IBasePanel panel)
  2432. {
  2433. var propertiesInterface = panel.GetType().GetInterfaceDefinition(typeof(IPropertiesPanel<>));
  2434. if (propertiesInterface is not null)
  2435. {
  2436. var propertiesType = propertiesInterface.GenericTypeArguments[0];
  2437. var method = typeof(MainWindow)
  2438. .GetMethod(nameof(InitializePanelPropertiesGeneric), BindingFlags.NonPublic | BindingFlags.Instance)
  2439. ?.MakeGenericMethod(panel.GetType(), propertiesType)
  2440. .Invoke(this, new object?[] { panel });
  2441. }
  2442. }
  2443. private void InitializePanelPropertiesGeneric<TPanel, TProperties>(TPanel panel)
  2444. where TPanel : IPropertiesPanel<TProperties>
  2445. where TProperties : BaseObject, IGlobalConfigurationSettings, new()
  2446. {
  2447. panel.Properties = LoadPanelProperties<TPanel, TProperties>();
  2448. }
  2449. private TProperties LoadPanelProperties<TPanel, TProperties>()
  2450. where TPanel : IPropertiesPanel<TProperties>
  2451. where TProperties : BaseObject, IGlobalConfigurationSettings, new()
  2452. {
  2453. var config = new GlobalConfiguration<TProperties>();
  2454. return config.Load();
  2455. }
  2456. private void SavePanelProperties<TPanel, TProperties>(TProperties properties)
  2457. where TPanel : IPropertiesPanel<TProperties>
  2458. where TProperties : BaseObject, IGlobalConfigurationSettings, new()
  2459. {
  2460. var config = new GlobalConfiguration<TProperties>();
  2461. config.Save(properties);
  2462. }
  2463. private void EditPanelProperties<TPanel, TProperties>()
  2464. where TPanel : IPropertiesPanel<TProperties>
  2465. where TProperties : BaseObject, IGlobalConfigurationSettings, new()
  2466. {
  2467. var properties = LoadPanelProperties<TPanel, TProperties>();
  2468. var editor = new DynamicEditorForm(typeof(TProperties));
  2469. editor.Items = new BaseObject[] { properties };
  2470. if (editor.ShowDialog() == true)
  2471. {
  2472. SavePanelProperties<TPanel, TProperties>(properties);
  2473. }
  2474. }
  2475. private void ConfigurePanel_Click()
  2476. {
  2477. if (CurrentPanel is null) return;
  2478. var propertiesInterface = CurrentPanel.GetType().GetInterfaceDefinition(typeof(IPropertiesPanel<>))!;
  2479. var propertiesType = propertiesInterface.GenericTypeArguments[0];
  2480. var method = typeof(MainWindow)
  2481. .GetMethod(nameof(EditPanelProperties), BindingFlags.NonPublic | BindingFlags.Instance)
  2482. ?.MakeGenericMethod(CurrentPanel.GetType(), propertiesType)
  2483. .Invoke(this, Array.Empty<object?>());
  2484. }
  2485. private void StartForm<TEntityForm, TEntity, TEntityLink>(DigitalForm form)
  2486. where TEntityForm : EntityForm<TEntity, TEntityLink, TEntityForm>, new()
  2487. where TEntity : Entity, new()
  2488. where TEntityLink : EntityLink<TEntity>, new()
  2489. {
  2490. var entityForm = new TEntityForm();
  2491. entityForm.Form.ID = form.ID;
  2492. entityForm.Form.Description = form.Description;
  2493. var entity = DFUtils.NewEntity<TEntityForm, TEntity, TEntityLink>(form);
  2494. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel, entity))
  2495. {
  2496. dataModel.Update(null);
  2497. }
  2498. }
  2499. private void Forms_Click(object sender, RoutedEventArgs e)
  2500. {
  2501. var select = new MultiSelectDialog<DigitalForm>(
  2502. Filter<DigitalForm>.And(
  2503. LookupFactory.DefineFilter<KanbanForm, DigitalForm>(Array.Empty<KanbanForm>()),
  2504. new Filter<DigitalForm>(x => x.ID).InQuery(
  2505. new Filter<EmployeeDigitalForm>(x => x.Employee.ID).IsEqualTo(App.EmployeeID),
  2506. x => x.Form.ID)),
  2507. LookupFactory.DefineColumns<DigitalForm>()
  2508. .Add(x => x.Description),
  2509. false);
  2510. if (select.ShowDialog() == true)
  2511. {
  2512. var digitalForm = select.Data().Rows.FirstOrDefault()?.ToObject<DigitalForm>();
  2513. if (digitalForm is not null)
  2514. {
  2515. StartForm<KanbanForm, Kanban, KanbanLink>(digitalForm);
  2516. }
  2517. };
  2518. }
  2519. #endregion
  2520. private bool OutstandingDailyReports(bool refresh)
  2521. {
  2522. if (!Security.IsAllowed<CanViewDailyReports>() || Security.IsAllowed<BypassOutstandingDailyReports>())
  2523. return false;
  2524. if (refresh)
  2525. RefreshTimeSheets();
  2526. if (_timesheets == null)
  2527. return false;
  2528. return _timesheets.Rows.Any(r => r.Get<TimeSheet, DateTime>(c => c.Date).Date < DateTime.Today);
  2529. }
  2530. private void ShutDownTransport()
  2531. {
  2532. if (_transport != null)
  2533. {
  2534. _transport.OnClose -= TransportConnectionLost;
  2535. if (_transport.IsConnected())
  2536. _transport.Disconnect();
  2537. _transport = null;
  2538. }
  2539. }
  2540. private void Window_Unloaded(object sender, RoutedEventArgs e)
  2541. {
  2542. ShutDownTransport();
  2543. }
  2544. private void RibbonWindow_Closed(object sender, EventArgs e)
  2545. {
  2546. ShutDownTransport();
  2547. DisconnectRecorderNotes();
  2548. Application.Current.Shutdown();
  2549. }
  2550. //private bool _closingFromSystemMenu = false;
  2551. private void Window_Closing(object sender, CancelEventArgs e)
  2552. {
  2553. /*if (!_closingFromSystemMenu && !CoreUtils.GetVersion().Equals("???"))
  2554. {
  2555. WindowState = WindowState.Minimized;
  2556. e.Cancel = true;
  2557. return;
  2558. }*/
  2559. if (CurrentPanel != null)
  2560. {
  2561. CurrentPanel.Shutdown(e);
  2562. if (e.Cancel)
  2563. {
  2564. return;
  2565. }
  2566. }
  2567. CurrentPanel = null;
  2568. App.IsClosing = true;
  2569. FinalizeAutoTimesheet();
  2570. if (!CoreUtils.GetVersion().Equals("???"))
  2571. scheduler.Stop();
  2572. CurrentTab = null;
  2573. UpdateRibbonColors();
  2574. if (!CoreUtils.GetVersion().Equals("???"))
  2575. if (station.ID != Guid.Empty)
  2576. ExecuteLogout();
  2577. ShutDownTransport();
  2578. }
  2579. private void FinalizeAutoTimesheet()
  2580. {
  2581. if (Security.IsAllowed<AutoGenerateTimesheet>())
  2582. {
  2583. var check = new Client<TimeSheet>().Query(
  2584. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today).And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID).And(x => x.Finish)
  2585. .IsEqualTo(TimeSpan.Zero)
  2586. );
  2587. if (check.Rows.Any())
  2588. {
  2589. var ts = check.Rows.First().ToObject<TimeSheet>();
  2590. if (DateTime.Now.TimeOfDay < ts.Start.Add(new TimeSpan(0, 2, 0)))
  2591. {
  2592. new Client<TimeSheet>().Delete(ts, "Deleting Auto TimeSheet because TimeBench Bypass is enabled", (o, ex) => { });
  2593. }
  2594. else
  2595. {
  2596. ts.Finish = DateTime.Now.TimeOfDay;
  2597. new Client<TimeSheet>().Save(ts, "Clocking off Auto Timesheet because Timesheet Bypass is enabled", (o, ex) => { });
  2598. }
  2599. }
  2600. }
  2601. }
  2602. #region Notifications + Heartbeat
  2603. private void ReceiveNotification(Notification notification)
  2604. {
  2605. if (Security.CanView<Notification>())
  2606. {
  2607. Notifications.AddNotification(notification);
  2608. }
  2609. if (CurrentPanel is NotificationPanel panel)
  2610. {
  2611. panel.AddNotification(notification);
  2612. }
  2613. }
  2614. private void Notifications_Tick(object? sender, EventArgs e)
  2615. {
  2616. if (ClientFactory.UserGuid != Guid.Empty)
  2617. {
  2618. try
  2619. {
  2620. ReloadNotifications();
  2621. }
  2622. catch (Exception err)
  2623. {
  2624. Logger.Send(LogType.Error, ClientFactory.UserID,
  2625. string.Format("Exception in Notifications_Tick:ReloadNotifications() {0}\n{1}", err.Message, err.StackTrace));
  2626. }
  2627. Heartbeat(DateTime.Now - CurrentPanel_Ticks, false);
  2628. try
  2629. {
  2630. CheckIsLoggedOn();
  2631. }
  2632. catch (Exception err2)
  2633. {
  2634. Logger.Send(LogType.Error, ClientFactory.UserID,
  2635. string.Format("Exception in Notifications_Tick:CheckIsLoggedOn() {0}\n{1}", err2.Message, err2.StackTrace));
  2636. }
  2637. }
  2638. //else
  2639. //{
  2640. // Logger.Send(LogType.Information, ClientFactory.UserID, "Notifications_Tick: ClientFactory.UserGuid is empty");
  2641. //}
  2642. }
  2643. private void CheckIsLoggedOn()
  2644. {
  2645. if (CoreUtils.GetVersion().Equals("???"))
  2646. return;
  2647. var bLogout = false;
  2648. if (!Security.IsAllowed<CanBypassTimeBench>())
  2649. if (!IsClockedOn())
  2650. {
  2651. Logger.Send(LogType.Information, ClientFactory.UserID, "User is no longer clocked in!");
  2652. bLogout = true;
  2653. Dispatcher.Invoke(() => { Logout(); });
  2654. }
  2655. if (!bLogout)
  2656. new Client<Login>().Query(
  2657. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  2658. new Columns<Login>(x => x.StationID),
  2659. null,
  2660. (o, e) =>
  2661. {
  2662. if (e is RemoteException remote)
  2663. {
  2664. if (remote.Status == StatusCode.Unauthenticated)
  2665. {
  2666. Logger.Send(LogType.Information, ClientFactory.UserID, "User has been logged out");
  2667. Dispatcher.Invoke(() =>
  2668. {
  2669. Logout("You have been logged out due to inactivity");
  2670. });
  2671. }
  2672. else
  2673. {
  2674. Logger.Send(LogType.Information, ClientFactory.UserID, CoreUtils.FormatException(remote));
  2675. }
  2676. }
  2677. else if (e is not null)
  2678. {
  2679. Logger.Send(LogType.Information, ClientFactory.UserID, CoreUtils.FormatException(e));
  2680. }
  2681. else if (o is not null)
  2682. {
  2683. var row = o.Rows.FirstOrDefault();
  2684. if (row == null)
  2685. {
  2686. station.ID = Guid.Empty;
  2687. new Client<Login>().Save(station, "", (o1, e1) => { });
  2688. }
  2689. else if (!row.Get<Login, string>(c => c.StationID).Equals(station.StationID))
  2690. {
  2691. Logger.Send(LogType.Information, ClientFactory.UserID, "User logged in somewhere else!");
  2692. bLogout = true;
  2693. Dispatcher.Invoke(() => { Logout(); });
  2694. }
  2695. }
  2696. }
  2697. );
  2698. }
  2699. private void Heartbeat(TimeSpan time, bool closing)
  2700. {
  2701. //Task.Run(() =>
  2702. //{
  2703. try
  2704. {
  2705. bool IsClockedOn = this.IsClockedOn();
  2706. if (IsClockedOn)
  2707. {
  2708. if ((_kanbantrackingassignment != null) && (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay))
  2709. {
  2710. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2711. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2712. }
  2713. if (Security.IsAllowed<MonitorApplicationWindows>())
  2714. {
  2715. if (ActivityHistory == null)
  2716. ActivityHistory = new LocalConfiguration<DailyActivityHistory>().Load();
  2717. var appname = OpenWindowGetter.GetActiveWindowProcess();
  2718. var title = OpenWindowGetter.GetActiveWindowTitle();
  2719. ActivityHistory.Activities[DateTime.Now] = (!string.IsNullOrWhiteSpace(appname) ? appname.Trim() + " - " : "") + title;
  2720. new LocalConfiguration<DailyActivityHistory>().Save(ActivityHistory);
  2721. }
  2722. }
  2723. //Logger.Send(LogType.Information, "", string.Format("Heartbeat: {0:hh\\:mm}{1}", time, closing ? " (closing)" : ""));
  2724. if (!closing && time.TotalMinutes < 5)
  2725. return;
  2726. CurrentPanel_Ticks = DateTime.Now;
  2727. if (CurrentPanel != null)
  2728. {
  2729. //Logger.Send(LogType.Information, "", string.Format("Heartbeat: {0}", CurrentPanel_Label));
  2730. if (ClientFactory.IsSupported<ModuleTracking>())
  2731. {
  2732. var keys = CurrentPanel_Keys;
  2733. CurrentPanel_Keys = 0;
  2734. var clicks = CurrentPanel_Clicks;
  2735. CurrentPanel_Clicks = 0;
  2736. var tracking = new ModuleTracking
  2737. {
  2738. Date = DateTime.Today,
  2739. Module = CurrentPanel_Label,
  2740. Clicks = clicks,
  2741. Keys = keys,
  2742. ActiveTime = clicks + keys > 0 ? time : new TimeSpan(),
  2743. IdleTime = clicks + keys == 0 ? time : new TimeSpan()
  2744. };
  2745. tracking.User.ID = ClientFactory.UserGuid;
  2746. new Client<ModuleTracking>().Save(tracking, "", (mt, ex) => { });
  2747. }
  2748. CurrentPanel.Heartbeat(time);
  2749. }
  2750. }
  2751. catch (Exception err)
  2752. {
  2753. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Exception in Heartbeat: {0}\n{1}", err.Message, err.StackTrace));
  2754. }
  2755. //});
  2756. }
  2757. private void Notifications_Changed(object sender)
  2758. {
  2759. if (Notifications.IsActive)
  2760. {
  2761. Notifications.Visibility = Visibility.Visible;
  2762. DockingGrid.ColumnDefinitions[1].Width = new GridLength(4, GridUnitType.Pixel);
  2763. DockingGrid.ColumnDefinitions[2].Width = Equals(0.0, DockingGrid.ColumnDefinitions[2].Width.Value)
  2764. ? new GridLength(300, GridUnitType.Pixel)
  2765. : DockingGrid.ColumnDefinitions[2].Width;
  2766. }
  2767. else
  2768. {
  2769. Notifications.Visibility = Visibility.Collapsed;
  2770. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  2771. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  2772. }
  2773. }
  2774. private void ReloadNotifications()
  2775. {
  2776. if (Security.CanView<Notification>())
  2777. Notifications.Refresh();
  2778. if (!NotificationsWatchDog.IsEnabled)
  2779. {
  2780. //Logger.Send(LogType.Information, ClientFactory.UserID, "Enabling Heartbeat");
  2781. NotificationsWatchDog.IsEnabled = true;
  2782. }
  2783. }
  2784. #endregion
  2785. private void RibbonWindow_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  2786. {
  2787. if (CurrentPanel != null)
  2788. CurrentPanel_Clicks++;
  2789. }
  2790. private void RibbonWindow_PreviewKeyUp(object sender, KeyEventArgs e)
  2791. {
  2792. if (CurrentPanel != null)
  2793. CurrentPanel_Keys++;
  2794. }
  2795. #region Recording
  2796. //private IntPtr myHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  2797. //{
  2798. // switch (msg)
  2799. // {
  2800. // case 0x100:
  2801. // if (_subject != null)
  2802. // {
  2803. // _recorder.Stop();
  2804. // pausestarted = DateTime.Now;
  2805. // _subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2806. // }
  2807. // break;
  2808. // default:
  2809. // messages.TryGetValue(msg, out int value);
  2810. // messages[msg] = value + 1;
  2811. // break;
  2812. // }
  2813. // return IntPtr.Zero;
  2814. //}
  2815. private void RecordScreenButton_Click(object sender, RoutedEventArgs e)
  2816. {
  2817. ToggleRecording();
  2818. }
  2819. private bool ToggleRecording()
  2820. {
  2821. if (!Security.IsAllowed<CanRecordScreen>())
  2822. return true;
  2823. if (_recorder is null)
  2824. {
  2825. var windowInteropHelper = new WindowInteropHelper(this);
  2826. var screen = Screen.FromHandle(windowInteropHelper.Handle);
  2827. _screenleft = screen.WorkingArea.Left;
  2828. _screentop = screen.WorkingArea.Top;
  2829. _screenwidth = screen.WorkingArea.Width;
  2830. _screenheight = screen.WorkingArea.Height;
  2831. //VIDEO_WIDTH = _screenwidth;
  2832. //VIDEO_HEIGHT = _screenheight;
  2833. //SetupJPEGEncoder();
  2834. messages.Clear();
  2835. _bitmaps.Clear();
  2836. ConnectToRecordNotes();
  2837. StartAudio();
  2838. _recorder = new DispatcherTimer();
  2839. _recorder.Tick += (timer, args) => { TakeScreenShot(); };
  2840. _recorder.Interval = TimeSpan.FromMilliseconds(1000 / FRAMES_PER_SECOND);
  2841. _recorder.Start();
  2842. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsBitmapImage();
  2843. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2844. RecordingNotesButton.Visibility = Visibility.Visible;
  2845. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2846. AudioRecordingButton.Visibility = Visibility.Visible;
  2847. }
  2848. else
  2849. {
  2850. using (new WaitCursor())
  2851. {
  2852. StopRecording();
  2853. _recorder.Stop();
  2854. _recorder = null;
  2855. DisconnectRecorderNotes();
  2856. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  2857. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2858. RecordingNotesButton.Visibility = Visibility.Hidden;
  2859. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2860. AudioRecordingButton.Visibility = Visibility.Hidden;
  2861. var filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos),
  2862. string.Format("PRS Screen Recording {0:yyyy-MM-dd hh-mm-ss-ff}.avi", DateTime.Now));
  2863. ProcessScreenShots(filename);
  2864. }
  2865. }
  2866. return true;
  2867. }
  2868. private void StopRecording()
  2869. {
  2870. try
  2871. {
  2872. _audio?.StopRecording();
  2873. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2874. }
  2875. catch (Exception e)
  2876. {
  2877. Logger.Send(LogType.Error, "", string.Format("Unable to stop Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2878. }
  2879. }
  2880. private void StartAudio()
  2881. {
  2882. _audioMuted = true;
  2883. _audioStream = new MemoryStream();
  2884. _audio = new WaveIn
  2885. {
  2886. DeviceNumber = 0,
  2887. WaveFormat = new WaveFormat(44100, 16, 2)
  2888. };
  2889. _audio.DataAvailable += (o, e) =>
  2890. {
  2891. var buf = _audioMuted ? new byte[e.BytesRecorded] : e.Buffer;
  2892. _audioStream.Write(buf, 0, e.BytesRecorded);
  2893. };
  2894. try
  2895. {
  2896. _audio.StartRecording();
  2897. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2898. }
  2899. catch (Exception e)
  2900. {
  2901. Logger.Send(LogType.Error, "", string.Format("Unable to start Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2902. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2903. }
  2904. }
  2905. private bool ToggleRecordingAudio()
  2906. {
  2907. if (!Security.IsAllowed<CanRecordScreen>())
  2908. return true;
  2909. if (_recorder != null)
  2910. {
  2911. _audioMuted = !_audioMuted;
  2912. AudioRecordingStatus.Source = _audioMuted
  2913. ? PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage()
  2914. : PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2915. }
  2916. return true;
  2917. }
  2918. private void DisconnectRecorderNotes()
  2919. {
  2920. if (_client != null)
  2921. {
  2922. _client.WriteAsync("QUIT");
  2923. _client.StopAsync();
  2924. _client = null;
  2925. }
  2926. }
  2927. private void ConnectToRecordNotes()
  2928. {
  2929. var filename = Debugger.IsAttached
  2930. ? "c:\\development\\comal\\prsrecordingnotes\\bin\\debug\\prsrecordingnotes.exe"
  2931. : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "recordingnotes", "prsrecordingnotes.exe");
  2932. Logger.Send(LogType.Information, "", "Recording Notes: " + filename);
  2933. _recordingnotes = Process.Start(filename);
  2934. //PipeSecurity sec = new System.IO.Pipes.PipeSecurity();
  2935. //sec.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));
  2936. _client = new PipeServer<string>("PRSScreenRecorder"); //, sec);
  2937. _client.ClientConnected += (o, args) => args.Connection.WriteAsync("Connected to PRSScreenRecorder");
  2938. _client.MessageReceived += (o, args) =>
  2939. {
  2940. if (string.Equals(args.Message, "RESUME"))
  2941. Dispatcher.Invoke(() =>
  2942. {
  2943. _audio?.StartRecording();
  2944. totalpauses += DateTime.Now - pausestarted;
  2945. _recorder?.Start();
  2946. Activate();
  2947. Focus();
  2948. });
  2949. };
  2950. _client.StartAsync();
  2951. }
  2952. private bool ShowRecordingNotes()
  2953. {
  2954. if (_recorder != null)
  2955. {
  2956. _audio?.StopRecording();
  2957. _recorder.Stop();
  2958. pausestarted = DateTime.Now;
  2959. _client?.WriteAsync("EDIT");
  2960. //_subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2961. }
  2962. return true;
  2963. }
  2964. private void TakeScreenShot()
  2965. {
  2966. using (var bmp = new ScreenCapture().CaptureScreen(_screenleft, _screentop, _screenwidth, _screenheight))
  2967. {
  2968. var cursor = PointToScreen(Mouse.GetPosition(this));
  2969. using (var g = Graphics.FromImage(bmp))
  2970. {
  2971. var brush = new SolidBrush(System.Drawing.Color.FromArgb(128, 255, 255, 0));
  2972. g.FillEllipse(brush, new RectangleF((float)cursor.X - 25F, (float)cursor.Y - 25F, 50F, 50F));
  2973. var pen = new Pen(System.Drawing.Color.Black, 0.75F);
  2974. g.DrawLine(pen, (float)cursor.X - 10F, (float)cursor.Y, (float)cursor.X + 10F, (float)cursor.Y);
  2975. g.DrawLine(pen, (float)cursor.X, (float)cursor.Y - 10F, (float)cursor.X, (float)cursor.Y + 10F);
  2976. }
  2977. var key = DateTime.Now - totalpauses;
  2978. using (var reduced = ReduceBitmap(bmp, VIDEO_WIDTH, VIDEO_HEIGHT))
  2979. {
  2980. var ms = new MemoryStream();
  2981. reduced.Save(ms, ImageFormat.Png);
  2982. ms.Position = 0;
  2983. _bitmaps[key] = ms;
  2984. }
  2985. }
  2986. }
  2987. public Bitmap ReduceBitmap(Bitmap original, int reducedWidth, int reducedHeight)
  2988. {
  2989. var reduced = new Bitmap(reducedWidth, reducedHeight);
  2990. using (var dc = Graphics.FromImage(reduced))
  2991. {
  2992. // Figure out the ratio
  2993. var ratioX = (double)reducedWidth / original.Width;
  2994. var ratioY = (double)reducedHeight / original.Height;
  2995. // use whichever multiplier is smaller
  2996. var ratio = ratioX < ratioY ? ratioX : ratioY;
  2997. // now we can get the new height and width
  2998. var newHeight = Convert.ToInt32(original.Height * ratio);
  2999. var newWidth = Convert.ToInt32(original.Width * ratio);
  3000. // Now calculate the X,Y position of the upper-left corner
  3001. // (one of these will always be zero)
  3002. var posX = Convert.ToInt32((reducedWidth - original.Width * ratio) / 2);
  3003. var posY = Convert.ToInt32((reducedHeight - original.Height * ratio) / 2);
  3004. dc.InterpolationMode = InterpolationMode.HighQualityBicubic;
  3005. dc.Clear(System.Drawing.Color.Black); // white padding
  3006. //dc.DrawImage(original, posX, posY, newWidth, newHeight);
  3007. dc.DrawImage(original, new Rectangle(posX, posY, newWidth, newHeight), new Rectangle(0, 0, original.Width, original.Height),
  3008. GraphicsUnit.Pixel);
  3009. }
  3010. return reduced;
  3011. }
  3012. public static byte[] BitmapToByteArray(Bitmap bitmap, int width, int height)
  3013. {
  3014. // and buffer of appropriate size for storing its bits
  3015. var buffer = new byte[width * height * 4];
  3016. var pixelFormat = PixelFormat.Format32bppRgb;
  3017. // Now copy bits from bitmap to buffer
  3018. var bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);
  3019. //Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  3020. Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  3021. bitmap.UnlockBits(bits);
  3022. return buffer;
  3023. }
  3024. private void ProcessScreenShots(string filename)
  3025. {
  3026. if (!_bitmaps.Any() || _audioStream is null)
  3027. return;
  3028. Progress.Show("Saving Video");
  3029. var framRate = 10;
  3030. using (var writer = new AviWriter(filename))
  3031. {
  3032. writer.FramesPerSecond = framRate;
  3033. writer.EmitIndex1 = true;
  3034. _audioStream.Position = 0;
  3035. var audio = writer.AddAudioStream(2);
  3036. //audio.WriteBlock(_audioStream.GetBuffer(), 0, (int)_audioStream.Length);
  3037. //File.WriteAllBytes(Path.ChangeExtension(filename, "wav"), _audioStream.GetBuffer());
  3038. var audioByteRate = audio.BitsPerSample / 8 * audio.ChannelCount * audio.SamplesPerSecond;
  3039. var audioBlockSize = (int)(audioByteRate / writer.FramesPerSecond);
  3040. var audioBuffer = new byte[audioBlockSize];
  3041. _audioStream.Position = 0;
  3042. var encoder = new MJpegWpfVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT, 50);
  3043. var stream = writer.AddEncodingVideoStream(encoder, true, VIDEO_WIDTH, VIDEO_HEIGHT);
  3044. //var encoder = new SharpAvi.Codecs.UncompressedVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT);
  3045. //var stream = writer.AddEncodingVideoStream(encoder,true,VIDEO_WIDTH, VIDEO_HEIGHT);
  3046. //stream.Codec = CodecIds.Uncompressed;
  3047. //stream.BitsPerPixel = BitsPerPixel.Bpp16;
  3048. IEnumerable<DateTime> keys = _bitmaps.Keys.OrderBy(x => x);
  3049. var start = keys.First();
  3050. var end = keys.Last();
  3051. for (var cur = start; cur <= end; cur = cur + TimeSpan.FromMilliseconds(100))
  3052. {
  3053. Progress.SetMessage(string.Format("Processing ({0:F2} complete)",
  3054. (cur - start).TotalSeconds * 100.0F / (end - start).TotalSeconds));
  3055. var key = keys.LastOrDefault(x => x <= cur);
  3056. if (_bitmaps.ContainsKey(key))
  3057. {
  3058. var frame = (Image.FromStream(_bitmaps[key]) as Bitmap)!;
  3059. //frame.RotateFlip(RotateFlipType.RotateNoneFlipY);
  3060. var buf = BitmapToByteArray(frame, stream.Width, stream.Height);
  3061. stream.WriteFrame(true, buf, 0, buf.Length);
  3062. if (_audioStream.Position < _audioStream.Length)
  3063. {
  3064. var bytes = _audioStream.Read(audioBuffer, 0, audioBlockSize);
  3065. audio.WriteBlock(audioBuffer, 0, bytes);
  3066. }
  3067. }
  3068. }
  3069. writer.Close();
  3070. //foreach (var key in _bitmaps.Keys)
  3071. // File.Delete(_bitmaps[key]);
  3072. }
  3073. Progress.SetMessage("Transcoding");
  3074. //var inputFile = new MediaFile { Filename = filename };
  3075. //var outputFile = new MediaFile { Filename = Path.ChangeExtension(filename, "mp4") };
  3076. //using (var engine = new Engine())
  3077. //{
  3078. // //engine.ConvertProgressEvent += ConvertProgressEvent;
  3079. // engine.Convert(inputFile, outputFile);
  3080. //}
  3081. Progress.Close();
  3082. var dirName = Path.GetDirectoryName(filename);
  3083. if (dirName is not null)
  3084. {
  3085. var startInfo = new ProcessStartInfo(dirName);
  3086. startInfo.Verb = "open";
  3087. startInfo.UseShellExecute = true;
  3088. Process.Start(startInfo);
  3089. //MessageBox.Show("Recording Saved");
  3090. }
  3091. }
  3092. private void VideoRecordingButton_Click(object sender, RoutedEventArgs e)
  3093. {
  3094. ToggleRecording();
  3095. }
  3096. private void AudioRecordingButton_Click(object sender, RoutedEventArgs e)
  3097. {
  3098. ToggleRecordingAudio();
  3099. }
  3100. private void RecordingNotesButton_Click(object sender, RoutedEventArgs e)
  3101. {
  3102. ShowRecordingNotes();
  3103. }
  3104. #endregion
  3105. public static void ActivateWindow(Window window)
  3106. {
  3107. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  3108. var threadId1 = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
  3109. var threadId2 = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
  3110. if (threadId1 != threadId2)
  3111. {
  3112. AttachThreadInput(threadId1, threadId2, true);
  3113. SetForegroundWindow(hwnd);
  3114. AttachThreadInput(threadId1, threadId2, false);
  3115. }
  3116. else
  3117. {
  3118. SetForegroundWindow(hwnd);
  3119. }
  3120. }
  3121. private static IntPtr GetForegroundWindow()
  3122. {
  3123. var active = GetActiveWindow();
  3124. var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => new WindowInteropHelper(x).Handle == active);
  3125. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  3126. return hwnd;
  3127. }
  3128. [DllImport("user32.dll", SetLastError = true)]
  3129. private static extern IntPtr SetForegroundWindow(IntPtr hWnd);
  3130. [DllImport("user32.dll")]
  3131. private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
  3132. [DllImport("user32.dll")]
  3133. private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
  3134. [DllImport("user32.dll")]
  3135. private static extern IntPtr GetActiveWindow();
  3136. //private void ConvertProgressEvent(object sender, ConvertProgressEventArgs e)
  3137. //{
  3138. // Dispatcher.Invoke(() =>
  3139. // {
  3140. // try
  3141. // {
  3142. // if (e.TotalDuration.TotalSeconds != 0.0F)
  3143. // Progress.SetMessage(String.Format("Transcoding ({0:F2}% complete)", e.ProcessedDuration.TotalSeconds * 100.0F / e.TotalDuration.TotalSeconds));
  3144. // }
  3145. // catch (Exception err)
  3146. // {
  3147. // }
  3148. // });
  3149. //}
  3150. #region Check For Updates
  3151. private string GetUpdateLocation()
  3152. {
  3153. if (App.DatabaseSettings.DatabaseType == DatabaseType.Networked)
  3154. {
  3155. string url = "";
  3156. //var domain = App.DatabaseSettings.URL.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).Last();
  3157. //var port = App.DatabaseSettings.Port;
  3158. var domain = ClientFactory.Parameters?.FirstOrDefault()?.ToString() ?? "";
  3159. domain = domain.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? "";
  3160. if (!String.IsNullOrWhiteSpace(domain))
  3161. {
  3162. try
  3163. {
  3164. var client = new HttpClient { BaseAddress = new Uri($"https://{domain}") };
  3165. client.GetAsync("operations").Wait();
  3166. url = $"https://{domain}";
  3167. }
  3168. catch (Exception)
  3169. {
  3170. url = $"http://{domain}";
  3171. }
  3172. }
  3173. return url;
  3174. }
  3175. else
  3176. return Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update");
  3177. }
  3178. private string GetLatestVersion(string location)
  3179. {
  3180. return App.DatabaseSettings.DatabaseType switch
  3181. {
  3182. DatabaseType.Networked => Update.GetRemoteFile($"{location}/version").Content,
  3183. DatabaseType.Standalone or DatabaseType.Local => File.ReadAllText(Path.Combine(location, "version.txt")),
  3184. _ => "",
  3185. } ?? "";
  3186. }
  3187. private string GetReleaseNotes(string location)
  3188. {
  3189. return App.DatabaseSettings.DatabaseType switch
  3190. {
  3191. DatabaseType.Networked => Update.GetRemoteFile($"{location}/releasenotes").Content,
  3192. DatabaseType.Standalone or DatabaseType.Local => File.ReadAllText(Path.Combine(location, "Release Notes.txt")),
  3193. _ => "",
  3194. } ?? "";
  3195. }
  3196. private byte[]? GetInstaller(string location)
  3197. {
  3198. return App.DatabaseSettings.DatabaseType switch
  3199. {
  3200. DatabaseType.Networked => Update.GetRemoteFile($"{location}/install").RawBytes,
  3201. DatabaseType.Standalone or DatabaseType.Local => File.ReadAllBytes(Path.Combine(location, "PRSDesktopSetup.exe")),
  3202. _ => null,
  3203. };
  3204. }
  3205. private void CheckForUpdates()
  3206. {
  3207. Update.CheckForUpdates(
  3208. GetUpdateLocation, GetLatestVersion, GetReleaseNotes, GetInstaller, null, App.AutoUpdateSettings.Elevated, "PRSDesktopSetup.exe");
  3209. }
  3210. #endregion
  3211. #region Modules
  3212. public void CreatePanelAction(PanelAction action)
  3213. {
  3214. if (_ribbon.SelectedTabItem is null)
  3215. return;
  3216. var Actions = FindRibbonBar(_ribbon.SelectedTabItem, x => x.Header.Equals("Actions"));
  3217. if (Actions is not null)
  3218. {
  3219. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  3220. {
  3221. var sep = new RibbonSeparator();
  3222. CurrentModules.Add(sep);
  3223. Actions.Items.Add(sep);
  3224. }
  3225. var button = new RibbonButton
  3226. {
  3227. Label = action.Caption,
  3228. LargeIcon = action.Image.AsBitmapImage(),
  3229. SizeForm = SizeForm.Large,
  3230. MinWidth = 60,
  3231. Tag = action
  3232. };
  3233. button.Click += PaneActionClick;
  3234. CurrentModules.Add(button);
  3235. Actions.Items.Add(button);
  3236. }
  3237. }
  3238. private List<ISetupActionItem> PanelSetupActions = new();
  3239. public void CreateSetupAction(PanelAction action)
  3240. {
  3241. if (_ribbon.SelectedTabItem is null)
  3242. return;
  3243. AddSetupAction(PanelSetupActions, action.Caption, () =>
  3244. {
  3245. action.Execute();
  3246. }, action.Image);
  3247. }
  3248. private void PaneActionClick(object sender, RoutedEventArgs e)
  3249. {
  3250. var button = (Control)sender;
  3251. var action = (PanelAction)button.Tag;
  3252. action.Execute();
  3253. }
  3254. private void ReloadModules(string sectionName, DataModel model)
  3255. {
  3256. foreach (var module in CurrentModules)
  3257. {
  3258. if (module.Parent is Fluent.RibbonGroupBox bar)
  3259. bar.Items.Remove(module);
  3260. }
  3261. CurrentModules.Clear();
  3262. PanelSetupActions.Clear();
  3263. if (CurrentPanel != null)
  3264. {
  3265. CurrentPanel.CreateToolbarButtons(this);
  3266. CreateModules(sectionName, model, new Progress<Tuple<string, Bitmap, CustomModule>>(CreateModuleButton));
  3267. }
  3268. }
  3269. private void CreateModules(string section, DataModel model, IProgress<Tuple<string, Bitmap, CustomModule>> progress)
  3270. {
  3271. if (ClientFactory.IsSupported<CustomModule>())
  3272. {
  3273. foreach (var (module, image) in CustomModuleUtils.LoadCustomModuleThumbnails(section, model))
  3274. {
  3275. progress.Report(new Tuple<string, Bitmap, CustomModule>(module.Name ?? "", image, module));
  3276. }
  3277. }
  3278. }
  3279. private void CreateModuleButton(Tuple<string, Bitmap, CustomModule> module)
  3280. {
  3281. Fluent.RibbonGroupBox? Actions = CurrentTab != null
  3282. ? FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"))
  3283. : null;
  3284. if (Actions != null)
  3285. {
  3286. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  3287. {
  3288. var sep = new RibbonSeparator();
  3289. CurrentModules.Add(sep);
  3290. Actions.Items.Add(sep);
  3291. }
  3292. if (!CurrentModules.Any(x => x is Fluent.Button button && module.Item1.Equals(button.Header)))
  3293. {
  3294. var button = new Fluent.Button
  3295. {
  3296. Header = module.Item1,
  3297. LargeIcon = module.Item2.AsBitmapImage(),
  3298. MinWidth = 60,
  3299. Tag = module.Item3
  3300. };
  3301. button.Click += Module_Click;
  3302. CurrentModules.Add(button);
  3303. Actions.Items.Add(button);
  3304. }
  3305. }
  3306. }
  3307. private void Module_Click(object sender, RoutedEventArgs e)
  3308. {
  3309. if (CurrentPanel != null)
  3310. {
  3311. var item = (Fluent.Button)sender;
  3312. var code = (CustomModule)item.Tag;
  3313. if (!string.IsNullOrWhiteSpace(code.Script))
  3314. try
  3315. {
  3316. Selection selection;
  3317. if (code.SelectedRecords && code.AllRecords)
  3318. selection = RecordSelectionDialog.Execute();
  3319. else if (code.SelectedRecords)
  3320. selection = Selection.Selected;
  3321. else if (code.AllRecords)
  3322. selection = Selection.All;
  3323. else
  3324. selection = Selection.None;
  3325. var result = ScriptDocument.RunCustomModule(CurrentPanel.DataModel(selection), CurrentPanel.Selected(), code.Script);
  3326. if (result)
  3327. CurrentPanel.Refresh();
  3328. }
  3329. catch (CompileException c)
  3330. {
  3331. MessageBox.Show(c.Message);
  3332. }
  3333. catch (Exception err)
  3334. {
  3335. MessageBox.Show(CoreUtils.FormatException(err));
  3336. }
  3337. else
  3338. MessageBox.Show("Unable to load " + item.Header);
  3339. }
  3340. }
  3341. private void ManageModules()
  3342. {
  3343. if (CurrentPanel != null)
  3344. {
  3345. var section = CurrentPanel.SectionName;
  3346. var dataModel = CurrentPanel.DataModel(Selection.Selected);
  3347. var manager = new CustomModuleManager()
  3348. {
  3349. Section = section,
  3350. DataModel = dataModel
  3351. };
  3352. manager.ShowDialog();
  3353. ReloadModules(section, dataModel);
  3354. }
  3355. }
  3356. private void ManageModulesClick(object sender, RoutedEventArgs e)
  3357. {
  3358. ManageModules();
  3359. }
  3360. #endregion
  3361. #region Report Buttons
  3362. private void ReloadReports(string section, DataModel model)
  3363. {
  3364. if (CurrentTab is null)
  3365. return;
  3366. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  3367. if (ReportsBar is not null)
  3368. {
  3369. ReportsBar.Visibility = Security.IsAllowed<CanPrintReports>() ? Visibility.Visible : Visibility.Collapsed;
  3370. //ReportsBar.IsLauncherVisible = Security.IsAllowed<CanDesignReports>();
  3371. ReportsBar.Items.Clear();
  3372. CreateReports(section, model, new Progress<Tuple<string, Guid>>(CreateReportButton));
  3373. }
  3374. }
  3375. private void CreateReports(string section, DataModel model, IProgress<Tuple<string, Guid>> progress)
  3376. {
  3377. var client = new Client<ReportTemplate>();
  3378. var templates = client.Query(
  3379. new Filter<ReportTemplate>(x => x.DataModel).IsEqualTo(model.Name)
  3380. .And(x => x.Section).IsEqualTo(section)
  3381. .And(x => x.Visible).IsEqualTo(true),
  3382. new Columns<ReportTemplate>(x => x.ID, x => x.Name),
  3383. new SortOrder<ReportTemplate>(x => x.Name)
  3384. );
  3385. foreach (var row in templates.Rows)
  3386. progress.Report(new Tuple<string, Guid>(row.Get<ReportTemplate, string>(x => x.Name), row.Get<ReportTemplate, Guid>(x => x.ID)));
  3387. }
  3388. public void CreateReportButton(Tuple<string, Guid> report)
  3389. {
  3390. if (CurrentTab is null)
  3391. return;
  3392. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  3393. if (ReportsBar is not null)
  3394. {
  3395. var bFound = false;
  3396. foreach (var item in ReportsBar.Items)
  3397. {
  3398. if (item is RibbonButton button && report.Item2.Equals(button.Tag))
  3399. bFound = true;
  3400. }
  3401. if (!bFound)
  3402. {
  3403. var button = new RibbonButton
  3404. {
  3405. Label = report.Item1,
  3406. LargeIcon = PRSDesktop.Resources.printer.AsBitmapImage(),
  3407. Tag = report.Item2,
  3408. SizeForm = SizeForm.Large,
  3409. MinWidth = 60
  3410. };
  3411. if (Security.IsAllowed<CanDesignReports>())
  3412. {
  3413. var menu = new ContextMenu();
  3414. menu.AddItem("Design Report", PRSDesktop.Resources.pencil, report.Item2, ReportButtonMenu_DesignReport_Click);
  3415. button.ContextMenu = menu;
  3416. }
  3417. button.Click += ReportMenu_Checked;
  3418. ReportsBar.Items.Add(button);
  3419. }
  3420. }
  3421. }
  3422. private void ReportButtonMenu_DesignReport_Click(Guid templateID)
  3423. {
  3424. if (CurrentPanel is null)
  3425. return;
  3426. var template = new Client<ReportTemplate>().Load(new Filter<ReportTemplate>(x => x.ID).IsEqualTo(templateID)).FirstOrDefault();
  3427. if (template is null)
  3428. {
  3429. Logger.Send(LogType.Error, "", $"No Report Template with ID '{templateID}'");
  3430. MessageBox.Show("Report does not exist!");
  3431. return;
  3432. }
  3433. ReportUtils.DesignReport(template, CurrentPanel.DataModel(Selection.None));
  3434. }
  3435. private void ReportMenu_Checked(object sender, RoutedEventArgs e)
  3436. {
  3437. if (CurrentPanel is null)
  3438. return;
  3439. var item = (RibbonButton)sender;
  3440. var id = (Guid)item.Tag;
  3441. var template = new Client<ReportTemplate>().Load(new Filter<ReportTemplate>(x => x.ID).IsEqualTo(id)).FirstOrDefault();
  3442. if (template == null)
  3443. {
  3444. Logger.Send(LogType.Error, "", $"No Report Template with ID '{id}'");
  3445. MessageBox.Show("Report does not exist!");
  3446. return;
  3447. }
  3448. var selection = Selection.None;
  3449. if (template.SelectedRecords && template.AllRecords)
  3450. selection = RecordSelectionDialog.Execute();
  3451. else if (template.SelectedRecords)
  3452. selection = Selection.Selected;
  3453. else if (template.AllRecords)
  3454. selection = Selection.All;
  3455. else
  3456. MessageBox.Show("Report must have either [Selected Records] or [All Records] checked to display!");
  3457. if (selection != Selection.None)
  3458. ReportUtils.PreviewReport(template, CurrentPanel.DataModel(selection), false, Security.IsAllowed<CanDesignReports>());
  3459. }
  3460. private void ManageReports()
  3461. {
  3462. if (CurrentTab is null || CurrentPanel is null)
  3463. return;
  3464. var section = CurrentPanel.SectionName;
  3465. var model = CurrentPanel.DataModel(Selection.None);
  3466. if (model == null)
  3467. {
  3468. MessageBox.Show("No DataModel for " + CurrentTab.Header);
  3469. return;
  3470. }
  3471. var form = new ReportManager { DataModel = model, Section = section, Populate = true };
  3472. form.ShowDialog();
  3473. ReloadReports(section, model);
  3474. }
  3475. private void ManageEmailTemplates()
  3476. {
  3477. if (CurrentTab is null || CurrentPanel is null)
  3478. return;
  3479. var section = CurrentPanel.SectionName;
  3480. var model = CurrentPanel.DataModel(Selection.None);
  3481. if (model == null)
  3482. {
  3483. MessageBox.Show("No DataModel for " + CurrentTab.Header);
  3484. return;
  3485. }
  3486. var window = new EmailTemplateManagerWindow(model);
  3487. window.ShowDialog();
  3488. }
  3489. private void ManageReportsMenu_Click(object sender, RoutedEventArgs e)
  3490. {
  3491. ManageReports();
  3492. }
  3493. #endregion
  3494. #region Tracking Kanban
  3495. private void SelectTask_Click(object sender, RoutedEventArgs e)
  3496. {
  3497. ContextMenu menu = new ContextMenu();
  3498. MenuItem others = new MenuItem() { Header = "Other Tasks" };
  3499. using (new WaitCursor())
  3500. {
  3501. var kanbans = new Client<KanbanSubscriber>().Query(
  3502. new Filter<KanbanSubscriber>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
  3503. .And(x => x.Kanban.Completed).IsEqualTo(DateTime.MinValue)
  3504. .And(x => x.Kanban.Closed).IsEqualTo(DateTime.MinValue),
  3505. new Columns<KanbanSubscriber>(x => x.Kanban.ID)
  3506. .Add(x => x.Kanban.Number)
  3507. .Add(x => x.Kanban.Title)
  3508. .Add(x => x.Assignee),
  3509. new SortOrder<KanbanSubscriber>(x => x.Kanban.Number, SortDirection.Ascending)
  3510. );
  3511. foreach (var row in kanbans.Rows)
  3512. {
  3513. CreateTaskMenu(row.Get<KanbanSubscriber, bool>(c => c.Assignee) ? menu.Items : others.Items,
  3514. String.Format("{0} {1}",
  3515. row.Get<KanbanSubscriber, int>(c => c.Kanban.Number),
  3516. row.Get<KanbanSubscriber, String>(c => c.Kanban.Title)),
  3517. row.Get<KanbanSubscriber, Guid>(c => c.Kanban.ID)
  3518. );
  3519. }
  3520. menu.Items.Add(new Separator());
  3521. menu.Items.Add(others);
  3522. menu.Items.Add(new Separator());
  3523. CreateTaskMenu(menu.Items, "(No Task Selected)", Guid.Empty);
  3524. }
  3525. menu.IsOpen = true;
  3526. }
  3527. private Assignment? _kanbantrackingassignment = null;
  3528. private void SetTrackingKanban(Guid kanbanID, string header)
  3529. {
  3530. SelectedTaskName.Content = header;
  3531. var createNewAssignment = false;
  3532. if (_kanbantrackingassignment is not null)
  3533. {
  3534. if (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay)
  3535. {
  3536. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  3537. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  3538. }
  3539. // Update Existing Kanban
  3540. if (kanbanID == Guid.Empty)
  3541. _kanbantrackingassignment = null;
  3542. else if (_kanbantrackingassignment.Task.ID != kanbanID)
  3543. {
  3544. createNewAssignment = true;
  3545. }
  3546. }
  3547. else if (kanbanID != Guid.Empty)
  3548. {
  3549. createNewAssignment = true;
  3550. }
  3551. if (createNewAssignment)
  3552. {
  3553. _kanbantrackingassignment = new Assignment();
  3554. _kanbantrackingassignment.Task.ID = kanbanID;
  3555. _kanbantrackingassignment.EmployeeLink.ID = App.EmployeeID;
  3556. _kanbantrackingassignment.Title = header;
  3557. _kanbantrackingassignment.Date = DateTime.Today;
  3558. _kanbantrackingassignment.Actual.Start = DateTime.Now.TimeOfDay;
  3559. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay.Add(new TimeSpan(0, 2, 0));
  3560. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  3561. }
  3562. }
  3563. private void ClearTrackingKanban()
  3564. => SetTrackingKanban(Guid.Empty, "(No Task Selected)");
  3565. private void CreateTaskMenu(ItemCollection items, String title, Guid id)
  3566. {
  3567. var item = new MenuItem()
  3568. {
  3569. Header = title,
  3570. Tag = id
  3571. };
  3572. item.Click += (o, args) =>
  3573. {
  3574. if (o is not MenuItem menu) return;
  3575. SetTrackingKanban((Guid)item.Tag, (menu.Header as string) ?? "");
  3576. };
  3577. items.Add(item);
  3578. }
  3579. #endregion
  3580. private void DockPanel_OnIsActiveChanged(object? sender, EventArgs e)
  3581. {
  3582. var layout = sender as LayoutAnchorable;
  3583. if (layout == null)
  3584. return;
  3585. var content = layout.Content as DependencyObject;
  3586. var dock = content is IDockPanel panel ? panel : content?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  3587. if (dock == null)
  3588. return;
  3589. if (layout.IsActive && layout.IsVisible)
  3590. dock.Refresh();
  3591. }
  3592. private void _ribbon_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  3593. {
  3594. e.Handled = true;
  3595. }
  3596. #region Backstage Functions
  3597. private enum DatabaseConfigurationResult
  3598. {
  3599. RestartRequired,
  3600. RestartNotRequired,
  3601. Cancel
  3602. }
  3603. private DatabaseConfigurationResult ShowDatabaseConfiguration()
  3604. {
  3605. DatabaseConfigurationResult result;
  3606. var config = new DataBaseConfiguration();
  3607. if (config.ShowDialog() == true)
  3608. {
  3609. var newsettings = new LocalConfiguration<DatabaseSettings>(App.Profile).Load();
  3610. if (newsettings.RestartRequired(App.DatabaseSettings))
  3611. {
  3612. result = DatabaseConfigurationResult.RestartRequired;
  3613. }
  3614. else
  3615. {
  3616. result = DatabaseConfigurationResult.RestartNotRequired;
  3617. }
  3618. if ((newsettings.DatabaseType == DatabaseType.Standalone) && (newsettings.ColorScheme != App.DatabaseSettings.ColorScheme))
  3619. {
  3620. App.DatabaseSettings.ColorScheme = newsettings.ColorScheme;
  3621. ApplyColorScheme();
  3622. }
  3623. }
  3624. else
  3625. {
  3626. result = DatabaseConfigurationResult.Cancel;
  3627. }
  3628. return result;
  3629. }
  3630. private void DatabaseSettings_OnClick(object sender, RoutedEventArgs e)
  3631. {
  3632. switch (ShowDatabaseConfiguration())
  3633. {
  3634. case DatabaseConfigurationResult.RestartRequired:
  3635. MessageBox.Show("Please restart the application to apply these changes!");
  3636. break;
  3637. }
  3638. }
  3639. private void CompanyInformation_OnClick(object sender, RoutedEventArgs e)
  3640. {
  3641. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  3642. if (info == null)
  3643. info = new CompanyInformation();
  3644. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  3645. }
  3646. private void SecurityDefaultsButton_OnClick(object sender, RoutedEventArgs e)
  3647. {
  3648. var window = new GlobalTokenWindow();
  3649. window.ShowDialog();
  3650. Security.Reset();
  3651. }
  3652. private void SystemLogsButton_OnClick(object sender, RoutedEventArgs e)
  3653. {
  3654. var logfile = Path.Combine(CoreUtils.GetPath(), string.Format("{0:yyyy-MM-dd}.log", DateTime.Today));
  3655. if (File.Exists(logfile))
  3656. {
  3657. var startInfo = new ProcessStartInfo("notepad.exe", logfile);
  3658. startInfo.Verb = "open";
  3659. startInfo.UseShellExecute = true;
  3660. Process.Start(startInfo);
  3661. }
  3662. else
  3663. {
  3664. MessageBox.Show(logfile + " does not exist!");
  3665. }
  3666. }
  3667. private void DocumentTypeList_OnClick(object sender, RoutedEventArgs e)
  3668. {
  3669. var list = new MasterList(typeof(DocumentType));
  3670. list.ShowDialog();
  3671. }
  3672. private void DocumentList_OnClick(object sender, RoutedEventArgs e)
  3673. {
  3674. var list = new MasterList(typeof(Document));
  3675. list.ShowDialog();
  3676. }
  3677. private void QAFormSetupButton_OnClick(object sender, RoutedEventArgs e)
  3678. {
  3679. var list = new MasterList(typeof(DigitalForm), "AppliesTo", null, true);
  3680. list.ShowDialog();
  3681. }
  3682. private void EditDetailsButton_OnClick(object sender, RoutedEventArgs e)
  3683. {
  3684. var employee = new Client<Employee>().Query(
  3685. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid))
  3686. .Rows.FirstOrDefault()?.ToObject<Employee>();
  3687. var item = new MyDetailsConfiguration(employee);
  3688. item.User = ClientFactory.UserGuid;
  3689. var buttons = new DynamicEditorButtons();
  3690. buttons.Add("Change Password", null, item, (sender, item) =>
  3691. {
  3692. var details = (item as MyDetailsConfiguration)!;
  3693. var changePassword = new ChangePassword(details.User);
  3694. if (changePassword.ShowDialog() == true && changePassword.Password != null)
  3695. {
  3696. var newUser = new User();
  3697. newUser.ID = details.User;
  3698. ChangePassword.ChangeUserPassword(newUser, changePassword.Password);
  3699. new Client<User>().Save(newUser, "Changed Password");
  3700. MessageBox.Show("Password changed!");
  3701. }
  3702. });
  3703. var editor = new DynamicEditorForm(typeof(MyDetailsConfiguration), buttons: buttons);
  3704. if (employee == null)
  3705. {
  3706. editor.OnFormCustomiseEditor += (sender, items, column, editor) =>
  3707. {
  3708. editor.Editable = Editable.Disabled;
  3709. };
  3710. }
  3711. editor.Items = new BaseObject[] { item };
  3712. if (editor.ShowDialog() == true)
  3713. {
  3714. if (employee != null)
  3715. {
  3716. item.SaveTo(employee);
  3717. new Client<Employee>().Save(employee, "Edited by user");
  3718. }
  3719. }
  3720. }
  3721. private void LogoutButton_OnClick(object sender, RoutedEventArgs e)
  3722. {
  3723. Logout();
  3724. }
  3725. private void LoginButton_OnClick(object sender, RoutedEventArgs e)
  3726. {
  3727. if (DoLogin(false) == ValidationStatus.VALID)
  3728. AfterLogin();
  3729. }
  3730. private void ExitButton_OnClick(object sender, RoutedEventArgs e)
  3731. {
  3732. //_closingFromSystemMenu = true;
  3733. Close();
  3734. }
  3735. #endregion
  3736. }
  3737. }