MainWindow.xaml.cs 171 KB

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