MainWindow.xaml.cs 180 KB

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