MainWindow.xaml.cs 164 KB

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