diff --git a/CardReaderService/CardReaderService.conf b/CardReaderService/CardReaderService.conf new file mode 100644 index 0000000..802a6f4 --- /dev/null +++ b/CardReaderService/CardReaderService.conf @@ -0,0 +1,5 @@ +[program:CardReaderService] +command=mono-service CardReaderService.exe --no-daemon +directory=/DIRECTORYTOSET/CardReaderService +stdout_logfile=/DIRECTORYTOSET/CardReaderService/out.log +redirect_stderr=true diff --git a/CardReaderService/CardReaderService/CardReaderService.sln b/CardReaderService/CardReaderService.sln similarity index 56% rename from CardReaderService/CardReaderService/CardReaderService.sln rename to CardReaderService/CardReaderService.sln index 61dbd08..0198e9b 100644 --- a/CardReaderService/CardReaderService/CardReaderService.sln +++ b/CardReaderService/CardReaderService.sln @@ -1,28 +1,41 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CardReaderService", "CardReaderService.csproj", "{5F30E8E4-5107-4C99-ADFF-38D735DC113D}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CardReaderServiceHost", "..\CardReaderServiceHost\CardReaderServiceHost.csproj", "{6E48913F-9D8C-4132-93A7-C7B1C6DD5264}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5F30E8E4-5107-4C99-ADFF-38D735DC113D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5F30E8E4-5107-4C99-ADFF-38D735DC113D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5F30E8E4-5107-4C99-ADFF-38D735DC113D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5F30E8E4-5107-4C99-ADFF-38D735DC113D}.Release|Any CPU.Build.0 = Release|Any CPU - {6E48913F-9D8C-4132-93A7-C7B1C6DD5264}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6E48913F-9D8C-4132-93A7-C7B1C6DD5264}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6E48913F-9D8C-4132-93A7-C7B1C6DD5264}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6E48913F-9D8C-4132-93A7-C7B1C6DD5264}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CardReaderService", "CardReaderService\CardReaderService.csproj", "{5F30E8E4-5107-4C99-ADFF-38D735DC113D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CardReaderServiceHost", "CardReaderServiceHost\CardReaderServiceHost.csproj", "{6E48913F-9D8C-4132-93A7-C7B1C6DD5264}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Logger", "Logger\Logger.csproj", "{42EFE386-DC2E-455A-BA81-5FC9CEE45D02}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Linux Conf", "Linux Conf", "{F9053F37-761D-45EE-9153-46776B083DBA}" + ProjectSection(SolutionItems) = preProject + CardReaderService.conf = CardReaderService.conf + install.sh = install.sh + uninstall.sh = uninstall.sh + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5F30E8E4-5107-4C99-ADFF-38D735DC113D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5F30E8E4-5107-4C99-ADFF-38D735DC113D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5F30E8E4-5107-4C99-ADFF-38D735DC113D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5F30E8E4-5107-4C99-ADFF-38D735DC113D}.Release|Any CPU.Build.0 = Release|Any CPU + {6E48913F-9D8C-4132-93A7-C7B1C6DD5264}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6E48913F-9D8C-4132-93A7-C7B1C6DD5264}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6E48913F-9D8C-4132-93A7-C7B1C6DD5264}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6E48913F-9D8C-4132-93A7-C7B1C6DD5264}.Release|Any CPU.Build.0 = Release|Any CPU + {42EFE386-DC2E-455A-BA81-5FC9CEE45D02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {42EFE386-DC2E-455A-BA81-5FC9CEE45D02}.Debug|Any CPU.Build.0 = Debug|Any CPU + {42EFE386-DC2E-455A-BA81-5FC9CEE45D02}.Release|Any CPU.ActiveCfg = Release|Any CPU + {42EFE386-DC2E-455A-BA81-5FC9CEE45D02}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/CardReaderService/CardReaderService/App.config b/CardReaderService/CardReaderService/App.config index da9bca9..89c3fd7 100644 --- a/CardReaderService/CardReaderService/App.config +++ b/CardReaderService/CardReaderService/App.config @@ -1,9 +1,9 @@ - + - + - \ No newline at end of file + diff --git a/CardReaderService/CardReaderService/CardDataPost.cs b/CardReaderService/CardReaderService/CardDataPost.cs new file mode 100644 index 0000000..6dfce4c --- /dev/null +++ b/CardReaderService/CardReaderService/CardDataPost.cs @@ -0,0 +1,10 @@ +using System; + +namespace CardReaderService +{ + public class CardDataPost + { + public DateTime UtcTimeStamp { get; set; } + public string CardUId { get; set; } + } +} \ No newline at end of file diff --git a/CardReaderService/CardReaderService/CardReaderService.csproj b/CardReaderService/CardReaderService/CardReaderService.csproj index 2b37206..c3dce55 100644 --- a/CardReaderService/CardReaderService/CardReaderService.csproj +++ b/CardReaderService/CardReaderService/CardReaderService.csproj @@ -1,79 +1,90 @@ - - - - - Debug - AnyCPU - {5F30E8E4-5107-4C99-ADFF-38D735DC113D} - WinExe - Properties - CardReaderService - CardReaderService - v4.5.2 - 512 - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll - True - - - packages\PCSC.3.6.0\lib\net40\pcsc-sharp.dll - True - - - - - - - - - - - - - - - - - Component - - - Service1.cs - - - - - - - - - - + + + + + Debug + AnyCPU + {5F30E8E4-5107-4C99-ADFF-38D735DC113D} + WinExe + Properties + CardReaderService + CardReaderService + v4.5 + 512 + true + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\Newtonsoft.Json.12.0.2\lib\net45\Newtonsoft.Json.dll + True + + + ..\packages\PCSC.4.2.0\lib\net40\PCSC.dll + True + + + + + + + + + + + + + + + + + + + + + Component + + + Service1.cs + + + + + + + + + + + {42EFE386-DC2E-455A-BA81-5FC9CEE45D02} + Logger + + + + \ No newline at end of file diff --git a/CardReaderService/CardReaderService/ConfigurationManager.cs b/CardReaderService/CardReaderService/ConfigurationManager.cs new file mode 100644 index 0000000..6ce4afa --- /dev/null +++ b/CardReaderService/CardReaderService/ConfigurationManager.cs @@ -0,0 +1,38 @@ +using System; +using System.Configuration; +using System.Linq; +using System.Reflection; + +namespace CardReaderService +{ + public class ConfigurationManager + { + public ConfigurationProperty GetConfiguration(string configName) + { + var cfgManager = GetConfigManager(); + if (cfgManager.AppSettings.Settings.AllKeys.Contains(configName)) + { + var cfg = cfgManager.AppSettings.Settings[configName]; + return new ConfigurationProperty + { + Group=string.Empty, + Id="NOTIMPLEMENTED", + Name = cfg.Key, + Value = cfg.Value, + ReadOnly = false, + Source = "CardReaderService", + Type = ConfigurationType.STRING + }; + } + + return null; + } + + private Configuration GetConfigManager() + { + return System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigFilePath); + } + + public string ConfigFilePath => new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath; + } +} \ No newline at end of file diff --git a/CardReaderService/CardReaderService/ConfigurationProperty.cs b/CardReaderService/CardReaderService/ConfigurationProperty.cs new file mode 100644 index 0000000..653f0ab --- /dev/null +++ b/CardReaderService/CardReaderService/ConfigurationProperty.cs @@ -0,0 +1,55 @@ +namespace CardReaderService +{ + /// + /// An object used to detail an element that can be configured in the system. + /// + public class ConfigurationProperty + { + /// + /// Unique Id for the configuration property. + /// + public string Id { get; set; } + /// + /// The display name of the configuration + /// + public string Name { get; set; } + + /// + /// The group under which this configuration falls (e.g.: TCP Settings - "TCP" or similar.) + /// + /// Application Specific grouping. + public string Group { get; set; } + + /// + /// The actual value of the Configuration property + /// + public string Value { get; set; } + + /// + /// The source of the configuration properties. + /// + /// + /// Using this property allows aggregation of configuration settings + /// by any configuration managers + /// + /// {TYPE}.getType().Name (or other suitably unique identifier) + public string Source { get; set; } + + /// + /// The type of the configuration + /// + /// + /// This can be used for UI proofing/validation to ensure a user + /// enters expected format (e.g.: enters a date time for a datetime type) + /// + public ConfigurationType Type { get; set; } + + /// + /// Specifies whether the configuration setting can be set by user or is readonly + /// + public bool ReadOnly { get; set; } + + //TODO: in future, add access level, could go read level/edit level + //public UserAccessLevel UserLevel {get;set;} + } +} \ No newline at end of file diff --git a/CardReaderService/CardReaderService/ConfigurationType.cs b/CardReaderService/CardReaderService/ConfigurationType.cs new file mode 100644 index 0000000..0f82c40 --- /dev/null +++ b/CardReaderService/CardReaderService/ConfigurationType.cs @@ -0,0 +1,33 @@ +namespace CardReaderService +{ + /// + /// The type of the configuration. + /// + public enum ConfigurationType + { + /// + /// No Type - shouldnt be used, but default for enum + /// + NONE, + /// + /// a string type configuration (could also be used for complex objects, e.g.: a json string/object). + /// + STRING, + /// + /// A whole number configuration + /// + INT, + /// + /// A number config with a decimal component + /// + DECIMAL, + /// + /// A Date Time Configuration + /// + DATETIME, + /// + /// A Boolean/TrueFalse configuration property (e.g.: On Off) + /// + BOOL + } +} \ No newline at end of file diff --git a/CardReaderService/CardReaderService/DataCenterHelper.cs b/CardReaderService/CardReaderService/DataCenterHelper.cs index 6180064..9c42926 100644 --- a/CardReaderService/CardReaderService/DataCenterHelper.cs +++ b/CardReaderService/CardReaderService/DataCenterHelper.cs @@ -1,36 +1,40 @@ using System; -using System.Collections.Generic; -using System.Configuration; -using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; +using Logger; using Newtonsoft.Json; namespace CardReaderService { static class DataCenterHelper { + static DataCenterHelper() + { + } + public static void Post(CardDataPost postObject, string url) { - var endpointConfig = ConfigurationManager.AppSettings["DataCenterServiceEndpoint"] ?? - "http://localhost:8800"; + var cfgMgr = new ConfigurationManager(); + //using ConfigurationManager means we can change the value at runtime without having to restart the service. + var endpointConfig = cfgMgr.GetConfiguration("DataCenterServiceEndpoint")?.Value?? "http://localhost:8800"; + MessageLogger.Log("Targeting Endpoint: " + endpointConfig); using (var client = new HttpClient()) { var jsonObject = JsonConvert.SerializeObject(postObject); var content = new StringContent(jsonObject, Encoding.UTF8, "application/json"); try { - Console.WriteLine("Writing"); + MessageLogger.Log("Writing uid: "+ postObject.CardUId + " to the server."); var fullUrl = endpointConfig + url; + MessageLogger.Log("Writing to URL: " + fullUrl); var response = client.PostAsync(fullUrl, content).Result; - Console.WriteLine("Written"); + MessageLogger.Log("Successfully written to server"); } catch (Exception) { - Console.WriteLine("exceptioning"); - //ignore + MessageLogger.Log("Failed to send log to server."); } } } @@ -40,9 +44,4 @@ namespace CardReaderService return Task.Run(() => Post(postObject, url)); } } - - public class CardDataPost - { - public string CardUId { get; set; } - } } diff --git a/CardReaderService/CardReaderService/Service1.cs b/CardReaderService/CardReaderService/Service1.cs index 7039de9..c50d4dd 100644 --- a/CardReaderService/CardReaderService/Service1.cs +++ b/CardReaderService/CardReaderService/Service1.cs @@ -1,10 +1,13 @@ using PCSC; using System; +using System.CodeDom; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading; +using Logger; +using PCSC.Monitoring; namespace CardReaderService { @@ -12,14 +15,15 @@ namespace CardReaderService { private Thread _mainWorkThread; private bool _stopMainWorkerThread; - private AutoResetEvent _mainWorkerTerminationSignal; - private string _readerName = ""; + private readonly ManualResetEvent _mre; + + private string _readerName = string.Empty; private SCardMonitor _cardMonitor; - private bool _initialised=false; public Service1() { InitializeComponent(); + _mre = new ManualResetEvent(false); } public void Start() @@ -27,44 +31,54 @@ namespace CardReaderService OnStart(new string[] { }); } - protected override void OnStart(string[] args) - { - StartWorkerThread(); - } - - private bool WeHaveValidCardReader() - { - if (_cardMonitor == null) - { - return false; - } - Console.WriteLine(_cardMonitor.GetCurrentState(0)); - if (_cardMonitor.GetCurrentState(0) == SCRState.Unknown - || _cardMonitor.GetCurrentState(0) == SCRState.Unavailable - || _cardMonitor.GetCurrentState(0) == (SCRState.Ignore | SCRState.Unavailable) - //|| _cardMonitor.GetCurrentState(0) == SCRState.Unaware //if we say this is an invalid state, we cause a memory leak where we create a duplicate card monitor, subscribe and overwrite. - ) - { - return false; - } - return true; - } - - public void Stop() + public new void Stop() { OnStop(); + base.Stop(); + } + + protected override void OnStart(string[] args) + { + MessageLogger.Log("Starting.. "); + var ctxFactory = ContextFactory.Instance; + using (var context = ctxFactory.Establish(SCardScope.System)) + { + MessageLogger.Log("Getting Card Readers"); + var readerNames = context.GetReaders(); + if (NoReaderAvailable(readerNames)) + { + MessageLogger.Log("No Card Reader available, Exiting.."); + } + else + { + MessageLogger.Log("Choosing first available reader: " + readerNames.First()); + _readerName = readerNames.First(); + _cardMonitor = new SCardMonitor(ctxFactory, SCardScope.System); + _cardMonitor.CardInserted += CardMonitor_CardInserted; + _cardMonitor.StatusChanged += CardMonitorOnStatusChanged; + _cardMonitor.Start(_readerName); + } + StartWorkerThread(); + } } protected override void OnStop() { + MessageLogger.Log("Stopping.."); _stopMainWorkerThread = true; - _mainWorkerTerminationSignal.Set(); + _mre.Set(); if (_mainWorkThread != null && _mainWorkThread.IsAlive) { - _mainWorkThread.Interrupt(); + _mainWorkThread.Join(3000); + if (_mainWorkThread.IsAlive) + { + _mainWorkThread.Interrupt(); + } } if (_cardMonitor != null) { + _cardMonitor.CardInserted -= CardMonitor_CardInserted; + _cardMonitor.StatusChanged -= CardMonitorOnStatusChanged; _cardMonitor.Cancel(); _cardMonitor.Dispose(); _cardMonitor = null; @@ -79,96 +93,110 @@ namespace CardReaderService Name = "CardServiceMainThread", IsBackground = false }; - _mainWorkerTerminationSignal = new AutoResetEvent(false); _mainWorkThread.Start(); } - private void _cardMonitor_CardInserted(object sender, CardStatusEventArgs e) + private void CardMonitor_CardInserted(object sender, CardStatusEventArgs e) { - var ctxFac = ContextFactory.Instance; - using (var ctx = ctxFac.Establish(SCardScope.System)) + try { - var reader = new SCardReader(ctx); - var pioSendPci = new IntPtr(); - byte[] rcvBuffer = new byte[256]; - - if (_readerName == string.Empty) + var ctxFac = ContextFactory.Instance; + using (var ctx = ctxFac.Establish(SCardScope.System)) { - Console.WriteLine("Reader name is somehow empty... WTF!"); - _stopMainWorkerThread = true; - return; - } + var reader = new SCardReader(ctx); + byte[] rcvBuffer = new byte[256]; - var err = reader.Connect(_readerName, SCardShareMode.Shared, SCardProtocol.T0 | SCardProtocol.T1); + if (_readerName == string.Empty) + { + MessageLogger.Log("Reader name is somehow empty... WTF!"); + _stopMainWorkerThread = true; + return; + } - if (err == SCardError.Success) - { - var uIdcmd = new byte[] { 0xFF, 0xCA, 0x00, 0x00, 0x00 }; - - err = reader.Transmit(pioSendPci, uIdcmd, ref rcvBuffer); + var err = reader.Connect(_readerName, SCardShareMode.Shared, SCardProtocol.Any); if (err == SCardError.Success) { - var uid = ConvertByteUIDToString(rcvBuffer); - var atrString = ConvertByteUIDToString(e.Atr); - Console.WriteLine("Card Inserted, ATR: " + atrString + ", and UID is: " + uid); + var pci = SCardPCI.GetPci(reader.ActiveProtocol); - CardDataPost postObj = new CardDataPost { CardUId = uid }; - DataCenterHelper.PostAsync(postObj, "/api/swipedata"); - Console.WriteLine("Posted to Server"); + err = reader.Transmit(pci, CardCommands.GetUid, ref rcvBuffer); + + if (err == SCardError.Success) + { + var uid = ConvertByteUIDToString(rcvBuffer); + var atrString = ConvertByteUIDToString(e.Atr); + + MessageLogger.Log("Card Inserted, ATR: " + atrString + ", and UID is: " + uid); + + CardDataPost postObj = new CardDataPost { CardUId = uid, UtcTimeStamp = DateTime.UtcNow }; + DataCenterHelper.PostAsync(postObj, "/api/swipedata"); + MessageLogger.Log("Posted to Server"); + } + else + { + MessageLogger.Log("Failed to Read UID, Error: " + err); + } + } + else + { + MessageLogger.Log("Reader failed to connect, error: " + Enum.GetName(typeof(SCardError), err)); } } - else - { - Console.WriteLine("Reader failed to connect, error: " + Enum.GetName(typeof(SCardError), err)); - } - + } + catch (Exception ex) + { + MessageLogger.Log("Exception has occurred in Card Inserted Event handler. Exception: "+ ex); + throw; } } private void MainWorkerThread() { + var minimumLoopTimemS = 5000; + while (!_stopMainWorkerThread) { - if (!WeHaveValidCardReader()) - { //only do this if we don't have a valid card reader - if (_initialised) - { - //card reader no longer available, tidy up. - _cardMonitor.Cancel(); - _cardMonitor.CardInserted -= _cardMonitor_CardInserted; - _cardMonitor.Dispose(); - _cardMonitor = null; - _initialised = false; - } - Console.WriteLine("Starting.. Getting available readers"); + if (_cardMonitor == null) + { var ctxFactory = ContextFactory.Instance; using (var context = ctxFactory.Establish(SCardScope.System)) { var readerNames = context.GetReaders(); - if (!NoReaderAvailable(readerNames)) + if (NoReaderAvailable(readerNames)) { - //we have a reader available, so initialise! - Console.WriteLine("Choosing first available reader: " + readerNames.First()); - _readerName = readerNames.First(); - _cardMonitor = new SCardMonitor(ctxFactory, SCardScope.System); - _cardMonitor.CardInserted += _cardMonitor_CardInserted; - _cardMonitor.Start(_readerName); - - _initialised = true; + MessageLogger.Log("No Card Reader available, Waiting.."); } else { - Console.WriteLine("No Card Reader is available.."); + MessageLogger.Log("Choosing first available reader: " + readerNames.First()); + _readerName = readerNames.First(); + _cardMonitor = new SCardMonitor(ctxFactory, SCardScope.System); + _cardMonitor.CardInserted += CardMonitor_CardInserted; + _cardMonitor.StatusChanged += CardMonitorOnStatusChanged; + _cardMonitor.Start(_readerName); } } } - _mainWorkerTerminationSignal.WaitOne(3000); + //dont actually need to do anything.. but cannot exit right away? + _mre.WaitOne(minimumLoopTimemS); + } + } + + private void CardMonitorOnStatusChanged(object sender, StatusChangeEventArgs e) + { + if ((e.NewState & SCRState.Unavailable) == SCRState.Unavailable && (e.NewState & SCRState.Ignore) == SCRState.Ignore) + { + Console.WriteLine("Card Reader Disconnected"); + _cardMonitor.CardInserted -= CardMonitor_CardInserted; + _cardMonitor.Cancel(); + _cardMonitor.Dispose(); + _cardMonitor = null; + _readerName = string.Empty; } } private string ConvertByteUIDToString(byte[] uid) { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); foreach (var b in uid) { @@ -183,4 +211,9 @@ namespace CardReaderService return readerNames == null || readerNames.Count < 1; } } + + internal class CardCommands + { + public static readonly byte[] GetUid = {0xFF, 0xCA, 0x00, 0x00, 0x08}; + } } diff --git a/CardReaderService/CardReaderService/packages.config b/CardReaderService/CardReaderService/packages.config index b8ef0ce..08418a9 100644 --- a/CardReaderService/CardReaderService/packages.config +++ b/CardReaderService/CardReaderService/packages.config @@ -1,5 +1,5 @@  - - + + \ No newline at end of file diff --git a/CardReaderService/CardReaderServiceHost/App.config b/CardReaderService/CardReaderServiceHost/App.config index 88fa402..d1428ad 100644 --- a/CardReaderService/CardReaderServiceHost/App.config +++ b/CardReaderService/CardReaderServiceHost/App.config @@ -1,6 +1,6 @@ - + - + - \ No newline at end of file + diff --git a/CardReaderService/CardReaderServiceHost/CardReaderServiceHost.csproj b/CardReaderService/CardReaderServiceHost/CardReaderServiceHost.csproj index 44c5609..61b73b5 100644 --- a/CardReaderService/CardReaderServiceHost/CardReaderServiceHost.csproj +++ b/CardReaderService/CardReaderServiceHost/CardReaderServiceHost.csproj @@ -9,9 +9,10 @@ Properties CardReaderServiceHost CardReaderServiceHost - v4.5.2 + v4.5 512 true + AnyCPU @@ -33,8 +34,8 @@ 4 - - ..\CardReaderService\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll + + ..\packages\Newtonsoft.Json.12.0.2\lib\net45\Newtonsoft.Json.dll True @@ -52,6 +53,18 @@ + + CardReaderService.conf + PreserveNewest + + + install.sh + PreserveNewest + + + uninstall.sh + PreserveNewest + diff --git a/CardReaderService/CardReaderServiceHost/Program.cs b/CardReaderService/CardReaderServiceHost/Program.cs index fc8886a..4e9511f 100644 --- a/CardReaderService/CardReaderServiceHost/Program.cs +++ b/CardReaderService/CardReaderServiceHost/Program.cs @@ -9,7 +9,7 @@ namespace CardReaderServiceHost { Service1 service1 = new Service1(); service1.Start(); - Console.WriteLine("Service Running..."); + Console.WriteLine("Service Running... Enter To Stop"); Console.ReadLine(); service1.Stop(); } diff --git a/CardReaderService/CardReaderServiceHost/packages.config b/CardReaderService/CardReaderServiceHost/packages.config index 9d64bf3..93b0be8 100644 --- a/CardReaderService/CardReaderServiceHost/packages.config +++ b/CardReaderService/CardReaderServiceHost/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/CardReaderService/Logger/Logger.csproj b/CardReaderService/Logger/Logger.csproj new file mode 100644 index 0000000..9ee3507 --- /dev/null +++ b/CardReaderService/Logger/Logger.csproj @@ -0,0 +1,55 @@ + + + + + Debug + AnyCPU + {42EFE386-DC2E-455A-BA81-5FC9CEE45D02} + Library + Properties + Logger + Logger + v4.5 + 512 + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CardReaderService/Logger/MessageLogger.cs b/CardReaderService/Logger/MessageLogger.cs new file mode 100644 index 0000000..a693525 --- /dev/null +++ b/CardReaderService/Logger/MessageLogger.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Logger +{ + public class MessageLogger + { + private static string _logPath = "log.txt"; + + public static void Log(string message) + { + Console.WriteLine(message); + File.AppendAllText(_logPath, string.Format("{0} | {1}{2}", DateTime.Now, message, Environment.NewLine)); + } + } +} diff --git a/CardReaderService/Logger/Properties/AssemblyInfo.cs b/CardReaderService/Logger/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3ae09c3 --- /dev/null +++ b/CardReaderService/Logger/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Logger")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Logger")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("42efe386-dc2e-455a-ba81-5fc9cee45d02")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/CardReaderService/dependencies.txt b/CardReaderService/dependencies.txt new file mode 100644 index 0000000..ceae7b8 --- /dev/null +++ b/CardReaderService/dependencies.txt @@ -0,0 +1,7 @@ +install: + - pcscd + - supervisor + - mono-complete + +copy CardReaderService.conf to /home/osboxes/CardReaderService + diff --git a/CardReaderService/install.sh b/CardReaderService/install.sh new file mode 100644 index 0000000..e81d6cc --- /dev/null +++ b/CardReaderService/install.sh @@ -0,0 +1,25 @@ +#!/bin/sh +if [ -z "$1" ] +then + echo "No arguments supplied, supply the base path" +fi +echo "Installing dependencies" +apt-get install mono-complete pcscd supervisor -y + +echo "Modifying supervisor conf file" +sed -i "s|/DIRECTORYTOSET|$1|g" CardReaderService.conf + +echo "Installing service configuration file" +cp CardReaderService.conf /etc/supervisor/conf.d/ + +echo "Installing applicaton" +mkdir $1/CardReaderService +cp ./*.* $1/CardReaderService +cd $1/CardReaderService +rm *.pdb +rm *.vshost.exe +rm *.vshost.exe.config +rm *.vshost.exe.manifest +echo "Starting application........." +service supervisor restart + diff --git a/CardReaderService/uninstall.sh b/CardReaderService/uninstall.sh new file mode 100644 index 0000000..7922179 --- /dev/null +++ b/CardReaderService/uninstall.sh @@ -0,0 +1,12 @@ +#!/bin/sh +if [ -z "$1" ] + then + echo "No arguments supplied, supply the base path" +fi +echo "Stopping service...." +service supervisor stop +rm -f /etc/supervisor/conf.d/CardReaderService.conf +echo "Removing Application.." +rm -r -f $1/CardReaderService +echo "Removing application dependencies.." +apt-get remove pcscd supervisor mono-complete -y diff --git a/DataCenter_Windows/WindowsDataCenter/CardReaderService/App.config b/DataCenter_Windows/WindowsDataCenter/CardReaderService/App.config index a1f8f1f..414b7d8 100644 --- a/DataCenter_Windows/WindowsDataCenter/CardReaderService/App.config +++ b/DataCenter_Windows/WindowsDataCenter/CardReaderService/App.config @@ -1,10 +1,18 @@ - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + diff --git a/DataCenter_Windows/WindowsDataCenter/CardReaderService/CardReaderService.csproj b/DataCenter_Windows/WindowsDataCenter/CardReaderService/CardReaderService.csproj index 2f275a1..912c1ac 100644 --- a/DataCenter_Windows/WindowsDataCenter/CardReaderService/CardReaderService.csproj +++ b/DataCenter_Windows/WindowsDataCenter/CardReaderService/CardReaderService.csproj @@ -1,125 +1,127 @@ - - - - - Debug - AnyCPU - {5F30E8E4-5107-4C99-ADFF-38D735DC113D} - WinExe - Properties - CardReaderService - CardReaderService - v4.5.2 - 512 - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - bin\DebugInstallers\ - DEBUG;TRACE - full - AnyCPU - prompt - MinimumRecommendedRules.ruleset - true - - - bin\ReleaseInstallers\ - TRACE - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - true - - - - ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll - True - - - ..\packages\Ninject.3.2.2.0\lib\net45-full\Ninject.dll - True - - - ..\packages\Ninject.Extensions.Xml.3.2.0.0\lib\net45-full\Ninject.Extensions.Xml.dll - True - - - ..\packages\PCSC.3.6.0\lib\net40\pcsc-sharp.dll - True - - - - - - - - - - - - - - - - - - - - Component - - - CardReaderService.cs - - - - - - - - - - - {115250F6-F8C4-4F9B-A15F-251EA258D963} - ConfigurationHandler - - - {B7347B72-E208-423A-9D99-723B558EA3D7} - Interfaces - - - - - Always - - - + + + + + Debug + AnyCPU + {5F30E8E4-5107-4C99-ADFF-38D735DC113D} + WinExe + Properties + CardReaderService + CardReaderService + v4.5 + 512 + true + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\DebugInstallers\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + true + + + bin\ReleaseInstallers\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + true + + + + ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll + True + + + ..\packages\Ninject.3.3.4\lib\net45\Ninject.dll + True + + + ..\packages\Ninject.Extensions.Xml.3.3.0\lib\net45\Ninject.Extensions.Xml.dll + True + + + ..\packages\PCSC.3.6.0\lib\net40\pcsc-sharp.dll + True + + + + + + + + + + + + + + + + + + + + + Component + + + CardReaderService.cs + + + + + + + + + + + {115250F6-F8C4-4F9B-A15F-251EA258D963} + ConfigurationHandler + + + {B7347B72-E208-423A-9D99-723B558EA3D7} + Interfaces + + + + + Always + + + + --> \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/CardReaderService/DefaultComponents/LogFileLogger.cs b/DataCenter_Windows/WindowsDataCenter/CardReaderService/DefaultComponents/LogFileLogger.cs new file mode 100644 index 0000000..2a12080 --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/CardReaderService/DefaultComponents/LogFileLogger.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Interfaces; + +namespace CardReaderService.DefaultComponents +{ + class LogFileLogger: ILogger + { + public bool IsDebugEnabled => true; + public bool IsErrorEnabled => true; + public bool IsFatalEnabled => true; + public bool IsInfoEnabled => true; + public bool IsTraceEnabled => true; + public bool IsWarnEnabled => true; + + public void Debug(Exception exception) + { + Log(exception.ToString()); + } + + public void Debug(string format, params object[] args) + { + Log(string.Format(format, args)); + } + + public void Debug(Exception exception, string format, params object[] args) + { + Log(exception.ToString()); + Log(string.Format(format, args)); + } + + public void Error(Exception exception) + { + Log(exception.ToString()); + } + + public void Error(string format, params object[] args) + { + Log(string.Format(format, args)); + } + + public void Error(Exception exception, string format, params object[] args) + { + Log(exception.ToString()); + Log(string.Format(format, args)); + } + + public void Fatal(Exception exception) + { + Log(exception.ToString()); + } + + public void Fatal(string format, params object[] args) + { + Log(string.Format(format, args)); + } + + public void Fatal(Exception exception, string format, params object[] args) + { + Log(exception.ToString()); + Log(string.Format(format, args)); + } + + public void Info(Exception exception) + { + Log(exception.ToString()); + } + + public void Info(string format, params object[] args) + { + Log(string.Format(format, args)); + } + + public void Info(Exception exception, string format, params object[] args) + { + Log(exception.ToString()); + Log(string.Format(format, args)); + } + + public void Trace(Exception exception) + { + Log(exception.ToString()); + } + + public void Trace(string format, params object[] args) + { + Log(string.Format(format, args)); + } + + public void Trace(Exception exception, string format, params object[] args) + { + Log(exception.ToString()); + Log(string.Format(format, args)); + } + + public void Warn(Exception exception) + { + Log(exception.ToString()); + } + + public void Warn(string format, params object[] args) + { + Log(string.Format(format, args)); + } + + public void Warn(Exception exception, string format, params object[] args) + { + Log(exception.ToString()); + Log(string.Format(format, args)); + } + + private static string _logPath = "log.txt"; + + public static void Log(string message) + { + System.IO.File.WriteAllText(_logPath, string.Format("{0} | {1}", DateTime.Now, message)); + } + } +} diff --git a/DataCenter_Windows/WindowsDataCenter/CardReaderService/NinjectConfig.xml b/DataCenter_Windows/WindowsDataCenter/CardReaderService/NinjectConfig.xml index 71ad73d..e9e7cb1 100644 --- a/DataCenter_Windows/WindowsDataCenter/CardReaderService/NinjectConfig.xml +++ b/DataCenter_Windows/WindowsDataCenter/CardReaderService/NinjectConfig.xml @@ -1,5 +1,5 @@  + to="CardReaderService.DefaultComponents.LogFileLogger, CardReaderService" scope="singleton" /> \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/CardReaderService/packages.config b/DataCenter_Windows/WindowsDataCenter/CardReaderService/packages.config index 4bf2383..23176dc 100644 --- a/DataCenter_Windows/WindowsDataCenter/CardReaderService/packages.config +++ b/DataCenter_Windows/WindowsDataCenter/CardReaderService/packages.config @@ -1,7 +1,7 @@ - - - - - - + + + + + + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/CardReaderServiceHost/App.config b/DataCenter_Windows/WindowsDataCenter/CardReaderServiceHost/App.config index 6fda695..9a7ce8e 100644 --- a/DataCenter_Windows/WindowsDataCenter/CardReaderServiceHost/App.config +++ b/DataCenter_Windows/WindowsDataCenter/CardReaderServiceHost/App.config @@ -1,10 +1,18 @@ - - - - - - - - - + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/CardReaderServiceHost/CardReaderServiceHost.csproj b/DataCenter_Windows/WindowsDataCenter/CardReaderServiceHost/CardReaderServiceHost.csproj index 3a3f061..ef110da 100644 --- a/DataCenter_Windows/WindowsDataCenter/CardReaderServiceHost/CardReaderServiceHost.csproj +++ b/DataCenter_Windows/WindowsDataCenter/CardReaderServiceHost/CardReaderServiceHost.csproj @@ -1,101 +1,101 @@ - - - - - Debug - AnyCPU - {6E48913F-9D8C-4132-93A7-C7B1C6DD5264} - Exe - Properties - CardReaderServiceHost - CardReaderServiceHost - v4.5.2 - 512 - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - bin\DebugInstallers\ - DEBUG;TRACE - full - AnyCPU - prompt - MinimumRecommendedRules.ruleset - true - - - bin\ReleaseInstallers\ - TRACE - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - true - - - - ..\CardReaderService\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll - True - - - - - - - - - - - - - - - - - - - - - - {5f30e8e4-5107-4c99-adff-38d735dc113d} - CardReaderService - - - - - mkdir "$(TargetDir)Configs" -copy "$(SolutionDir)NLogLogger\$(OutDir)NLogLogger.dll" "$(TargetDir)" -copy "$(SolutionDir)NLogLogger\$(OutDir)NLog.dll" "$(TargetDir)" -copy "$(SolutionDir)NLogLogger\$(OutDir)NLogLogger.dll.config" "$(TargetDir)" -copy "$(SolutionDir)NLogLogger\$(OutDir)NLogConfig.xml" "$(TargetDir)Configs\" - -copy "$(SolutionDir)WindowsDataCenter\$(OutDir)Ninject.Extensions.Xml.dll" "$(TargetDir)" - - + + + + + Debug + AnyCPU + {6E48913F-9D8C-4132-93A7-C7B1C6DD5264} + Exe + Properties + CardReaderServiceHost + CardReaderServiceHost + v4.5.2 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\DebugInstallers\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + true + + + bin\ReleaseInstallers\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + true + + + + ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll + True + + + + + + + + + + + + + + + + + + + + + + {5f30e8e4-5107-4c99-adff-38d735dc113d} + CardReaderService + + + + + mkdir "$(TargetDir)Configs" +copy "$(SolutionDir)NLogLogger\$(OutDir)NLogLogger.dll" "$(TargetDir)" +copy "$(SolutionDir)NLogLogger\$(OutDir)NLog.dll" "$(TargetDir)" +copy "$(SolutionDir)NLogLogger\$(OutDir)NLogLogger.dll.config" "$(TargetDir)" +copy "$(SolutionDir)NLogLogger\$(OutDir)NLogConfig.xml" "$(TargetDir)Configs\" + +copy "$(SolutionDir)WindowsDataCenter\$(OutDir)Ninject.Extensions.Xml.dll" "$(TargetDir)" + + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/CardReaderServiceHost/packages.config b/DataCenter_Windows/WindowsDataCenter/CardReaderServiceHost/packages.config index 9d64bf3..6576d88 100644 --- a/DataCenter_Windows/WindowsDataCenter/CardReaderServiceHost/packages.config +++ b/DataCenter_Windows/WindowsDataCenter/CardReaderServiceHost/packages.config @@ -1,4 +1,4 @@ - - - + + + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/CardReaderServiceInstaller/CardReaderServiceComponents.wxs b/DataCenter_Windows/WindowsDataCenter/CardReaderServiceInstaller/CardReaderServiceComponents.wxs index 9b96fdf..a5723d1 100644 --- a/DataCenter_Windows/WindowsDataCenter/CardReaderServiceInstaller/CardReaderServiceComponents.wxs +++ b/DataCenter_Windows/WindowsDataCenter/CardReaderServiceInstaller/CardReaderServiceComponents.wxs @@ -30,8 +30,18 @@ + + + + + + + diff --git a/DataCenter_Windows/WindowsDataCenter/ConfigurationHandler/ConfigurationHandler.csproj b/DataCenter_Windows/WindowsDataCenter/ConfigurationHandler/ConfigurationHandler.csproj index 461434d..456c1dc 100644 --- a/DataCenter_Windows/WindowsDataCenter/ConfigurationHandler/ConfigurationHandler.csproj +++ b/DataCenter_Windows/WindowsDataCenter/ConfigurationHandler/ConfigurationHandler.csproj @@ -9,8 +9,9 @@ Properties ConfigurationHandler ConfigurationHandler - v4.5.2 + v4.5 512 + true diff --git a/DataCenter_Windows/WindowsDataCenter/Interfaces/IRepository.cs b/DataCenter_Windows/WindowsDataCenter/Interfaces/IRepository.cs index e5e4f59..3551b49 100644 --- a/DataCenter_Windows/WindowsDataCenter/Interfaces/IRepository.cs +++ b/DataCenter_Windows/WindowsDataCenter/Interfaces/IRepository.cs @@ -1,114 +1,120 @@ -using System; -using System.Collections.Generic; - -namespace Interfaces -{ - public interface IRepository - { - /// - /// Get a list of Users - /// - /// - /// Returns with full list of users, - /// plus a total user count. Pagination options are supported. - /// - UserList GetUsers(int pageNumber = -1, int pageSize = -1, int groupId = -1); - /// - /// Search the user list for the following string - /// - /// string to search the user store for. - /// - /// Returns with full list of users, - /// plus a total user count. Pagination options are supported. - /// - UserList Search(string searchParam); - /// - /// Get details about a single user in the system base on their Id - /// - /// - /// integer data type, the Id of the User to get details about. - /// - /// object with full details, - /// including full - /// - User GetUser(int id); - /// - /// Get a list of the timelogs available for the specified user - /// for the current Calendar Week - /// - /// - /// integer data type, the Id of the user to get time logs for - /// - /// - /// with nested objects - /// for the current calendar week - /// - TimeLogList GetTimeLogs(int userId); - /// - /// Get a list of the timelogs available for the specified user - /// for the specified calendar week - /// - /// - /// integer data type, the Id of the user to get time logs for - /// - /// - /// datetime data type, the date to receive time logs for (will scope out to calendar week). - /// - /// - /// with nested objects - /// for the current calendar week - /// - TimeLogList GetTimeLogs(int userId, DateTime selectedDate); - /// - /// Get a full list of Identifiers which are not associated to a user. - /// - /// - /// with nested list - /// - IdentifierList GetUnassignedIdentifierList(); - /// - /// Remove all unassigned identifiers from the system. - /// - void ClearUnassignedIdentifiers(); - - /// - /// Update a user in the system with the new values. - /// - /// - /// If the user object passed does not exist, it will be created. - /// - /// - /// object detailing the new properties to assign to the user. - /// The Id Field should not be changed, or should be -1 for new users. - /// - /// - /// int - ref param, value will be the UserId of the inserted or updated user - /// - /// - /// to indicate procedure status. - /// - OperationResponse UpdateUser(User user, out int userId); - - /// - /// Create a new TimeLog Event in the repository. - /// - /// - /// object with the Unique Id triggering the event - /// - /// The resultant Id of the inserted TimeLog - /// - /// to indicate procedure status. - /// - LogEventResponse LogEventTime(Identifier identifier, out int logId); - - OperationResponse CreateGroup(Group group, out int groupId); - List GetGroups(int userId = -1); - Group GetGroup(int groupId); - OperationResponse UpdateGroup(Group group); - OperationResponse DeleteGroup(int groupId); - - OperationResponse DeleteLog(TimeLog log); - OperationResponse CreateLog(TimeLog log); - OperationResponse UpdateLog(TimeLog log); - } -} +using System; +using System.Collections.Generic; + +namespace Interfaces +{ + public interface IRepository + { + /// + /// Get a list of Users + /// + /// + /// Returns with full list of users, + /// plus a total user count. Pagination options are supported. + /// + UserList GetUsers(int pageNumber = -1, int pageSize = -1, int groupId = -1, SortOptions sort = SortOptions.None); + /// + /// Search the user list for the following string + /// + /// string to search the user store for. + /// + /// Returns with full list of users, + /// plus a total user count. Pagination options are supported. + /// + UserList Search(string searchParam); + /// + /// Get details about a single user in the system base on their Id + /// + /// + /// integer data type, the Id of the User to get details about. + /// + /// object with full details, + /// including full + /// + User GetUser(int id); + /// + /// Get a list of the timelogs available for the specified user + /// for the current Calendar Week + /// + /// + /// integer data type, the Id of the user to get time logs for + /// + /// + /// with nested objects + /// for the current calendar week + /// + TimeLogList GetTimeLogs(int userId); + /// + /// Get a list of the timelogs available for the specified user + /// for the specified calendar week + /// + /// + /// integer data type, the Id of the user to get time logs for + /// + /// + /// datetime data type, the date to receive time logs for (will scope out to calendar week). + /// + /// + /// with nested objects + /// for the current calendar week + /// + TimeLogList GetTimeLogs(int userId, DateTime selectedDate); + /// + /// Get a full list of Identifiers which are not associated to a user. + /// + /// + /// with nested list + /// + IdentifierList GetUnassignedIdentifierList(); + /// + /// Remove all unassigned identifiers from the system. + /// + void ClearUnassignedIdentifiers(); + + /// + /// Update a user in the system with the new values. + /// + /// + /// If the user object passed does not exist, it will be created. + /// + /// + /// object detailing the new properties to assign to the user. + /// The Id Field should not be changed, or should be -1 for new users. + /// + /// + /// int - ref param, value will be the UserId of the inserted or updated user + /// + /// + /// to indicate procedure status. + /// + OperationResponse UpdateUser(User user, out int userId); + + /// + /// Create a new TimeLog Event in the repository. + /// + /// + /// object with the Unique Id triggering the event + /// + /// The resultant Id of the inserted TimeLog + /// Optional - To set the log time of the swipe. + /// Particularly useful for buffering logs in nodes if they cannot contact server for whatever reason to minimise data loss + /// + /// to indicate procedure status. + /// + LogEventResponse LogEventTime(Identifier identifier, out int logId, DateTime logTime = default(DateTime)); + + OperationResponse CreateGroup(Group group, out int groupId); + List GetGroups(int userId = -1); + Group GetGroup(int groupId); + OperationResponse UpdateGroup(Group group); + OperationResponse DeleteGroup(int groupId); + + OperationResponse DeleteLog(TimeLog log); + OperationResponse CreateLog(TimeLog log); + OperationResponse UpdateLog(TimeLog log); + + Policy GetPolicy(); + + void SavePolicy(Policy policy); + } +} diff --git a/DataCenter_Windows/WindowsDataCenter/Interfaces/Interfaces.csproj b/DataCenter_Windows/WindowsDataCenter/Interfaces/Interfaces.csproj index 2a53dee..23a1f0c 100644 --- a/DataCenter_Windows/WindowsDataCenter/Interfaces/Interfaces.csproj +++ b/DataCenter_Windows/WindowsDataCenter/Interfaces/Interfaces.csproj @@ -1,86 +1,89 @@ - - - - - Debug - AnyCPU - {B7347B72-E208-423A-9D99-723B558EA3D7} - Library - Properties - Interfaces - Interfaces - v4.5.2 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - bin\DebugInstallers\ - DEBUG;TRACE - full - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - bin\ReleaseInstallers\ - TRACE - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + Debug + AnyCPU + {B7347B72-E208-423A-9D99-723B558EA3D7} + Library + Properties + Interfaces + Interfaces + v4.5 + 512 + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\DebugInstallers\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + bin\ReleaseInstallers\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + --> \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/Interfaces/Policy.cs b/DataCenter_Windows/WindowsDataCenter/Interfaces/Policy.cs new file mode 100644 index 0000000..6baac80 --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/Interfaces/Policy.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Interfaces +{ + public class Policy + { + public DateTime ChangeDate { get; set; } + public string ChangeDescription { get; set; } + public string ChangeAuthor { get; set; } + public string Version { get; set; } + public string Markdown { get; set; } + public string Html { get; set; } + } +} diff --git a/DataCenter_Windows/WindowsDataCenter/Interfaces/SortOptions.cs b/DataCenter_Windows/WindowsDataCenter/Interfaces/SortOptions.cs new file mode 100644 index 0000000..240ae66 --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/Interfaces/SortOptions.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Interfaces +{ + public enum SortOptions + { + None, + FirstNameAscending, + FirstNameDescending, + LastNameAscending, + LastNameDescending, + } +} diff --git a/DataCenter_Windows/WindowsDataCenter/Interfaces/UserList.cs b/DataCenter_Windows/WindowsDataCenter/Interfaces/UserList.cs index 0cb7171..916e1b0 100644 --- a/DataCenter_Windows/WindowsDataCenter/Interfaces/UserList.cs +++ b/DataCenter_Windows/WindowsDataCenter/Interfaces/UserList.cs @@ -1,30 +1,33 @@ -using System.Collections.Generic; - -namespace Interfaces -{ - public class UserList - { - public UserList() - { - Users = new List(); - PageSize = 10; - } - public string Query { get; set; } - public int UserCount { get { return Users.Count; } } - public int TotalUserCount { get; set; } - public List Users { get; set; } - - public int PageCount - { - get - { - if (TotalUserCount < PageSize) - return 1; - return (TotalUserCount / PageSize); - } - } - public Group GroupFilter { get; set; } - public int PageSize { get; set; } - public int PageNumber { get; set; } - } +using System; +using System.Collections.Generic; + +namespace Interfaces +{ + public class UserList + { + public UserList() + { + Users = new List(); + PageSize = 10; + } + public string Query { get; set; } + public int UserCount { get { return Users.Count; } } + public int TotalUserCount { get; set; } + public List Users { get; set; } + + public SortOptions SelectedSortOption { get; set; } + + public int PageCount + { + get + { + if (TotalUserCount < PageSize) + return 1; + return (int)Math.Ceiling(Convert.ToDouble(TotalUserCount) / Convert.ToDouble(PageSize)); + } + } + public Group GroupFilter { get; set; } + public int PageSize { get; set; } + public int PageNumber { get; set; } + } } \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/NLogLogger/NLogLogger.csproj b/DataCenter_Windows/WindowsDataCenter/NLogLogger/NLogLogger.csproj index 82362dc..6dcb560 100644 --- a/DataCenter_Windows/WindowsDataCenter/NLogLogger/NLogLogger.csproj +++ b/DataCenter_Windows/WindowsDataCenter/NLogLogger/NLogLogger.csproj @@ -1,96 +1,96 @@ - - - - - Debug - AnyCPU - {1C5220D6-9166-4F47-B57D-BEB4D09D2A3F} - Library - Properties - NLogLogger - NLogLogger - v4.5.2 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - bin\DebugInstallers\ - DEBUG;TRACE - full - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - bin\ReleaseInstallers\ - TRACE - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - - ..\packages\NLog.4.4.2\lib\net45\NLog.dll - True - - - - - - - - - - - - - - - - - - {115250F6-F8C4-4F9B-A15F-251EA258D963} - ConfigurationHandler - - - {B7347B72-E208-423A-9D99-723B558EA3D7} - Interfaces - - - - - - - - - Always - - - - + + + + + Debug + AnyCPU + {1C5220D6-9166-4F47-B57D-BEB4D09D2A3F} + Library + Properties + NLogLogger + NLogLogger + v4.5.2 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\DebugInstallers\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + bin\ReleaseInstallers\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\NLog.4.4.2\lib\net45\NLog.dll + True + + + + + + + + + + + + + + + + + + {115250F6-F8C4-4F9B-A15F-251EA258D963} + ConfigurationHandler + + + {B7347B72-E208-423A-9D99-723B558EA3D7} + Interfaces + + + + + + + + + Always + + + + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/NLogLogger/packages.config b/DataCenter_Windows/WindowsDataCenter/NLogLogger/packages.config index 42af3c0..d7980ce 100644 --- a/DataCenter_Windows/WindowsDataCenter/NLogLogger/packages.config +++ b/DataCenter_Windows/WindowsDataCenter/NLogLogger/packages.config @@ -1,4 +1,4 @@ - - - + + + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/IdentifierConverter.cs b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/IdentifierConverter.cs new file mode 100644 index 0000000..d55a781 --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/IdentifierConverter.cs @@ -0,0 +1,29 @@ +using Interfaces; + +namespace SQLiteRepository.Converters +{ + static class IdentifierConverter + { + public static Identifier ConvertToIdentifierDto(CardUniqueId ident) + { + return new Identifier + { + Id = ident.Id, + UniqueId = ident.CardUId, + IsAssociatedToUser = ident.UserId_FK != Constants.UNASSIGNED_CARD_USER_ID, + LastUsed = ident.LastUsed.DateTime + }; + } + + public static CardUniqueId ConvertFromIdentifierDto(Identifier ident, int userId) + { + return new CardUniqueId + { + CardUId = ident.UniqueId, + Id = ident.Id, + UserId_FK = userId, + LastUsed = ident.LastUsed + }; + } + } +} \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/LogDirectionConverter.cs b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/LogDirectionConverter.cs new file mode 100644 index 0000000..72a536e --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/LogDirectionConverter.cs @@ -0,0 +1,51 @@ +using Interfaces; + +namespace SQLiteRepository.Converters +{ + static class LogDirectionConverter + { + public static LogDirection ConvertToLogDirectionDto(LogDirectionDb direction) + { + switch (direction) + { + case LogDirectionDb.IN: + return LogDirection.IN; + case LogDirectionDb.OUT: + return LogDirection.OUT; + default: + return LogDirection.UNKNOWN; + } + } + + public static LogDirectionDb ConvertFromLogDirectionDto(LogDirection direction) + { + switch (direction) + { + case LogDirection.IN: + return LogDirectionDb.IN; + case LogDirection.OUT: + return LogDirectionDb.OUT; + default: + return LogDirectionDb.UNKNOWN; + } + } + + public static LogDirectionDb InvertLogDirectionDb(LogDirectionDb direction) + { + return (LogDirectionDb)(int)InvertLogDirection((LogDirection)(int)direction); + } + + public static LogDirection InvertLogDirection(LogDirection direction) + { + switch (direction) + { + case LogDirection.IN: + return LogDirection.OUT; + case LogDirection.OUT: + return LogDirection.IN; + default: + return LogDirection.UNKNOWN; + } + } + } +} \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/LogSourceConverter.cs b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/LogSourceConverter.cs new file mode 100644 index 0000000..6ebc7c1 --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/LogSourceConverter.cs @@ -0,0 +1,37 @@ +using Interfaces; + +namespace SQLiteRepository.Converters +{ + static class LogSourceConverter + { + public static LogSource ConvertToLogSourceDto(LogSourceDb source) + { + switch (source) + { + case LogSourceDb.IDENTIFIER: + return LogSource.IDENTIFIER; + case LogSourceDb.TRAYAPP: + return LogSource.TRAYAPP; + case LogSourceDb.UI: + return LogSource.UI; + default: + return LogSource.UNKNOWN; + } + } + + public static LogSourceDb ConvertFromLogSourceDto(LogSource source) + { + switch (source) + { + case LogSource.IDENTIFIER: + return LogSourceDb.IDENTIFIER; + case LogSource.TRAYAPP: + return LogSourceDb.TRAYAPP; + case LogSource.UI: + return LogSourceDb.UI; + default: + return LogSourceDb.UNKNOWN; + } + } + } +} \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/PolicyConverter.cs b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/PolicyConverter.cs new file mode 100644 index 0000000..79cf4e4 --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/PolicyConverter.cs @@ -0,0 +1,35 @@ +using Interfaces; + +namespace SQLiteRepository.Converters +{ + static class PolicyConverter + { + public static Policy ConvertToPolicyDto(PolicyDb policyDb) + { + if (policyDb == null) return null; + return new Policy + { + ChangeDescription = policyDb.ChangeDescription, + ChangeDate = policyDb.ChangeDate.UtcDateTime, + Html = policyDb.Html, + Version = policyDb.Version, + ChangeAuthor = policyDb.ChangeAuthor, + Markdown = policyDb.Markdown + }; + } + + public static PolicyDb ConvertFromPolicyDto(Policy policy) + { + if (policy == null) return null; + return new PolicyDb + { + ChangeDescription = policy.ChangeDescription, + ChangeDate = policy.ChangeDate, + Html = policy.Html, + Version = policy.Version, + ChangeAuthor = policy.ChangeAuthor, + Markdown = policy.Markdown + }; + } + } +} \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/TimeLogConverter.cs b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/TimeLogConverter.cs new file mode 100644 index 0000000..a118836 --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/TimeLogConverter.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Interfaces; + +namespace SQLiteRepository.Converters +{ + static class TimeLogConverter + { + public static TimeLog ConvertToTimeLogDto(TimeLogDb log) + { + return new TimeLog + { + CalendarWeek = log.CalendarWeek, + Direction = LogDirectionConverter.ConvertToLogDirectionDto(log.Direction), + EventTime = log.SwipeEventDateTime, + Id = log.Id, + IdentifierId = log.IdentifierId, + UserId = log.UserId_FK, + Source = LogSourceConverter.ConvertToLogSourceDto(log.Source), + Year = log.Year + }; + } + + public static TimeLogDb ConvertFromTimeLogDto(TimeLog log) + { + return new TimeLogDb + { + CalendarWeek = log.CalendarWeek, + Year = log.Year, + UserId_FK = log.UserId, + IdentifierId = log.IdentifierId, + Direction = LogDirectionConverter.ConvertFromLogDirectionDto(log.Direction), + Id = log.Id, + Source = LogSourceConverter.ConvertFromLogSourceDto(log.Source), + SwipeEventDateTime = log.EventTime + }; + } + } +} diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/UserConverter.cs b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/UserConverter.cs new file mode 100644 index 0000000..8933a67 --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Converters/UserConverter.cs @@ -0,0 +1,32 @@ +using System; +using Interfaces; + +namespace SQLiteRepository.Converters +{ + static class UserConverter + { + public static User ConvertToUserDto(UserIdentity user) + { + return new User + { + UserId = user.Id, + FirstName = user.FirstName, + LastName = user.LastName, + IsContractor = user.IsContractor, + HoursPerWeek = user.HoursPerWeek, + }; + } + + public static UserIdentity ConvertFromUserDto(User user) + { + return new UserIdentity + { + Id = user.UserId, + FirstName = user.FirstName, + LastName = user.LastName, + HoursPerWeek = user.HoursPerWeek, + IsContractor = user.IsContractor + }; + } + } +} diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Extensions/Extensions.cs b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Extensions/Extensions.cs new file mode 100644 index 0000000..ad3bc2f --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/Extensions/Extensions.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SQLiteRepository.Extensions +{ + public static class EnumerableExtensions + { + public static IEnumerable Exclude(this IEnumerable source, + IEnumerable exclude, Func keySelector) + { + var excludedSet = new HashSet(exclude.Select(keySelector)); + return source.Where(item => !excludedSet.Contains(keySelector(item))); + } + } +} diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/PolicyDb.cs b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/PolicyDb.cs new file mode 100644 index 0000000..ab2017d --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/PolicyDb.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SQLite.Net.Attributes; + +namespace SQLiteRepository +{ + internal class PolicyDb + { + [PrimaryKey, AutoIncrement] + public int Id { get; set; } + public DateTimeOffset ChangeDate { get; set; } + + public string ChangeDescription { get; set; } + + public string ChangeAuthor { get; set; } + + public string Version { get; set; } + + public string Markdown { get; set; } + + public string Html { get; set; } + + } +} diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/SQLiteProcedures.cs b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/SQLiteProcedures.cs index bcded4e..db5d8fb 100644 --- a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/SQLiteProcedures.cs +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/SQLiteProcedures.cs @@ -1,9 +1,14 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.Design; +using System.Linq; + namespace SQLiteRepository { internal static class SQLiteProcedures { public const string GET_LOGS_IN_LAST_X_MINUTES = - "select * from TimeLogDb where " + nameof(TimeLogDb.SwipeEventDateTime) + " > ? AND " + + "select * from " + nameof(TimeLogDb) + " where " + nameof(TimeLogDb.SwipeEventDateTime) + " > ? AND " + nameof(TimeLogDb.UserId_FK) + "=?"; public const string GET_TIMELOGS = @@ -11,20 +16,18 @@ namespace SQLiteRepository nameof(TimeLogDb.CalendarWeek) + "=? and " + nameof(TimeLogDb.Year) + "=?)"; public const string GET_ALL_USERS = - "select * from " + nameof(UserIdentity) + " ut " + "select * from " + nameof(UserIdentity) + " ut " + "where " + "EXISTS( select " + nameof(GroupDb.GroupId) - + " from " + nameof(GroupDb) - + " where " + nameof(GroupDb.GroupName) + " = 'Archived') AND " - + "NOT EXISTS( select * from " + nameof(UserGroupJoinDb) + " ugp where " - + nameof(UserGroupJoinDb.UserId_FK) + " = ut.Id" - + " and " + nameof(UserGroupJoinDb.GroupId_FK) + " = ( " - + "select " + nameof(GroupDb.GroupId) - + " from " + nameof(GroupDb) - + " where " + nameof(GroupDb.GroupName) + " = 'Archived') )" - + "order by " - + nameof(UserIdentity.LastName) + " collate nocase, " - + nameof(UserIdentity.FirstName) + " collate nocase"; + + " from " + nameof(GroupDb) + + " where " + nameof(GroupDb.GroupName) + " = 'Archived') AND " + + "NOT EXISTS( select * from " + nameof(UserGroupJoinDb) + " ugp where " + + nameof(UserGroupJoinDb.UserId_FK) + " = ut.Id" + + " and " + nameof(UserGroupJoinDb.GroupId_FK) + " = ( " + + "select " + nameof(GroupDb.GroupId) + + " from " + nameof(GroupDb) + + " where " + nameof(GroupDb.GroupName) + " = 'Archived') )" + + "order by ? collate nocase ?, ? collate nocase ?"; public const string GET_ALL_USERS_PAGINATE = "select * from " + nameof(UserIdentity) + " ut " @@ -38,18 +41,18 @@ namespace SQLiteRepository + "select " + nameof(GroupDb.GroupId) + " from " + nameof(GroupDb) + " where " + nameof(GroupDb.GroupName) + " = 'Archived') )" - + "order by " - + nameof(UserIdentity.LastName) + " collate nocase, " - + nameof(UserIdentity.FirstName) + " collate nocase " - + "limit ? offset ?"; + + " order by " + + "{0} collate nocase {1}, " + + "{2} collate nocase {3} " + + "limit {4} offset {5}"; public const string GET_ALL_USERS_BY_GROUP = "select u." + nameof(UserIdentity.Id) + ", u." + nameof(UserIdentity.FirstName) + ", u." + nameof(UserIdentity.LastName) + ", u." + nameof(UserIdentity.HoursPerWeek) + ", u." + nameof(UserIdentity.IsContractor) + " from " + nameof(UserIdentity) + " u left join " + nameof(UserGroupJoinDb) + " ugj on ugj." + nameof(UserGroupJoinDb.UserId_FK) + " = u." + - nameof(UserIdentity.Id) + " where ugj." + nameof(UserGroupJoinDb.GroupId_FK) + "=? order by u." + - nameof(UserIdentity.LastName) + " collate nocase, u." + nameof(UserIdentity.LastName) + " collate nocase"; + nameof(UserIdentity.Id) + " where ugj." + nameof(UserGroupJoinDb.GroupId_FK) + "= {0} " + + "order by u.{1} collate nocase {2}, u.{3} collate nocase {4}"; public const string GET_USER_BY_ID = "select * from " + nameof(UserIdentity) + " where " + nameof(UserIdentity.Id) + "=?"; @@ -60,6 +63,9 @@ namespace SQLiteRepository public const string GET_CARDS_BY_UNIQUE_ID = "select * from " + nameof(CardUniqueId) + " where " + nameof(CardUniqueId.CardUId) + "=?"; + public const string GET_CARDS_BY_UNIQUE_ID_LIST = + "select * from " + nameof(CardUniqueId) + " where " + nameof(CardUniqueId.CardUId) + " in (#IN#)"; + public const string GET_UNASSIGNED_CARD_LIST = "select * from " + nameof(CardUniqueId) + " where " + nameof(CardUniqueId.UserId_FK) + "=?"; @@ -88,9 +94,82 @@ namespace SQLiteRepository nameof(TimeLogDb.SwipeEventDateTime) + " desc LIMIT 1"; public const string GET_TOTAL_USER_COUNT = - "select Max(" + nameof(UserIdentity.Id) + ") from " + nameof(UserIdentity); + "select count(1) from " + nameof(UserIdentity) + " ut " + + "where " + + "EXISTS( select " + nameof(GroupDb.GroupId) + + " from " + nameof(GroupDb) + + " where " + nameof(GroupDb.GroupName) + " = 'Archived') " + + "AND NOT EXISTS( select * from " + nameof(UserGroupJoinDb) + " ugp where " + + nameof(UserGroupJoinDb.UserId_FK) + " = ut.Id" + + " and " + nameof(UserGroupJoinDb.GroupId_FK) + " = ( " + + "select " + nameof(GroupDb.GroupId) + + " from " + nameof(GroupDb) + + " where " + nameof(GroupDb.GroupName) + " = 'Archived') )"; + //"select Max(" + nameof(UserIdentity.Id) + ") from " + nameof(UserIdentity); public const string GET_USER_CONTRACTED_HOURS = "select " + nameof(UserIdentity.HoursPerWeek) + " From UserIdentity where " + nameof(UserIdentity.Id) + "=?"; + + public const string GET_GROUPS = "select gp."+ nameof(GroupDb.GroupId)+ ", gp."+nameof(GroupDb.GroupName)+", " + + "sum(case when gp." + nameof(GroupDb.GroupId) + " = ujdb." + nameof(UserGroupJoinDb.GroupId_FK) + " then 1 else 0 end) as " + nameof(GroupDb.AssignedUserCount) + + " from " + nameof(GroupDb) + " gp" + + " left join " + nameof(UserGroupJoinDb) + " ujdb " + + "on ujdb." + nameof(UserGroupJoinDb.GroupId_FK) + " = gp." + nameof(GroupDb.GroupId) + + " group by gp." + nameof(GroupDb.GroupId); + + public const string GET_GROUPS_FOR_USER = "select gdb." + nameof(GroupDb.GroupId) + ", gdb." + nameof(GroupDb.GroupName) + ", gdb." + nameof(GroupDb.AssignedUserCount) + "" + + " from " + nameof(GroupDb) + " gdb" + + " left join " + nameof(UserGroupJoinDb) + " ujdb" + + " on gdb." + nameof(GroupDb.GroupId) + " = ujdb." + nameof(UserGroupJoinDb.GroupId_FK) + + " where ujdb." + nameof(UserGroupJoinDb.UserId_FK) + " = ?"; + + public const string GET_GROUP_BY_ID = + "select * from " + nameof(GroupDb) + " where " + nameof(GroupDb.GroupId) + " =?"; + + public const string UPDATE_GROUP = "update " + nameof(GroupDb) + " set " + nameof(GroupDb.GroupName) + + "=? where " + nameof(GroupDb.GroupId) + "=?"; + + public const string GET_GROUP_BY_NAME = + "select 1 from " + nameof(GroupDb)+" where "+nameof(GroupDb.GroupName)+"= ?"; + + public const string GET_TIMELOG_ENTRY = + "select * from " + nameof(TimeLogDb) + " where " + nameof(TimeLogDb.Id) + "=?"; + + public const string DELETE_TIMELOG_ENTRY = + "delete from " + nameof(TimeLogDb) + " where " + nameof(TimeLogDb.Id) + "=?"; + + public const string DELETE_TIMELOG_ENTRIES = + "delete from " + nameof(TimeLogDb) + " where " + nameof(TimeLogDb.Id) + "in (#IN#)"; + + public const string UPDATE_TIMELOG_ENTRY = "update " + nameof(TimeLogDb) + + " set " + nameof(TimeLogDb.UserId_FK) + "=?, " + + nameof(TimeLogDb.Direction) + "=?," + + nameof(TimeLogDb.SwipeEventDateTime) + "=?," + + nameof(TimeLogDb.CalendarWeek) + "=?," + + nameof(TimeLogDb.Year) + "=?," + + nameof(TimeLogDb.Source) + "=? " + + "where " + nameof(TimeLogDb.Id) + "=?"; + + public const string GET_DB_VERSION = "select * from " + nameof(DbVersion); + + /// + /// This works on the tokenisation of the query string. + /// where the list of params is to be inserted, the query should have #IN# + /// + /// the query to add the list of parameters to + /// the parameters to add to the query. + /// + public static string FormatInQuery(string query, List args) + { + if (!query.Contains("#IN#")) + { + throw new ArgumentException("query doesnt contain any #IN# tokenisation"); + } + //Convert to a comma separated list e.g.: val1,val2,val3 + //but we need to use string.. so.. enclose in single quotes 'val1','val2'..etc + var argsFormatted = string.Join(",", args.Select(x=>$"'{x}'")); + + return query.Replace("#IN#", argsFormatted); + } } } \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/SQLiteRepository.cs b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/SQLiteRepository.cs index 89c510b..d977d37 100644 --- a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/SQLiteRepository.cs +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/SQLiteRepository.cs @@ -1,929 +1,963 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net; -using System.Reflection; -using Interfaces; -using SQLite.Net; -using SQLite.Net.Platform.Win32; -using SQLiteRepository.Properties; - -namespace SQLiteRepository -{ - public class SQLiteRepository : IRepository - { - private readonly SQLiteConnection _connection; - private readonly ILogger _logger; - private string _path = "flexitimedb.db"; - - public SQLiteRepository(ILogger logger) - { - _path = - new Uri(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().CodeBase), "flexitimedb.db")) - .LocalPath; - if (logger == null) throw new ArgumentNullException(nameof(logger)); - _logger = logger; - - _connection = new SQLiteConnection(new SQLitePlatformWin32(), _path); - - _connection.CreateTable(); - _connection.CreateTable(); - _connection.CreateTable(); - _connection.CreateTable(); - _connection.CreateTable(); - _connection.CreateTable(); - _logger.Trace("Initialised SQLite Repository"); - _logger.Trace("Checking For Upgrades"); - CheckForDbUpgrade(); - } - - private void CheckForDbUpgrade() - { - var data = _connection.Query("select * from DbVersion"); - if (!data.Any()) - { - //Pre-Upgrade database, need upgrading - _logger.Trace("Pre version 0.2 RC database found, performing update.."); - ExecuteUpgradeFromVersion("0.1"); //execute 0.2 upgrade scripts onwards. - } - else - { - var installedVersion = new Version(data.First().VersionNumber); - var currentVersion = new Version(AssemblyInfo.ASSEMBLY_VERSION); - if (currentVersion.CompareTo(installedVersion) > 0) //greater than 0 - current version is newer - { - _logger.Trace("Installed Database Version: {0} is older than current version {1}"); - ExecuteUpgradeFromVersion(installedVersion.ToString()); - } - } - } - - private void ExecuteUpgradeFromVersion(string installedVersion) - { - const string PREFIX = "SQLiteRepository.UpgradeScripts."; - var instVers = new Version(installedVersion); - //so we have established that each script for upgrade will be .sql, so now start at lowest version and work up! - var assembly = Assembly.GetExecutingAssembly(); - var upgradeScripts = assembly.GetManifestResourceNames() - .Where(x=>x.StartsWith(PREFIX)) - .OrderBy(x=>new Version(Path.GetFileNameWithoutExtension(x.Replace(PREFIX, "")))) - .Where(x => - { - var scriptVersion = new Version(Path.GetFileNameWithoutExtension(x.Replace(PREFIX, ""))).CompareTo(instVers); - return scriptVersion > 0; - } - ) - .ToList(); - //now have an ordered list of upgrade script files, so execute in order! - foreach (var upgradeScript in upgradeScripts) - { - using (var stream = assembly.GetManifestResourceStream(upgradeScript)) - using(var str = new StreamReader(stream)) - { - var script = str.ReadToEnd(); - _logger.Trace("Executing upgrade script with name: {0}", upgradeScript); - _connection.Execute(script); - } - } - SetDbVersion(AssemblyInfo.ASSEMBLY_VERSION); - } - - private void SetDbVersion(string vers) - { - _connection.DeleteAll(); - _connection.Insert(new DbVersion {VersionNumber = vers}); - _logger.Trace("Set Database version to: {0}", vers); - } - - public UserList GetUsers(int pageNumber = -1, int pageSize = -1, int groupId = -1) - { - var ret = new UserList(); - List users; - int userCount; - if (pageNumber != -1 && pageSize != -1) - { - users = _connection.Query(SQLiteProcedures.GET_ALL_USERS_PAGINATE, - pageSize, (pageNumber - 1) * pageSize); - userCount = _connection.ExecuteScalar(SQLiteProcedures.GET_TOTAL_USER_COUNT); - } - else if (groupId != -1) - { - users = - _connection.Query( - SQLiteProcedures.GET_ALL_USERS_BY_GROUP, - groupId); - userCount = users.Count; - } - else - { - users = _connection.Query(SQLiteProcedures.GET_ALL_USERS); - userCount = users.Count; - } - - if (!users.Any()) - { - if (pageNumber == -1 && pageSize == -1) - { - ret.PageNumber = 1; - ret.PageSize = 20; - } - else - { - ret.PageNumber = pageNumber; - ret.PageSize = pageSize; - } - return ret; - } - - foreach (var user in users) - { - var userObj = ChangeToUserObject(user); - - userObj.AssociatedIdentifiers = GetAssociatedIdentifiers(user.Id); - userObj.State = GetUserState(GetLogDirection(user.Id)); - userObj.LastEventDateTime = GetLastLogDateTime(GetLastTimeLog(user.Id)); - userObj.Groups = GetGroups(user.Id); - ret.Users.Add(userObj); - } - if (pageNumber == -1 && pageSize == -1) - { - ret.PageSize = 10; - ret.PageNumber = 1; - } - else - { - ret.PageSize = pageSize; - ret.PageNumber = pageNumber; - } - ret.TotalUserCount = userCount; - return ret; - } - - public UserList Search(string searchParam) - { - _logger.Trace("Searching SQLite database for the term: {0}", searchParam); - var ret = new UserList(); - searchParam = string.Format("%{0}%", searchParam); - var users = _connection.Query( - SQLiteProcedures.SEARCH_USER_LIST, - searchParam, searchParam); - - _logger.Trace("Got {0} results for term: {1}", users.Count, searchParam); - if (!users.Any()) - { - ret.PageNumber = 1; - ret.PageSize = 20; - return ret; - } - - foreach (var user in users) - { - var userObj = ChangeToUserObject(user); - var cards = _connection.Query( - SQLiteProcedures.GET_CARDS_BY_USER_ID, - user.Id); - - foreach (var card in cards) - { - userObj.AssociatedIdentifiers.Add(new Identifier() - { - UniqueId = card.CardUId, - IsAssociatedToUser = true, - Id = card.Id - }); - } - userObj.State = GetUserState(GetLogDirection(user.Id)); - ret.Users.Add(userObj); - } - //TODO: figure out paging here. - should there be any? - ret.PageSize = 20; - ret.PageNumber = 1; - - return ret; - } - - public User GetUser(int id) - { - var ret = new User(); - - try - { - var users = _connection.Query( - SQLiteProcedures.GET_USER_BY_ID, - id); - - if (!users.Any()) return ret; - - var user = users.First(); - ret = ChangeToUserObject(user); - ret.Groups = GetGroups(); - var usersGroups = GetGroups(user.Id); - foreach (var group in usersGroups) - { - ret.Groups.First(x => x.Id == group.Id).IsAssociatedToUser = true; - } - var cards = _connection.Query( - SQLiteProcedures.GET_CARDS_BY_USER_ID, - user.Id); - - foreach (var card in cards) - { - ret.AssociatedIdentifiers.Add(new Identifier { UniqueId = card.CardUId, IsAssociatedToUser = true, Id = card.Id }); - } - } - catch (Exception ex) - { - _logger.Error(ex, "Error in GetUser with Id: {0}", id); - ret.UserId = id; - ret.FirstName = ret.LastName = string.Empty; - ret.HoursPerWeek = -1.0f; - ret.IsContractor = false; - ret.AssociatedIdentifiers.Clear(); - } - - return ret; - } - - public TimeLogList GetTimeLogs(int userId) - { - return GetTimeLogs(userId, DateTime.UtcNow); - } - - public TimeLogList GetTimeLogs(int userId, DateTime selectedDate) - { - var ret = new TimeLogList { SelectedDate = selectedDate.Date }; - var calendarWeek = GetIso8601CalendarWeek(selectedDate); - ret.CalendarWeek = calendarWeek; - - try - { - ret.TimeLogs = GetTimeLogList(userId, calendarWeek, selectedDate.Year); - } - catch (Exception ex) - { - _logger.Error(ex, "Error in GetTimeLogs with Id: {0} and selected date: {1}, Exception: {2}", userId, selectedDate, ex); - } - - try - { - ret.HoursPerWeekMinutes = GetUserContractedHours(userId) * 60.0f; - } - catch (Exception ex) - { - _logger.Error(ex, "Error in GetUserContracterHours with Id: {0} and selected date: {1}, Exception: {2}", userId, selectedDate, ex); - } - - ret.UserInformation = GetUser(userId); - return ret; - } - - private float GetUserContractedHours(int userId) - { - var hoursQuery = _connection.Query(SQLiteProcedures.GET_USER_CONTRACTED_HOURS, userId); - if (hoursQuery.Any()) - { - return hoursQuery.First().HoursPerWeek; - } - return -1.0f; - } - - public IdentifierList GetUnassignedIdentifierList() - { - var ret = new IdentifierList(); - var cardQuery = _connection.Query( - SQLiteProcedures.GET_UNASSIGNED_CARD_LIST, - Constants.UNASSIGNED_CARD_USER_ID); - - foreach (var card in cardQuery) - { - ret.data.Add(new Identifier - { - Id = card.Id, - IsAssociatedToUser = card.UserId_FK != Constants.UNASSIGNED_CARD_USER_ID, - UniqueId = card.CardUId, - LastUsed = card.LastUsed.DateTime - }); - } - return ret; - } - - public void ClearUnassignedIdentifiers() - { - _connection.Execute( - SQLiteProcedures.CLEAR_UNASSIGNED_CARDS, - Constants.UNASSIGNED_CARD_USER_ID); - } - - //TODO: Check time logs table on update to ensure associated cards/unique identifiers are removed/added as appropriate. - public OperationResponse UpdateUser(User user, out int userIdResult) - { - //if(user.UserId <=0) return OperationResponse.FAILED; - - var ret = OperationResponse.NONE; - var cardIds = new List(); - - //Get a list of current associated identifiers, convert into a list of Identifier Objects.. - var currentCards = - _connection.Query(SQLiteProcedures.GET_CARDS_BY_USER_ID, user.UserId) - .Select(x => new Identifier { Id = x.Id, IsAssociatedToUser = true, UniqueId = x.CardUId }); - var cardsToRemove = currentCards.Except(user.AssociatedIdentifiers).Select(x => x.Id).ToList(); - - #region GetUnique Identifiers - foreach (var card in user.AssociatedIdentifiers) - { - var existingCard = _connection.Query( - SQLiteProcedures.GET_CARDS_BY_UNIQUE_ID, card.UniqueId); - - if (!existingCard.Any()) - { - var cardInsert = new CardUniqueId { CardUId = card.UniqueId, UserId_FK = -1 }; - _connection.Insert(cardInsert); - cardIds.Add(cardInsert.Id); - if (ret < OperationResponse.CREATED) - ret = OperationResponse.CREATED; //only change it if my status supercedes. - } - else - { - cardIds.Add(existingCard.First().Id); - if (ret < OperationResponse.UPDATED) - ret = OperationResponse.UPDATED; - } - } - #endregion - - #region Update/Create User - int userId; - - if (user.UserId != -1) - { - //edit.. - _connection.Query( - SQLiteProcedures.UPDATE_USER_DETAILS, - user.FirstName, - user.LastName, - user.HoursPerWeek, - user.IsContractor, - user.UserId - ); - userId = user.UserId; - } - else - { - var userInsert = new UserIdentity - { - FirstName = user.FirstName, - LastName = user.LastName, - HoursPerWeek = user.HoursPerWeek, - IsContractor = user.IsContractor - }; - _connection.Insert(userInsert); - userId = userInsert.Id; - if (ret < OperationResponse.CREATED) - ret = OperationResponse.CREATED; - } - #endregion - - #region Update Card/Unique Id entries. - foreach (var cardId in cardIds) - { - _connection.Query( - SQLiteProcedures.UPDATE_CARD_USER_ID, - userId, cardId); - } - foreach (var card in cardsToRemove) - { - _connection.Query( - SQLiteProcedures.UPDATE_CARD_USER_ID, - -1, card); - } - #endregion - - #region Update Group Associations - - SetUserGroups(userId, user.Groups.Where(x => x.IsAssociatedToUser).ToList()); - - #endregion - - userIdResult = userId; - return ret; - } - - public LogEventResponse LogEventTime(Identifier identifier, out int logId) - { - var ret = new LogEventResponse(); - var cardIdQuery = _connection.Query( - SQLiteProcedures.GET_CARDS_BY_UNIQUE_ID, - identifier.UniqueId); - - #region Get/Insert the PK Id Identifier to associate the time log to. - var ident = new CardUniqueId(); - if (!cardIdQuery.Any()) - { - //new card, create it! - ident.UserId_FK = -1; - ident.CardUId = identifier.UniqueId; - _connection.Insert(ident); - UpdateIdentifierLastUsed(DateTimeOffset.UtcNow, ident.Id); - logId = -1; - //dont try to log any timelogs against this card, as it is unassigned to a user. - ret.ProcessResponse=OperationResponse.SUCCESS; - ret.Direction = LogDirection.UNKNOWN; - return ret; - } - else - { - //TODO: log when more than one comes back. should NEVER happen but.... - ident = cardIdQuery.First(); - } - #endregion - - // Get The User Direction (are they going in or out)? - var logDirection = GetLogDirection(ident.UserId_FK); - - #region Check the user hasnt registered an event in the last few minutes.. - - if (ident.UserId_FK != -1) - { //only check log gap if the card is associated to a user - var hysteresisThresholdMinutes = Convert.ToInt32(ConfigurationHandler.ConfigurationHandler.GetConfiguration("SwipeTimeGap") ?? "3"); - var threshold = DateTime.UtcNow.AddMinutes(0 - hysteresisThresholdMinutes); - var logs = _connection.Query( - SQLiteProcedures.GET_LOGS_IN_LAST_X_MINUTES, - threshold.Ticks, ident.UserId_FK); - _logger.Trace("Checking last swipe event gap"); - if (logs.Any()) - { - _logger.Error("Not logging event for user id: {0}, logged event within TimeGap Threshold of {1}", ident.UserId_FK, threshold); - logId = -1; - ret.ProcessResponse = OperationResponse.FAILED; - ret.Direction = LogDirection.UNKNOWN; - return ret; - } - } - - #endregion - - #region Get the current time (for swiping). and calendar week/year to help recall the data. - var logTime = DateTime.UtcNow; - var calendarWeek = GetIso8601CalendarWeek(logTime); - var year = logTime.Year; - #endregion - - var timeLog = new TimeLogDb - { - SwipeEventDateTime = DateTime.UtcNow, - UserId_FK = ident.UserId_FK, - IdentifierId = ident.Id, - Direction = logDirection, - Year = year, - CalendarWeek = calendarWeek, - Source = LogSourceDb.IDENTIFIER - }; - - _connection.Insert(timeLog); - UpdateIdentifierLastUsed(timeLog.SwipeEventDateTime, timeLog.IdentifierId); - - logId = timeLog.Id; - ret.Direction = (LogDirection)(int)logDirection; - ret.ProcessResponse = OperationResponse.SUCCESS; - return ret; - } - - /*Groups*/ - //TODO: check group name can only be entered once. - public OperationResponse CreateGroup(Group group, out int groupId) - { - var groupDb = new GroupDb { GroupName = group.Name }; - var resp = _connection.Insert(groupDb); - groupId = groupDb.GroupId; - return OperationResponse.CREATED; - } - - public List GetGroups(int userId = -1) - { - var ret = new List(); - List query; - if (userId == -1) - { - query = _connection.Query("select gp.GroupId, gp.GroupName, " + - "sum(case when gp.GroupId = ujdb.GroupId_FK then 1 else 0 end) as AssignedUserCount " + - "from GroupDb gp " + - "left join UserGroupJoinDb ujdb " + - "on ujdb.GroupId_FK = gp.GroupId " + - "group by gp.GroupId"); - } - else - { - query = - _connection.Query( - "select gdb.GroupId, gdb.GroupName, gdb.AssignedUserCount" + - " from GroupDb gdb" + - " left join UserGroupJoinDb ujdb" + - " on gdb.GroupId = ujdb.GroupId_FK" + - " where ujdb.UserId_FK = ?", - userId); - } - foreach (var group in query) - { - ret.Add(new Group - { - Id = group.GroupId, - Name = group.GroupName, - UserCount = int.Parse(group.AssignedUserCount ?? "0") - }); - } - return ret; - } - - public Group GetGroup(int groupId) - { - var query = _connection.Query("select * from GroupDb where GroupId = ?", groupId); - if (query.Any()) - { - var group = query.First(); - return new Group - { - Id = group.GroupId, - Name = group.GroupName, - UserCount = 0 - }; - } - return new Group(); - } - - public OperationResponse UpdateGroup(Group group) - { - //TODO: I would probably prefer to do this manually.... - var resp = _connection.Query("update GroupDb set GroupName=? where GroupId=?", group.Name, group.Id); - - return OperationResponse.UPDATED; - } - - public OperationResponse DeleteGroup(int groupId) - { - _connection.Delete(groupId); - return OperationResponse.DELETED; - } - - public OperationResponse DeleteLog(TimeLog log) - { - var query = _connection.Query( - "select * from TimeLogDb where Id=?", log.Id); - - if (!query.Any()) - return OperationResponse.FAILED; - - UpdateExistingLogDirections(log); - - _connection.ExecuteScalar("delete from TimeLogDb where Id=?", log.Id); - - return OperationResponse.DELETED; - } - - public OperationResponse CreateLog(TimeLog log) - { - var calendarWeek = GetIso8601CalendarWeek(log.EventTime.UtcDateTime); - var year = log.EventTime.Year; - log.CalendarWeek = calendarWeek; - log.Year = year; - var dbLog = new TimeLogDb - { - SwipeEventDateTime = log.EventTime, - Direction = (LogDirectionDb)(int)log.Direction, - Year = year, - CalendarWeek = calendarWeek, - Source = (LogSourceDb)(int)log.Source, - UserId_FK = log.UserId, - IdentifierId = ConvertSourceToIdentifierId(log.Source), - }; - #region update in/out directions for manual logs. - UpdateExistingLogDirections(log); - #endregion - //and now insert the new log. - _connection.Insert(dbLog); - return OperationResponse.CREATED; - } - - public OperationResponse UpdateLog(TimeLog log) - { - var query = _connection.Query( - "select * from TimeLogDb where Id=?", log.Id); - if(!query.Any()) - return OperationResponse.FAILED; - - if (log.CalendarWeek > 52 || log.CalendarWeek < 1) - { - log.CalendarWeek = GetIso8601CalendarWeek(log.EventTime.UtcDateTime); - } - if (log.Year < 2017) - { - log.Year = log.EventTime.Year; - } - _connection.ExecuteScalar( - "update TimeLogDb set UserId_FK=?, Direction=?,SwipeEventDateTime=?,CalendarWeek=?,Year=?,Source=? where Id=?", - log.UserId, (LogDirectionDb) (int) log.Direction, log.EventTime, log.CalendarWeek, log.Year, - (LogSourceDb) (int) log.Source, log.Id); - - return OperationResponse.UPDATED; - } - - private DateTime GetLastLogDateTime(TimeLogDb timeLog) - { - if (timeLog != null) - { - return timeLog.SwipeEventDateTime.DateTime; - } - return DateTime.MinValue; - } - - private bool GetUserState(LogDirectionDb logDirection) - { - switch (logDirection) - { - case LogDirectionDb.OUT: - return true; - default: - return false; - } - } - - private int ConvertSourceToIdentifierId(LogSource logSource) - { - switch (logSource) - { - case LogSource.UI: - return -100; - case LogSource.TRAYAPP: - return -200; - default: - return -10; - } - } - - private bool SetUserGroups(int userId, List groups) - { - var groupIds = GetGroupIds(groups.Select(x => x.Name).ToList()); - return SetUserGroups(userId, groupIds); - } - - private bool SetUserGroups(int userId, int[] groupIds) - { - //remove the existing user>group associations - _connection.Query("delete from UserGroupJoinDb where UserId_FK = ?", userId); - //add the new group associations. - _connection.InsertAll(groupIds.Select(x => new UserGroupJoinDb { GroupId_FK = x, UserId_FK = userId })); - return true; - } - - private int[] GetGroupIds(List groupNames) - { - var ret = new List(); - - foreach (var g in groupNames) - { - var query = _connection.Query("select GroupId from GroupDb where GroupName=?", g); - if (!query.Any()) continue; - var id = query.First(); - ret.Add(id.GroupId); - } - return ret.ToArray(); - } - - private List GetTimeLogList(int userId, int calendarWeek, int year) - { - var timeLogList = _connection.Query( - SQLiteProcedures.GET_TIMELOGS, - userId, calendarWeek, year); - - var timeLogs = timeLogList.Select(x => new TimeLog - { - Id = x.Id, - CalendarWeek = x.CalendarWeek, - Direction = (LogDirection)x.Direction, - IdentifierId = x.IdentifierId, - EventTime = x.SwipeEventDateTime, - UserId = x.UserId_FK, - Year = x.Year - }).OrderBy(x=>x.EventTime.UtcDateTime).ToList(); - - var dict = new Dictionary(); - var logList = new List(); - - //make sure each day of the week is accounted for in the dictionary. - foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek))) - { - dict.Add(day, new DailyLogs()); - } - - //add the logs to the respective day of the week. - foreach (var log in timeLogs.OrderBy(x=>x.EventTime)) - { - dict[log.EventTime.DayOfWeek].Logs.Add(log); - } - var logGroups = timeLogs.GroupBy(x => x.EventTime.DayOfWeek); - foreach (var group in logGroups) - { - var groupLogs = group.ToList(); - var dailyLog = new DailyLogs - { - Logs = groupLogs, - Day = group.Key, - DayOfWeek = group.Key.ToString() - }; - dailyLog.DailyTotal = CalculateDailyTotal(dailyLog); - logList.Add(dailyLog); - } - foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek))) - { - if (logList.Any(x => x.Day == day)) continue; - var dailyLog = new DailyLogs { Day = day, DayOfWeek = day.ToString() }; - logList.Add(dailyLog); - } - - foreach (var dailyCollection in dict) - { - dailyCollection.Value.DailyTotal = CalculateDailyTotal(dailyCollection.Value); - } - - return logList.OrderBy(x => ((int)x.Day + 6) % 7).ToList(); - } - - private double CalculateDailyTotal(DailyLogs dailyLogs) - { - var totalInTime = TimeSpan.FromSeconds(0); - var logs = dailyLogs.Logs.OrderBy(x => x.EventTime.UtcDateTime).ToArray(); - var totalCalcMax = IsOdd(logs.Length) ? logs.Length - 1 : logs.Length; - for (int i = 0; i < totalCalcMax; i += 2) - { - totalInTime += (logs[i + 1].EventTime - logs[i].EventTime); - } - return Math.Round(totalInTime.TotalMinutes, 2); - } - - /// - /// determines if the number is an odd or even value - /// - /// number to determine is odd or even - /// true - number is odd - private bool IsOdd(int value) - { - return value % 2 != 0; - } - - /// - /// Get the new direction for the user based on previous entry logs in the system. - /// - /// - /// If the user has not logged in today, the direction will be In. - /// If the user has logged in already today, the direction will be the opposite of the last - /// recorded log direction. ("out" if "in", "in" if "out") - /// - /// Id of the user to get the log direction of. - /// indicating what direction the new log is. - private LogDirectionDb GetLogDirection(int userId) - { - var logDirection = LogDirectionDb.UNKNOWN; - if (userId != -1) - { - var lastEntry = GetLastTimeLog(userId); - if (lastEntry != null) - { - // See if the datetime retrieved is yesterday. If yesterday, logDirection = true (in) - if (IsLogDateTimeYesterdayOrOlder(lastEntry.SwipeEventDateTime.DateTime)) - { - logDirection = LogDirectionDb.IN; - } - else - { - // we have a time log from today already, so just do the opposite of what we last did! - logDirection = InvertLogDirectionDb(lastEntry.Direction); - } - } - else - { - //assume its the first then! - logDirection = LogDirectionDb.IN; - } - } - return logDirection; - } - - private TimeLogDb GetLastTimeLog(int userId) - { - var lastEntry = _connection.Query( - SQLiteProcedures.GET_LAST_TIMELOG_DIRECTION, - userId); - if (lastEntry.Any()) - { - return lastEntry.First(); - } - return null; - } - - private void UpdateIdentifierLastUsed(DateTimeOffset dt, int cardId) - { - var res = _connection.ExecuteScalar(SQLiteProcedures.UPDATE_CARD_LAST_USED, - dt, - cardId); - } - - private List GetAssociatedIdentifiers(int userId) - { - var cards = _connection.Query( - SQLiteProcedures.GET_CARDS_BY_USER_ID, - userId); - var ret = new List(); - foreach (var card in cards) - { - ret.Add(new Identifier() - { - UniqueId = card.CardUId, - IsAssociatedToUser = true, - Id = card.Id - }); - } - return ret; - } - - /// - /// Get the calendar week of the year according to the ISO8601 standard (starts monday). - /// - /// the date to get the calendar week of. - /// the calendar week of the year in integer form (1-52) - private int GetIso8601CalendarWeek(DateTime date) - { - var day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(date); - if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) - { - date = date.AddDays(3); - } - return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, - DayOfWeek.Monday); - } - - /// - /// Check whether the specified DateTime is from yesterday or older. - /// - /// the DateTime object to check is yesterday or older - /// true - is yesterday or older. - private bool IsLogDateTimeYesterdayOrOlder(DateTime dt) - { - return dt.Date.CompareTo(DateTime.Today.Date) < 0; - } - - private User ChangeToUserObject(UserIdentity user) - { - return new User - { - UserId = user.Id, - FirstName = user.FirstName, - LastName = user.LastName, - HoursPerWeek = user.HoursPerWeek, - IsContractor = user.IsContractor - }; - } - - private void UpdateExistingLogDirections(TimeLog log) - { - //need to make this generic so that both create and delete will update the log directions.. but ARGH. - //if you want to use this as a delete, you would delete and call this, if you want to create, call this then create. - //should look at how to improve this method so that it will compensate for if the log hasnt been deleted yet, but ott? - var weekLogs = GetTimeLogList(log.UserId, log.CalendarWeek, log.Year); - - //Get the same logs of the day that the log has been entered for - var todaysLogs = weekLogs.FirstOrDefault(x => x.Day == log.EventTime.DayOfWeek); - if (todaysLogs != null) - { - //Get the days logs that are after the manually created date - var logs = todaysLogs.Logs.Where(x => x.EventTime.CompareTo(log.EventTime) >= 0).OrderBy(x => x.EventTime).ToList(); - //Update each log with the inverse progressively - var currentlogDirection = log.Direction; - for (var i = 0; i < logs.Count; i++) - { - logs[i].Direction = InvertLogDirection(currentlogDirection); - UpdateLog(logs[i]); - currentlogDirection = logs[i].Direction; - } - } - } - - private LogDirectionDb InvertLogDirectionDb(LogDirectionDb direction) - { - return (LogDirectionDb) (int) InvertLogDirection((LogDirection) (int) direction); - } - - private LogDirection InvertLogDirection(LogDirection direction) - { - switch (direction) - { - case LogDirection.IN: - return LogDirection.OUT; - case LogDirection.OUT: - return LogDirection.IN; - default: - return LogDirection.UNKNOWN; - } - } - } -} +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using Interfaces; +using SQLite.Net; +using SQLite.Net.Platform.Win32; +using SQLiteRepository.Converters; +using SQLiteRepository.Extensions; +using SQLiteRepository.Properties; + +namespace SQLiteRepository +{ + public class SQLiteRepository : IRepository + { + private readonly SQLiteConnection _connection; + private readonly ILogger _logger; + private readonly string _path; + private const string DATABASE_NAME = "flexitimedb.db"; + private const string UPGRADE_SCRIPT_PREFIX = "SQLiteRepository.UpgradeScripts."; + + public SQLiteRepository(ILogger logger) + { + _path = + new Uri(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().CodeBase), DATABASE_NAME)) + .LocalPath; + if (logger == null) throw new ArgumentNullException(nameof(logger)); + _logger = logger; + + _connection = new SQLiteConnection(new SQLitePlatformWin32(), _path); + + _connection.CreateTable(); + _connection.CreateTable(); + _connection.CreateTable(); + _connection.CreateTable(); + _connection.CreateTable(); + _connection.CreateTable(); + _connection.CreateTable(); + + _logger.Trace("Initialised SQLite Repository"); + _logger.Trace("Checking For Upgrades"); + CheckForDbUpgrade(); + } + + public UserList GetUsers(int pageNumber = -1, int pageSize = -1, int groupId = -1, SortOptions sort = SortOptions.None) + { + var ret = new UserList(); + List users = GetUserList(groupId, pageSize, pageNumber, sort); + + var userCount = GetUserCount(); + + if (pageNumber == -1 && pageSize == -1) + { + ret.PageNumber = 1; + ret.PageSize = 20; + } + else + { + ret.PageNumber = pageNumber; + ret.PageSize = pageSize; + } + + if (!users.Any()) + { + return ret; + } + + foreach (var user in users) + { + var userObj = UserConverter.ConvertToUserDto(user); + + userObj.AssociatedIdentifiers = GetAssociatedIdentifiers(user.Id); + userObj.State = GetUserState(GetLogDirection(user.Id)); + userObj.LastEventDateTime = GetLastLogDateTime(GetLastTimeLog(user.Id)); + userObj.Groups = GetGroups(user.Id); + ret.Users.Add(userObj); + } + + ret.TotalUserCount = userCount; + return ret; + } + + public UserList Search(string searchParam) + { + _logger.Trace("Searching SQLite database for the term: {0}", searchParam); + var ret = new UserList(); + searchParam = string.Format("%{0}%", searchParam); + var users = _connection.Query( + SQLiteProcedures.SEARCH_USER_LIST, + searchParam, searchParam); + + _logger.Trace("Got {0} results for term: {1}", users.Count, searchParam); + if (!users.Any()) + { + ret.PageNumber = 1; + ret.PageSize = 20; + return ret; + } + + foreach (var user in users) + { + var userObj = UserConverter.ConvertToUserDto(user); + var cards = _connection.Query( + SQLiteProcedures.GET_CARDS_BY_USER_ID, + user.Id); + + foreach (var card in cards) + { + userObj.AssociatedIdentifiers.Add(IdentifierConverter.ConvertToIdentifierDto(card)); + } + userObj.State = GetUserState(GetLogDirection(user.Id)); + ret.Users.Add(userObj); + } + ret.PageSize = 20; + ret.PageNumber = (int)Math.Ceiling((double)ret.Users.Count / (double)ret.PageSize); + + return ret; + } + + public User GetUser(int id) + { + var ret = new User(); + + try + { + var users = _connection.Query( + SQLiteProcedures.GET_USER_BY_ID, + id); + + if (!users.Any()) return ret; + + var user = users.First(); + ret = UserConverter.ConvertToUserDto(user); + ret.Groups = GetGroups(); + var usersGroups = GetGroups(user.Id); + foreach (var group in usersGroups) + { + ret.Groups.First(x => x.Id == group.Id).IsAssociatedToUser = true; + } + var cards = _connection.Query( + SQLiteProcedures.GET_CARDS_BY_USER_ID, + user.Id); + + foreach (var card in cards) + { + ret.AssociatedIdentifiers.Add(IdentifierConverter.ConvertToIdentifierDto(card)); + } + } + catch (Exception ex) + { + _logger.Error(ex, "Error in GetUser with Id: {0}", id); + ret.UserId = id; + ret.FirstName = ret.LastName = string.Empty; + ret.HoursPerWeek = -1.0f; + ret.IsContractor = false; + ret.AssociatedIdentifiers.Clear(); + } + + return ret; + } + + public TimeLogList GetTimeLogs(int userId) + { + return GetTimeLogs(userId, DateTime.UtcNow); + } + + public TimeLogList GetTimeLogs(int userId, DateTime selectedDate) + { + var ret = new TimeLogList { SelectedDate = selectedDate.Date }; + var calendarWeek = GetIso8601CalendarWeek(selectedDate); + ret.CalendarWeek = calendarWeek; + + try + { + ret.TimeLogs = GetTimeLogList(userId, calendarWeek, selectedDate.Year); + } + catch (Exception ex) + { + _logger.Error(ex, "Error in GetTimeLogs with Id: {0} and selected date: {1}, Exception: {2}", userId, selectedDate, ex); + } + + try + { + ret.HoursPerWeekMinutes = GetUserContractedHours(userId) * 60.0f; + } + catch (Exception ex) + { + _logger.Error(ex, "Error in GetUserContracterHours with Id: {0} and selected date: {1}, Exception: {2}", userId, selectedDate, ex); + } + + ret.UserInformation = GetUser(userId); + return ret; + } + + private float GetUserContractedHours(int userId) + { + var hoursQuery = _connection.Query(SQLiteProcedures.GET_USER_CONTRACTED_HOURS, userId); + if (hoursQuery.Any()) + { + return hoursQuery.First().HoursPerWeek; + } + return -1.0f; + } + + public IdentifierList GetUnassignedIdentifierList() + { + var ret = new IdentifierList(); + var cardQuery = _connection.Query( + SQLiteProcedures.GET_UNASSIGNED_CARD_LIST, + Constants.UNASSIGNED_CARD_USER_ID); + + foreach (var card in cardQuery) + { + ret.data.Add(IdentifierConverter.ConvertToIdentifierDto(card)); + // new Identifier + //{ + // Id = card.Id, + // IsAssociatedToUser = card.UserId_FK != Constants.UNASSIGNED_CARD_USER_ID, + // UniqueId = card.CardUId, + // LastUsed = card.LastUsed.DateTime + //}); + } + return ret; + } + + public void ClearUnassignedIdentifiers() + { + var unassignedIdentifiers = _connection.Query(SQLiteProcedures.GET_UNASSIGNED_CARD_LIST); + + //remove the logs from the timelog db + _connection.Query( + SQLiteProcedures.FormatInQuery(SQLiteProcedures.DELETE_TIMELOG_ENTRIES, + unassignedIdentifiers.Select(x => x.Id.ToString()).ToList())); + + //now remove the unassigned identifiers/cards + _connection.Execute( + SQLiteProcedures.CLEAR_UNASSIGNED_CARDS, + Constants.UNASSIGNED_CARD_USER_ID); + } + + public OperationResponse UpdateUser(User user, out int userIdResult) + { + var ret = OperationResponse.NONE; + //Get a list of current associated identifiers, convert into a list of Identifier Objects.. + var currentCards = + _connection.Query(SQLiteProcedures.GET_CARDS_BY_USER_ID, user.UserId) + .Select(IdentifierConverter.ConvertToIdentifierDto).ToList(); + var cardsToRemove = currentCards.Exclude(user.AssociatedIdentifiers, x => x.Id).Select(x => x.Id).ToList(); + + #region Update/Create User + int userId; + + if (user.UserId != -1) + { + UpdateUserDetails(user.FirstName, user.LastName, user.HoursPerWeek, user.IsContractor, user.UserId); + userId = user.UserId; + } + else + { + var userInsert = UserConverter.ConvertFromUserDto(user); + _connection.Insert(userInsert); + userId = userInsert.Id; + if (ret < OperationResponse.CREATED) + ret = OperationResponse.CREATED; + } + #endregion + + #region GetUnique Identifiers + + var existingCards = _connection.Query(SQLiteProcedures.FormatInQuery( + SQLiteProcedures.GET_CARDS_BY_UNIQUE_ID_LIST, + user.AssociatedIdentifiers.Select(x => x.UniqueId.ToString()).ToList())); + + foreach (var card in user.AssociatedIdentifiers) + { + if (existingCards.All(x => x.CardUId != card.UniqueId)) + { + //this card is not currently in the system.. + var cardInsert = IdentifierConverter.ConvertFromIdentifierDto(card, user.UserId); + _connection.Insert(cardInsert); + existingCards.Add(cardInsert); + if (ret < OperationResponse.CREATED) + ret = OperationResponse.CREATED; //only change it if my status supercedes. + } + } + #endregion + + #region Update Card/Unique Id entries/associations + //make sure all identifiers are associated to the right user + UpdateIdentifierUserId(existingCards.Select(x => x.Id).ToList(), userId); + + //make sure to remove all identifiers that have been deselected in edit are removed from user + UpdateIdentifierUserId(cardsToRemove, Constants.UNASSIGNED_CARD_USER_ID); + #endregion + + #region Update Group Associations + + SetUserGroups(userId, user.Groups.Where(x => x.IsAssociatedToUser).ToList()); + + #endregion + + userIdResult = userId; + return ret; + } + + public LogEventResponse LogEventTime(Identifier identifier, out int logId, DateTime logTime = default(DateTime)) + { + #region Set the LogTime before we start querying anything. + if (logTime == default(DateTime)) + { + logTime = DateTime.UtcNow; + _logger.Debug("Using own log time: {0}", logTime.ToString("o")); + } + else + { + _logger.Debug("Using supplied log time: {0}", logTime.ToString("o")); + } + #endregion + + var ret = new LogEventResponse(); + var cardIdQuery = _connection.Query( + SQLiteProcedures.GET_CARDS_BY_UNIQUE_ID, + identifier.UniqueId); + + #region Get/Insert the PK Id Identifier to associate the time log to. + var ident = new CardUniqueId(); + if (!cardIdQuery.Any()) + { + //new card, create it! + ident.UserId_FK = -1; + ident.CardUId = identifier.UniqueId; + _connection.Insert(ident); + UpdateIdentifierLastUsed(DateTimeOffset.UtcNow, ident.Id); + logId = -1; + //dont try to log any timelogs against this card, as it is unassigned to a user. + ret.ProcessResponse = OperationResponse.SUCCESS; + ret.Direction = LogDirection.UNKNOWN; + return ret; + } + + ident = cardIdQuery.First(); + _logger.Warn("More than 1 Identifier returned with ID {0}, card ids returned: {2}", + ident.CardUId, + string.Join(",", cardIdQuery.Select(x => x.CardUId).ToList())); + #endregion + + // Get The User Direction (are they going in or out)? + var logDirection = GetLogDirection(ident.UserId_FK); + + #region Check the user hasnt registered an event in the last few minutes.. + + if (ident.UserId_FK != -1) + { //only check log gap if the card is associated to a user + var hysteresisThresholdMinutes = Convert.ToInt32(ConfigurationHandler.ConfigurationHandler.GetConfiguration("SwipeTimeGap") ?? "3"); + var threshold = DateTime.UtcNow.AddMinutes(0 - hysteresisThresholdMinutes); + var logs = _connection.Query( + SQLiteProcedures.GET_LOGS_IN_LAST_X_MINUTES, + threshold.Ticks, ident.UserId_FK); + _logger.Trace("Checking last swipe event gap"); + if (logs.Any()) + { + _logger.Error("Not logging event for user id: {0}, logged event within TimeGap Threshold of {1}", ident.UserId_FK, threshold); + logId = -1; + ret.ProcessResponse = OperationResponse.FAILED; + ret.Direction = LogDirection.UNKNOWN; + return ret; + } + } + + #endregion + + #region Get the current time (for swiping). and calendar week/year to help recall the data. + + var calendarWeek = GetIso8601CalendarWeek(logTime); + var year = logTime.Year; + #endregion + + var timeLog = new TimeLogDb + { + SwipeEventDateTime = DateTime.UtcNow, + UserId_FK = ident.UserId_FK, + IdentifierId = ident.Id, + Direction = logDirection, + Year = year, + CalendarWeek = calendarWeek, + Source = LogSourceDb.IDENTIFIER + }; + + _connection.Insert(timeLog); + UpdateIdentifierLastUsed(timeLog.SwipeEventDateTime, timeLog.IdentifierId); + + logId = timeLog.Id; + ret.Direction = (LogDirection)(int)logDirection; + ret.ProcessResponse = OperationResponse.SUCCESS; + return ret; + } + + public OperationResponse CreateGroup(Group group, out int groupId) + { + var query = _connection.Query(SQLiteProcedures.GET_GROUP_BY_NAME, group.Name); + if (query.Any()) + { + groupId = query[0].GroupId; + return OperationResponse.NONE; + } + var groupDb = new GroupDb { GroupName = group.Name }; + var resp = _connection.Insert(groupDb); + groupId = groupDb.GroupId; + return OperationResponse.CREATED; + } + + public List GetGroups(int userId = -1) + { + var ret = new List(); + List query; + if (userId == -1) + { + query = _connection.Query(SQLiteProcedures.GET_GROUPS); + } + else + { + query = + _connection.Query(SQLiteProcedures.GET_GROUPS_FOR_USER, + userId); + } + foreach (var group in query) + { + ret.Add(new Group + { + Id = group.GroupId, + Name = group.GroupName, + UserCount = int.Parse(group.AssignedUserCount ?? "0") + }); + } + return ret; + } + + public Group GetGroup(int groupId) + { + var query = _connection.Query(SQLiteProcedures.GET_GROUP_BY_ID, groupId); + if (query.Any()) + { + var group = query.First(); + return new Group + { + Id = group.GroupId, + Name = group.GroupName, + UserCount = 0 + }; + } + return new Group(); + } + + public OperationResponse UpdateGroup(Group group) + { + _connection.Query(SQLiteProcedures.UPDATE_GROUP, @group.Name, @group.Id); + + return OperationResponse.UPDATED; + } + + public OperationResponse DeleteGroup(int groupId) + { + _connection.Delete(groupId); + return OperationResponse.DELETED; + } + + public OperationResponse DeleteLog(TimeLog log) + { + var query = _connection.Query( + SQLiteProcedures.GET_TIMELOG_ENTRY, log.Id); + + if (!query.Any()) + return OperationResponse.FAILED; + + UpdateExistingLogDirections(log); + + _connection.ExecuteScalar(SQLiteProcedures.DELETE_TIMELOG_ENTRY, log.Id); + + return OperationResponse.DELETED; + } + + public OperationResponse CreateLog(TimeLog log) + { + log.CalendarWeek = GetIso8601CalendarWeek(log.EventTime.UtcDateTime); + log.Year = log.EventTime.Year; + + var dbLog = TimeLogConverter.ConvertFromTimeLogDto(log); + dbLog.IdentifierId = ConvertSourceToIdentifierId(log.Source); + + #region update in/out directions for manual logs. + UpdateExistingLogDirections(log); + #endregion + //and now insert the new log. + _connection.Insert(dbLog); + return OperationResponse.CREATED; + } + + public OperationResponse UpdateLog(TimeLog log) + { + var query = _connection.Query( + SQLiteProcedures.GET_TIMELOG_ENTRY, log.Id); + + if (!query.Any()) + return OperationResponse.FAILED; + + if (log.CalendarWeek > 52 || log.CalendarWeek < 1) + { + log.CalendarWeek = GetIso8601CalendarWeek(log.EventTime.UtcDateTime); + } + if (log.Year < 2017) + { + log.Year = log.EventTime.Year; + } + _connection.ExecuteScalar( + SQLiteProcedures.UPDATE_TIMELOG_ENTRY, + log.UserId, (LogDirectionDb)(int)log.Direction, log.EventTime, log.CalendarWeek, log.Year, + (LogSourceDb)(int)log.Source, log.Id); + + return OperationResponse.UPDATED; + } + + public Policy GetPolicy() + { + var query = $"select * from {nameof(PolicyDb)}"; + var policies = _connection.Query(query); + + + return PolicyConverter.ConvertToPolicyDto(policies.OrderByDescending(x => x.Version).FirstOrDefault()); + } + + public void SavePolicy(Policy policy) + { + if (string.IsNullOrEmpty(policy.Version)) + { + policy.Version = (GetNextPolicyVersion() + 1).ToString(); + } + var policyDb = PolicyConverter.ConvertFromPolicyDto(policy); + _connection.Insert(policyDb); + } + + private int GetNextPolicyVersion() + { + var query = $"select Max({nameof(PolicyDb.Id)}) from {nameof(PolicyDb)}"; + + var id = _connection.ExecuteScalar(query); + + return id; + } + + private int GetUserCount() + { + return _connection.ExecuteScalar(SQLiteProcedures.GET_TOTAL_USER_COUNT); + } + + private List GetUserList(int groupId = -1, int pageSize = -1, int pageNumber = -1, SortOptions sort = SortOptions.None) + { + List users; + + var orderByFirst = nameof(UserIdentity.LastName); + var firstOrderDir = "ASC"; + var orderBySecond = nameof(UserIdentity.FirstName); + var secondOrderDir = "ASC"; + + if (sort != SortOptions.None) + { + switch (sort) + { + case SortOptions.FirstNameAscending: + orderByFirst = nameof(UserIdentity.FirstName); + firstOrderDir = "ASC"; + orderBySecond = nameof(UserIdentity.LastName); + secondOrderDir = "ASC"; + break; + case SortOptions.FirstNameDescending: + orderByFirst = nameof(UserIdentity.FirstName); + firstOrderDir = "DESC"; + orderBySecond = nameof(UserIdentity.LastName); + secondOrderDir = "ASC"; + break; + case SortOptions.LastNameDescending: + firstOrderDir = "DESC"; + break; + } + + } + if (pageNumber != -1 && pageSize != -1) + { + var qString = string.Format(SQLiteProcedures.GET_ALL_USERS_PAGINATE, orderByFirst, firstOrderDir, + orderBySecond, secondOrderDir, pageSize, (pageNumber - 1) * pageSize); + users = _connection.Query(qString); + } + else if (groupId != -1) + { + var qString = string.Format(SQLiteProcedures.GET_ALL_USERS_BY_GROUP, groupId, + orderByFirst, firstOrderDir, + orderBySecond, secondOrderDir); + users = + _connection.Query(qString); + } + else + { + users = _connection.Query(SQLiteProcedures.GET_ALL_USERS, + orderByFirst, firstOrderDir, + orderBySecond, secondOrderDir); + } + + return users; + } + + private void CheckForDbUpgrade() + { + var data = _connection.Query(SQLiteProcedures.GET_DB_VERSION); + if (!data.Any()) + { + //Pre-Upgrade database, need upgrading + _logger.Trace("Pre version 0.2 RC database found, performing update.."); + ExecuteUpgradeFromVersion("0.1"); //execute 0.2 upgrade scripts onwards. + } + else + { + var installedVersion = new Version(data.First().VersionNumber); + var currentVersion = new Version(AssemblyInfo.ASSEMBLY_VERSION); + if (currentVersion.CompareTo(installedVersion) > 0) //greater than 0 - current version is newer + { + _logger.Trace("Installed Database Version: {0} is older than current version {1}"); + ExecuteUpgradeFromVersion(installedVersion.ToString()); + } + } + } + + private void ExecuteUpgradeFromVersion(string installedVersion) + { + var instVers = new Version(installedVersion); + //so we have established that each script for upgrade will be .sql, so now start at lowest version and work up! + var assembly = Assembly.GetExecutingAssembly(); + var upgradeScripts = assembly.GetManifestResourceNames() + .Where(x => x.StartsWith(UPGRADE_SCRIPT_PREFIX)) + .OrderBy(x => + new Version(Path.GetFileNameWithoutExtension(x.Replace(UPGRADE_SCRIPT_PREFIX, string.Empty)))) + .Where(x => + { + var scriptVersion = + new Version(Path.GetFileNameWithoutExtension(x.Replace(UPGRADE_SCRIPT_PREFIX, string.Empty))) + .CompareTo(instVers); + return scriptVersion > 0; + }) + .ToList(); + //now have an ordered list of upgrade script files, so execute in order! + foreach (var upgradeScript in upgradeScripts) + { + using (var stream = assembly.GetManifestResourceStream(upgradeScript)) + using (var str = new StreamReader(stream)) + { + var script = str.ReadToEnd(); + _logger.Trace("Executing upgrade script with name: {0}", upgradeScript); + _connection.Execute(script); + } + } + SetDbVersion(AssemblyInfo.ASSEMBLY_VERSION); + } + + private void SetDbVersion(string vers) + { + _connection.DeleteAll(); + _connection.Insert(new DbVersion { VersionNumber = vers }); + _logger.Trace("Set Database version to: {0}", vers); + } + + private DateTime GetLastLogDateTime(TimeLogDb timeLog) + { + if (timeLog != null) + { + return timeLog.SwipeEventDateTime.DateTime; + } + return DateTime.MinValue; + } + + private bool GetUserState(LogDirectionDb logDirection) + { + switch (logDirection) + { + case LogDirectionDb.OUT: + return true; + default: + return false; + } + } + + private int ConvertSourceToIdentifierId(LogSource logSource) + { + switch (logSource) + { + case LogSource.UI: + return -100; + case LogSource.TRAYAPP: + return -200; + default: + return -10; + } + } + + private bool SetUserGroups(int userId, List groups) + { + var groupIds = GetGroupIds(groups.Select(x => x.Name).ToList()); + return SetUserGroups(userId, groupIds); + } + + private bool SetUserGroups(int userId, int[] groupIds) + { + //remove the existing user>group associations + _connection.Query("delete from UserGroupJoinDb where UserId_FK = ?", userId); + //add the new group associations. + _connection.InsertAll(groupIds.Select(x => new UserGroupJoinDb { GroupId_FK = x, UserId_FK = userId })); + return true; + } + + private int[] GetGroupIds(List groupNames) + { + var ret = new List(); + + foreach (var g in groupNames) + { + var query = _connection.Query("select GroupId from GroupDb where GroupName=?", g); + if (!query.Any()) continue; + var id = query.First(); + ret.Add(id.GroupId); + } + return ret.ToArray(); + } + + private List GetTimeLogList(int userId, int calendarWeek, int year) + { + var timeLogList = _connection.Query( + SQLiteProcedures.GET_TIMELOGS, + userId, calendarWeek, year); + + var timeLogs = timeLogList.Select(x => new TimeLog + { + Id = x.Id, + CalendarWeek = x.CalendarWeek, + Direction = (LogDirection)x.Direction, + IdentifierId = x.IdentifierId, + EventTime = x.SwipeEventDateTime, + UserId = x.UserId_FK, + Year = x.Year + }).OrderBy(x => x.EventTime.UtcDateTime).ToList(); + + var dict = new Dictionary(); + var logList = new List(); + + //make sure each day of the week is accounted for in the dictionary. + foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek))) + { + dict.Add(day, new DailyLogs()); + } + + //add the logs to the respective day of the week. + foreach (var log in timeLogs.OrderBy(x => x.EventTime)) + { + dict[log.EventTime.DayOfWeek].Logs.Add(log); + } + var logGroups = timeLogs.GroupBy(x => x.EventTime.DayOfWeek); + foreach (var group in logGroups) + { + var groupLogs = group.ToList(); + var dailyLog = new DailyLogs + { + Logs = groupLogs, + Day = group.Key, + DayOfWeek = group.Key.ToString() + }; + dailyLog.DailyTotal = CalculateDailyTotal(dailyLog); + logList.Add(dailyLog); + } + foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek))) + { + if (logList.Any(x => x.Day == day)) continue; + var dailyLog = new DailyLogs { Day = day, DayOfWeek = day.ToString() }; + logList.Add(dailyLog); + } + + foreach (var dailyCollection in dict) + { + dailyCollection.Value.DailyTotal = CalculateDailyTotal(dailyCollection.Value); + } + + return logList.OrderBy(x => ((int)x.Day + 6) % 7).ToList(); + } + + private double CalculateDailyTotal(DailyLogs dailyLogs) + { + var totalInTime = TimeSpan.FromSeconds(0); + var logs = dailyLogs.Logs.OrderBy(x => x.EventTime.UtcDateTime).ToArray(); + var totalCalcMax = IsOdd(logs.Length) ? logs.Length - 1 : logs.Length; + for (int i = 0; i < totalCalcMax; i += 2) + { + totalInTime += (logs[i + 1].EventTime - logs[i].EventTime); + } + return Math.Round(totalInTime.TotalMinutes, 2); + } + + /// + /// determines if the number is an odd or even value + /// + /// number to determine is odd or even + /// true - number is odd + private bool IsOdd(int value) + { + return value % 2 != 0; + } + + /// + /// Get the new direction for the user based on previous entry logs in the system. + /// + /// + /// If the user has not logged in today, the direction will be In. + /// If the user has logged in already today, the direction will be the opposite of the last + /// recorded log direction. ("out" if "in", "in" if "out") + /// + /// Id of the user to get the log direction of. + /// indicating what direction the new log is. + private LogDirectionDb GetLogDirection(int userId) + { + var logDirection = LogDirectionDb.UNKNOWN; + if (userId != -1) + { + var lastEntry = GetLastTimeLog(userId); + if (lastEntry != null) + { + // See if the datetime retrieved is yesterday. If yesterday, logDirection = true (in) + if (IsLogDateTimeYesterdayOrOlder(lastEntry.SwipeEventDateTime.DateTime)) + { + logDirection = LogDirectionDb.IN; + } + else + { + // we have a time log from today already, so just do the opposite of what we last did! + logDirection = LogDirectionConverter.InvertLogDirectionDb(lastEntry.Direction); + } + } + else + { + //assume its the first then! + logDirection = LogDirectionDb.IN; + } + } + return logDirection; + } + + private TimeLogDb GetLastTimeLog(int userId) + { + var lastEntry = _connection.Query( + SQLiteProcedures.GET_LAST_TIMELOG_DIRECTION, + userId); + if (lastEntry.Any()) + { + return lastEntry.First(); + } + return null; + } + + private void UpdateIdentifierLastUsed(DateTimeOffset dt, int cardId) + { + _connection.ExecuteScalar(SQLiteProcedures.UPDATE_CARD_LAST_USED, + dt, + cardId); + } + + private List GetAssociatedIdentifiers(int userId) + { + var cards = _connection.Query( + SQLiteProcedures.GET_CARDS_BY_USER_ID, + userId); + var ret = new List(); + foreach (var card in cards) + { + ret.Add(new Identifier() + { + UniqueId = card.CardUId, + IsAssociatedToUser = true, + Id = card.Id + }); + } + return ret; + } + + /// + /// Get the calendar week of the year according to the ISO8601 standard (starts monday). + /// + /// the date to get the calendar week of. + /// the calendar week of the year in integer form (1-52) + private int GetIso8601CalendarWeek(DateTime date) + { + var day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(date); + if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) + { + date = date.AddDays(3); + } + return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, + DayOfWeek.Monday); + } + + /// + /// Check whether the specified DateTime is from yesterday or older. + /// + /// the DateTime object to check is yesterday or older + /// true - is yesterday or older. + private bool IsLogDateTimeYesterdayOrOlder(DateTime dt) + { + return dt.Date.CompareTo(DateTime.Today.Date) < 0; + } + + private void UpdateExistingLogDirections(TimeLog log) + { + //need to make this generic so that both create and delete will update the log directions.. but ARGH. + //if you want to use this as a delete, you would delete and call this, if you want to create, call this then create. + //should look at how to improve this method so that it will compensate for if the log hasnt been deleted yet, but ott? + var weekLogs = GetTimeLogList(log.UserId, log.CalendarWeek, log.Year); + + //Get the same logs of the day that the log has been entered for + var todaysLogs = weekLogs.FirstOrDefault(x => x.Day == log.EventTime.DayOfWeek); + if (todaysLogs != null) + { + //Get the days logs that are after the manually created date + var logs = todaysLogs.Logs.Where(x => x.EventTime.CompareTo(log.EventTime) >= 0).OrderBy(x => x.EventTime).ToList(); + //Update each log with the inverse progressively + var currentlogDirection = log.Direction; + for (var i = 0; i < logs.Count; i++) + { + logs[i].Direction = LogDirectionConverter.InvertLogDirection(currentlogDirection); + UpdateLog(logs[i]); + currentlogDirection = logs[i].Direction; + } + } + } + + private void UpdateIdentifierUserId(List cardsToUpdate, int userId) + { + foreach (var card in cardsToUpdate) + { + _connection.Query( + SQLiteProcedures.UPDATE_CARD_USER_ID, + userId, card); + } + } + + private void UpdateUserDetails(string firstName, string lastName, float hoursPerWeek, bool isContractor, + int userId) + { + _connection.Query( + SQLiteProcedures.UPDATE_USER_DETAILS, + firstName, + lastName, + hoursPerWeek, + isContractor, + userId + ); + } + } +} diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/SQLiteRepository.csproj b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/SQLiteRepository.csproj index 46517fc..5ef82e2 100644 --- a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/SQLiteRepository.csproj +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/SQLiteRepository.csproj @@ -1,124 +1,132 @@ - - - - - Debug - AnyCPU - {B3510C81-F069-48A2-B826-EBE0CE7AB0B2} - Library - Properties - SQLiteRepository - SQLiteRepository - v4.5.2 - 512 - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - bin\DebugInstallers\ - DEBUG;TRACE - full - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - bin\ReleaseInstallers\ - TRACE - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - - - - ..\packages\SQLite.Net.Core-PCL.3.1.1\lib\portable-win8+net45+wp8+wpa81+MonoAndroid1+MonoTouch1\SQLite.Net.dll - True - - - ..\packages\SQLite.Net-PCL.3.1.1\lib\net40\SQLite.Net.Platform.Generic.dll - True - - - ..\packages\SQLite.Net-PCL.3.1.1\lib\net4\SQLite.Net.Platform.Win32.dll - True - - - - - - ..\packages\System.Data.SQLite.Core.1.0.104.0\lib\net451\System.Data.SQLite.dll - True - - - - - - - - - - - - - - - - - - - - - - - - - {115250F6-F8C4-4F9B-A15F-251EA258D963} - ConfigurationHandler - - - {B7347B72-E208-423A-9D99-723B558EA3D7} - Interfaces - - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + + Debug + AnyCPU + {B3510C81-F069-48A2-B826-EBE0CE7AB0B2} + Library + Properties + SQLiteRepository + SQLiteRepository + v4.5.2 + 512 + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\DebugInstallers\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + bin\ReleaseInstallers\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\SQLite.Net.Core-PCL.3.1.1\lib\portable-win8+net45+wp8+wpa81+MonoAndroid1+MonoTouch1\SQLite.Net.dll + True + + + ..\packages\SQLite.Net-PCL.3.1.1\lib\net40\SQLite.Net.Platform.Generic.dll + True + + + ..\packages\SQLite.Net-PCL.3.1.1\lib\net4\SQLite.Net.Platform.Win32.dll + True + + + + + + ..\packages\System.Data.SQLite.Core.1.0.104.0\lib\net451\System.Data.SQLite.dll + True + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {115250F6-F8C4-4F9B-A15F-251EA258D963} + ConfigurationHandler + + + {B7347B72-E208-423A-9D99-723B558EA3D7} + Interfaces + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + --> \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/UpgradeScripts/0.2.sql b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/UpgradeScripts/0.2.sql index 5eeccd7..8eb6cd4 100644 --- a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/UpgradeScripts/0.2.sql +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/UpgradeScripts/0.2.sql @@ -1 +1,3 @@ -insert into GroupDb values ((select max(groupId) from GroupDb)+1,'Archived',0) \ No newline at end of file +insert into GroupDb(GroupId, GroupName, AssignedUserCount) +select (select max(GroupId) from GroupDb)+1, 'Archived', 0 +WHERE NOT EXISTS(select * from GroupDb where GroupName='Archived'); \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/packages.config b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/packages.config index 633c6d1..03b7b99 100644 --- a/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/packages.config +++ b/DataCenter_Windows/WindowsDataCenter/SQLiteRepository/packages.config @@ -1,6 +1,6 @@ - - - - - + + + + + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/App.config b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/App.config index ebf5f25..ecb9bb0 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/App.config +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/App.config @@ -1,41 +1,53 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/App_Start/Ninject.Web.Common.cs b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/App_Start/Ninject.Web.Common.cs new file mode 100644 index 0000000..72d1261 --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/App_Start/Ninject.Web.Common.cs @@ -0,0 +1,66 @@ +[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(WindowsDataCenter.App_Start.NinjectWebCommon), "Start")] +[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(WindowsDataCenter.App_Start.NinjectWebCommon), "Stop")] + +namespace WindowsDataCenter.App_Start +{ + using System; + using System.Web; + + using Microsoft.Web.Infrastructure.DynamicModuleHelper; + + using Ninject; + using Ninject.Web.Common; + using Ninject.Web.Common.WebHost; + + public static class NinjectWebCommon + { + private static readonly Bootstrapper bootstrapper = new Bootstrapper(); + + /// + /// Starts the application + /// + public static void Start() + { + DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); + DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); + bootstrapper.Initialize(CreateKernel); + } + + /// + /// Stops the application. + /// + public static void Stop() + { + bootstrapper.ShutDown(); + } + + /// + /// Creates the kernel that will manage your application. + /// + /// The created kernel. + private static IKernel CreateKernel() + { + var kernel = new StandardKernel(); + try + { + kernel.Bind>().ToMethod(ctx => () => new Bootstrapper().Kernel); + kernel.Bind().To(); + RegisterServices(kernel); + return kernel; + } + catch + { + kernel.Dispose(); + throw; + } + } + + /// + /// Load your modules or register your services here! + /// + /// The kernel. + private static void RegisterServices(IKernel kernel) + { + } + } +} \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/CardData.cs b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/CardData.cs index eee79f0..a019bea 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/CardData.cs +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/CardData.cs @@ -1,7 +1,10 @@ -namespace WindowsDataCenter -{ - public class CardData - { - public string CardUId { get; set; } - } +using System; + +namespace WindowsDataCenter +{ + public class CardData + { + public DateTime? UtcTimeStamp { get; set; } + public string CardUId { get; set; } + } } \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Controllers/ApplicationController.cs b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Controllers/ApplicationController.cs index 8b3fc15..ce47313 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Controllers/ApplicationController.cs +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Controllers/ApplicationController.cs @@ -1,26 +1,51 @@ -using System.Reflection; -using System.Web.Http; -using Interfaces; - -namespace WindowsDataCenter -{ - [RoutePrefix("api/app")] - public class ApplicationController:ApiController - { - [Route("")] - public IHttpActionResult GetAppDetails() - { - var ninjectHelper = NinjectHelper.GetInstance(); - var appDetails = new AppDetails - { - ApplicationName = "Flexitime Tracker", - DataBaseProvider = ninjectHelper.Get().GetType().ToString(), - LoggerProvider = ninjectHelper.Get().GetType().ToString(), - Version = Assembly.GetEntryAssembly().GetName().Version.ToString(), - ErrorEmailAddress = ConfigurationHandler.ConfigurationHandler.GetConfiguration("BugSubmissionEmailAddress") ?? "NONE" - }; - - return Ok(appDetails); - } - } -} +using System.Reflection; +using System.Web.Http; +using WindowsDataCenter.Helpers; +using Interfaces; + +namespace WindowsDataCenter +{ + [RoutePrefix("api/app")] + public class ApplicationController:ApiController + { + private IRepository _repo; + public ApplicationController(IRepository repo) + { + _repo = repo; + } + + [Route("")] + public IHttpActionResult GetAppDetails() + { + var ninjectHelper = NinjectHelper.GetInstance(); + var appDetails = new AppDetails + { + ApplicationName = "Flexitime Tracker", + DataBaseProvider = ninjectHelper.Get().GetType().ToString(), + LoggerProvider = ninjectHelper.Get().GetType().ToString(), + Version = Assembly.GetEntryAssembly().GetName().Version.ToString(), + ErrorEmailAddress = ConfigurationHandler.ConfigurationHandler.GetConfiguration("BugSubmissionEmailAddress") ?? "NONE" + }; + + return Ok(appDetails); + } + + [Route("policy")] + [HttpGet] + [CacheControl(MaxAge = 0)] + public IHttpActionResult GetPolicy() + { + Policy policy = _repo.GetPolicy(); + return Json(policy); + } + + [Route("policy")] + [HttpPost] + [CacheControl(MaxAge = 0)] + public IHttpActionResult SavePolicy(Policy policy) + { + _repo.SavePolicy(policy); + return Ok(new {}); //empty to ensure ajax triggers Success.. + } + } +} diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Controllers/SwipeDataController.cs b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Controllers/SwipeDataController.cs index ed31a9f..91e5c96 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Controllers/SwipeDataController.cs +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Controllers/SwipeDataController.cs @@ -1,47 +1,53 @@ -using System; -using System.Net; -using System.Net.Http; -using System.Web.Http; -using Interfaces; - -namespace WindowsDataCenter -{ - /// - /// - /// - [RoutePrefix("api/swipedata")] - public class SwipeDataController : ApiController - { - private readonly IRepository _repo; - private readonly ILogger _logger; - - /// - /// - /// - /// - /// - public SwipeDataController(IRepository repo, ILogger logger) - { - if(repo == null) throw new ArgumentNullException(nameof(repo)); - _repo = repo; - if(logger == null) throw new ArgumentNullException(nameof(logger)); - _logger = logger; - } - - /// - /// - /// - /// - /// - [HttpPost] - [Route("")] - public IHttpActionResult PostData([FromBody] CardData cData) - { - int logId; - var resp = _repo.LogEventTime(new Identifier {UniqueId = cData.CardUId}, out logId); - _logger.Trace("Received new \"Swipe Event\" for UId: {0} at {1}, direction is : {2}", cData.CardUId, - DateTime.UtcNow, resp.Direction); - return Ok(new {Id = logId, resp.Direction}); - } - } +using System; +using System.Net; +using System.Net.Http; +using System.Web.Http; +using Interfaces; + +namespace WindowsDataCenter +{ + /// + /// + /// + [RoutePrefix("api/swipedata")] + public class SwipeDataController : ApiController + { + private readonly IRepository _repo; + private readonly ILogger _logger; + + /// + /// + /// + /// + /// + public SwipeDataController(IRepository repo, ILogger logger) + { + if(repo == null) throw new ArgumentNullException(nameof(repo)); + _repo = repo; + if(logger == null) throw new ArgumentNullException(nameof(logger)); + _logger = logger; + } + + /// + /// + /// + /// + /// + [HttpPost] + [Route("")] + public IHttpActionResult PostData([FromBody] CardData cData) + { + int logId; + + var id = new Identifier {UniqueId = cData.CardUId}; + + var resp = cData.UtcTimeStamp.HasValue + ? _repo.LogEventTime(id, out logId, cData.UtcTimeStamp.Value) + : _repo.LogEventTime(id, out logId); + + _logger.Trace("Received new \"Swipe Event\" for UId: {0} at {1}, direction is : {2}", cData.CardUId, + DateTime.UtcNow, resp.Direction); + return Ok(new {Id = logId, resp.Direction}); + } + } } \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Controllers/UsersController.cs b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Controllers/UsersController.cs index 763ffe6..88d73dc 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Controllers/UsersController.cs +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Controllers/UsersController.cs @@ -30,17 +30,18 @@ namespace WindowsDataCenter public IHttpActionResult GetUsers([FromUri] string query = "" , [FromUri] int pageSize = -1 , [FromUri] int pageNumber = -1 - , [FromUri] int groupId = -1) + , [FromUri] int groupId = -1 + , [FromUri] SortOptions sort = SortOptions.None) { - _logger.Trace("GetUsers called with arguments >> query: {0}, pageSize: {1}, pageNumber: {2}, groupFilter: {3}", query, pageSize, pageNumber, groupId); + _logger.Trace("GetUsers called with arguments >> query: {0}, pageSize: {1}, pageNumber: {2}, groupFilter: {3}, sort: {4}", query, pageSize, pageNumber, groupId, sort); pageNumber = pageNumber == -1 ? 1 : pageNumber; pageSize = GetPageSize(pageSize); var userList = query != string.Empty ? _repo.Search(query) : groupId != -1 - ? _repo.GetUsers(groupId: groupId) - : _repo.GetUsers(pageNumber, pageSize); + ? _repo.GetUsers(groupId: groupId, sort:sort) + : _repo.GetUsers(pageNumber, pageSize, sort:sort); _logger.Trace("Got UserList from Repository, UserCount: {0}", userList.UserCount); if (query != string.Empty) { @@ -57,6 +58,7 @@ namespace WindowsDataCenter userList.PageNumber = pageNumber; userList.PageSize = pageSize; + userList.SelectedSortOption = sort; _logger.Trace("Returning UserList from GetUsers."); var msg = Request.CreateResponse(HttpStatusCode.OK, userList); @@ -93,8 +95,7 @@ namespace WindowsDataCenter { int userId; _repo.UpdateUser(user, out userId); - //TODO return ID. - return ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent("unknownIdTODO")}); + return ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(userId.ToString())}); } [HttpPost] diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/ApiGroup.cshtml b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/ApiGroup.cshtml index 7cfdde8..b3e3a8a 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/ApiGroup.cshtml +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/ApiGroup.cshtml @@ -1,28 +1,28 @@ -@using System.Web.Http.Description -@using DalSoft.WebApi.HelpPage -@model IGrouping - -

@Model.Key

- - - - - - @foreach (var api in Model) - { - - - - - } - +@using System.Web.Http.Description +@using DalSoft.WebApi.HelpPage +@model IGrouping + +

@Model.Key

+
APIDescription
@api.HttpMethod.Method @api.RelativePath - @if (api.Documentation !=null) - { -

@api.Documentation

- } - else - { -

No documentation available.

- } -
+ + + + + @foreach (var api in Model) + { + + + + + } +
APIDescription
@api.HttpMethod.Method @api.RelativePath + @if (api.Documentation !=null) + { +

@api.Documentation

+ } + else + { +

No documentation available.

+ } +
\ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/HelpPageApiModel.cshtml b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/HelpPageApiModel.cshtml index 37bb2eb..435629c 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/HelpPageApiModel.cshtml +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/HelpPageApiModel.cshtml @@ -1,49 +1,49 @@ -@using System.Collections.Generic -@using System.Net.Http.Headers -@using DalSoft.WebApi.HelpPage.Models - -@model HelpPageApiModel - -@{ - var description = Model.ApiDescription; - var hasParameters = description.ParameterDescriptions.Count > 0; - var hasRequestSamples = Model.SampleRequests.Count > 0; - var hasResponseSamples = Model.SampleResponses.Count > 0; -} -

@description.HttpMethod.Method @description.RelativePath

-
- @{ - if (description.Documentation != null) - { -

@description.Documentation

- } - else - { -

No documentation available.

- } - - if (hasParameters || hasRequestSamples) - { -

Request Information

- if (hasParameters) - { -

Parameters

- @Include("Parameters.cshtml", Model, typeof(HelpPageApiModel)) - } - if (hasRequestSamples) - { -

Request body formats

- var ModelSamples = Model.SampleRequests; - @Include("Samples.cshtml", ModelSamples, typeof(IDictionary)) - } - } - - if (hasResponseSamples) - { -

Response Information

-

Response body formats

- var ModelSamples = Model.SampleResponses; - @Include("Samples.cshtml", ModelSamples, typeof(IDictionary)) - } -} +@using System.Collections.Generic +@using System.Net.Http.Headers +@using DalSoft.WebApi.HelpPage.Models + +@model HelpPageApiModel + +@{ + var description = Model.ApiDescription; + var hasParameters = description.ParameterDescriptions.Count > 0; + var hasRequestSamples = Model.SampleRequests.Count > 0; + var hasResponseSamples = Model.SampleResponses.Count > 0; +} +

@description.HttpMethod.Method @description.RelativePath

+
+ @{ + if (description.Documentation != null) + { +

@description.Documentation

+ } + else + { +

No documentation available.

+ } + + if (hasParameters || hasRequestSamples) + { +

Request Information

+ if (hasParameters) + { +

Parameters

+ @Include("Parameters.cshtml", Model, typeof(HelpPageApiModel)) + } + if (hasRequestSamples) + { +

Request body formats

+ var ModelSamples = Model.SampleRequests; + @Include("Samples.cshtml", ModelSamples, typeof(IDictionary)) + } + } + + if (hasResponseSamples) + { +

Response Information

+

Response body formats

+ var ModelSamples = Model.SampleResponses; + @Include("Samples.cshtml", ModelSamples, typeof(IDictionary)) + } +}
\ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/Parameters.cshtml b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/Parameters.cshtml index 1a45b7c..90f8461 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/Parameters.cshtml +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/Parameters.cshtml @@ -1,55 +1,55 @@ -@using System.Collections.ObjectModel -@using System.Threading -@using System.Web.Http.Description - -@{ Collection parameters = Model.ApiDescription.ParameterDescriptions; } -@if (parameters.Count > 0) -{ - - - - - - @{ - foreach (ApiParameterDescription parameter in parameters) - { - var parameterDocumentation = parameter.Documentation ?? "No documentation available."; - - // Don't show CancellationToken because it's a special parameter - if (!typeof (CancellationToken).IsAssignableFrom(parameter.ParameterDescriptor.ParameterType)) - { - - - - - - } - } - } - -
NameDescriptionAdditional information
@parameter.Name -

@parameterDocumentation

-
- @{ - switch (parameter.Source) - { - case ApiParameterSource.FromBody: -

Define this parameter in the request body. -

- break; - case ApiParameterSource.FromUri: -

Define this parameter in the request URI. -

- break; - case ApiParameterSource.Unknown: - default: -

None.

- break; - } - } -
-} -else -{ -

None.

+@using System.Collections.ObjectModel +@using System.Threading +@using System.Web.Http.Description + +@{ Collection parameters = Model.ApiDescription.ParameterDescriptions; } +@if (parameters.Count > 0) +{ + + + + + + @{ + foreach (ApiParameterDescription parameter in parameters) + { + var parameterDocumentation = parameter.Documentation ?? "No documentation available."; + + // Don't show CancellationToken because it's a special parameter + if (!typeof (CancellationToken).IsAssignableFrom(parameter.ParameterDescriptor.ParameterType)) + { + + + + + + } + } + } + +
NameDescriptionAdditional information
@parameter.Name +

@parameterDocumentation

+
+ @{ + switch (parameter.Source) + { + case ApiParameterSource.FromBody: +

Define this parameter in the request body. +

+ break; + case ApiParameterSource.FromUri: +

Define this parameter in the request URI. +

+ break; + case ApiParameterSource.Unknown: + default: +

None.

+ break; + } + } +
+} +else +{ +

None.

} \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/Samples.cshtml b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/Samples.cshtml index c76f82d..b4d4593 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/Samples.cshtml +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/DisplayTemplates/Samples.cshtml @@ -1,37 +1,37 @@ -@using System.Net.Http.Headers -@using DalSoft.WebApi.HelpPage.SampleGeneration -@model IDictionary - -@{ - // Group the samples into a single tab if they are the same. - var samples = Model.GroupBy(x => x.Value).ToDictionary(x => string.Join(", ", x.Select(m => m.Key.ToString()).ToArray()), x => x.Key); - var mediaTypes = samples.Keys; -} -
- @{ - foreach (var mediaType in mediaTypes) - { -

@mediaType

-
- Sample: - @{ var sample = samples[mediaType]; } - @if (sample == null) - { -

Sample not available.

- } - else if (sample is TextSample) - { -
@(((TextSample)sample).Text)
- } - else if (sample is ImageSample) - { - - } - else if (sample is InvalidSample) - { -
@(((InvalidSample)sample).ErrorMessage)
- } -
- } - } +@using System.Net.Http.Headers +@using DalSoft.WebApi.HelpPage.SampleGeneration +@model IDictionary + +@{ + // Group the samples into a single tab if they are the same. + var samples = Model.GroupBy(x => x.Value).ToDictionary(x => string.Join(", ", x.Select(m => m.Key.ToString()).ToArray()), x => x.Key); + var mediaTypes = samples.Keys; +} +
+ @{ + foreach (var mediaType in mediaTypes) + { +

@mediaType

+
+ Sample: + @{ var sample = samples[mediaType]; } + @if (sample == null) + { +

Sample not available.

+ } + else if (sample is TextSample) + { +
@(((TextSample)sample).Text)
+ } + else if (sample is ImageSample) + { + + } + else if (sample is InvalidSample) + { +
@(((InvalidSample)sample).ErrorMessage)
+ } +
+ } + }
\ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/HelpPage.css b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/HelpPage.css index aff2230..488544c 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/HelpPage.css +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/HelpPage.css @@ -1,134 +1,134 @@ -.help-page h1, -.help-page .h1, -.help-page h2, -.help-page .h2, -.help-page h3, -.help-page .h3, -#body.help-page, -.help-page-table th, -.help-page-table pre, -.help-page-table p { - font-family: "Segoe UI Light", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif; -} - -.help-page pre.wrapped { - white-space: -moz-pre-wrap; - white-space: -pre-wrap; - white-space: -o-pre-wrap; - white-space: pre-wrap; -} - -.help-page .warning-message-container { - margin-top: 20px; - padding: 0 10px; - color: #525252; - background: #EFDCA9; - border: 1px solid #CCCCCC; -} - -.help-page-table { - width: 100%; - border-collapse: collapse; - text-align: left; - margin: 0px 0px 20px 0px; - border-top: 1px solid #D4D4D4; -} - -.help-page-table th { - text-align: left; - font-weight: bold; - border-bottom: 1px solid #D4D4D4; - padding: 5px 6px 5px 6px; -} - -.help-page-table td { - border-bottom: 1px solid #D4D4D4; - padding: 10px 8px 10px 8px; - vertical-align: top; -} - -.help-page-table pre, -.help-page-table p { - margin: 0px; - padding: 0px; - font-family: inherit; - font-size: 100%; -} - -.help-page-table tbody tr:hover td { - background-color: #F3F3F3; -} - -.help-page a:hover { - background-color: transparent; -} - -.help-page .sample-header { - border: 2px solid #D4D4D4; - background: #00497E; - color: #FFFFFF; - padding: 8px 15px; - border-bottom: none; - display: inline-block; - margin: 10px 0px 0px 0px; -} - -.help-page .sample-content { - display: block; - border-width: 0; - padding: 15px 20px; - background: #FFFFFF; - border: 2px solid #D4D4D4; - margin: 0px 0px 10px 0px; -} - -.help-page .api-name { - width: 40%; -} - -.help-page .api-documentation { - width: 60%; -} - -.help-page .parameter-name { - width: 20%; -} - -.help-page .parameter-documentation { - width: 40%; -} - -.help-page .parameter-type { - width: 20%; -} - -.help-page .parameter-annotations { - width: 20%; -} - -.help-page h1, -.help-page .h1 { - font-size: 36px; - line-height: normal; -} - -.help-page h2, -.help-page .h2 { - font-size: 24px; -} - -.help-page h3, -.help-page .h3 { - font-size: 20px; -} - -#body.help-page { - font-size: 14px; - line-height: 143%; - color: #333; -} - -.help-page a { - color: #0000EE; - text-decoration: none; -} +.help-page h1, +.help-page .h1, +.help-page h2, +.help-page .h2, +.help-page h3, +.help-page .h3, +#body.help-page, +.help-page-table th, +.help-page-table pre, +.help-page-table p { + font-family: "Segoe UI Light", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif; +} + +.help-page pre.wrapped { + white-space: -moz-pre-wrap; + white-space: -pre-wrap; + white-space: -o-pre-wrap; + white-space: pre-wrap; +} + +.help-page .warning-message-container { + margin-top: 20px; + padding: 0 10px; + color: #525252; + background: #EFDCA9; + border: 1px solid #CCCCCC; +} + +.help-page-table { + width: 100%; + border-collapse: collapse; + text-align: left; + margin: 0px 0px 20px 0px; + border-top: 1px solid #D4D4D4; +} + +.help-page-table th { + text-align: left; + font-weight: bold; + border-bottom: 1px solid #D4D4D4; + padding: 5px 6px 5px 6px; +} + +.help-page-table td { + border-bottom: 1px solid #D4D4D4; + padding: 10px 8px 10px 8px; + vertical-align: top; +} + +.help-page-table pre, +.help-page-table p { + margin: 0px; + padding: 0px; + font-family: inherit; + font-size: 100%; +} + +.help-page-table tbody tr:hover td { + background-color: #F3F3F3; +} + +.help-page a:hover { + background-color: transparent; +} + +.help-page .sample-header { + border: 2px solid #D4D4D4; + background: #00497E; + color: #FFFFFF; + padding: 8px 15px; + border-bottom: none; + display: inline-block; + margin: 10px 0px 0px 0px; +} + +.help-page .sample-content { + display: block; + border-width: 0; + padding: 15px 20px; + background: #FFFFFF; + border: 2px solid #D4D4D4; + margin: 0px 0px 10px 0px; +} + +.help-page .api-name { + width: 40%; +} + +.help-page .api-documentation { + width: 60%; +} + +.help-page .parameter-name { + width: 20%; +} + +.help-page .parameter-documentation { + width: 40%; +} + +.help-page .parameter-type { + width: 20%; +} + +.help-page .parameter-annotations { + width: 20%; +} + +.help-page h1, +.help-page .h1 { + font-size: 36px; + line-height: normal; +} + +.help-page h2, +.help-page .h2 { + font-size: 24px; +} + +.help-page h3, +.help-page .h3 { + font-size: 20px; +} + +#body.help-page { + font-size: 14px; + line-height: 143%; + color: #333; +} + +.help-page a { + color: #0000EE; + text-decoration: none; +} diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/api.cshtml b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/api.cshtml index 8c58cd7..f10b331 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/api.cshtml +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/api.cshtml @@ -1,28 +1,28 @@ -@using DalSoft.WebApi.HelpPage.Models -@model HelpPageApiModel - -@{ - var description = Model.ApiDescription; - var title = description.HttpMethod.Method + " " + description.RelativePath; -} - - - - @title - - - -
- -
- @Include("HelpPageApiModel.cshtml", Model, typeof(HelpPageApiModel)) -
-
- - +@using DalSoft.WebApi.HelpPage.Models +@model HelpPageApiModel + +@{ + var description = Model.ApiDescription; + var title = description.HttpMethod.Method + " " + description.RelativePath; +} + + + + @title + + + +
+ +
+ @Include("HelpPageApiModel.cshtml", Model, typeof(HelpPageApiModel)) +
+
+ + diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/index.cshtml b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/index.cshtml index e4ccb5b..4bf1778 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/index.cshtml +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/Help/DalSoft.WebApi.HelpPage.Views/index.cshtml @@ -1,43 +1,43 @@ -@using System.Web.Http.Description -@using System.Collections.ObjectModel -@using System.Linq -@model Collection - -@{ - ViewBag.Title = "ASP.NET Web API Help Page"; - - // Group APIs by controller - ILookup apiGroups = Model.ToLookup(api => api.ActionDescriptor.ControllerDescriptor.ControllerName); -} - - - - @ViewBag.Title - - - -
-
-
-

@ViewBag.Title

-
-
-
-
- -
- @foreach (IGrouping controllerGroup in apiGroups) - { - @Include("ApiGroup.cshtml", controllerGroup, typeof (IGrouping)) - } -
-
- - +@using System.Web.Http.Description +@using System.Collections.ObjectModel +@using System.Linq +@model Collection + +@{ + ViewBag.Title = "ASP.NET Web API Help Page"; + + // Group APIs by controller + ILookup apiGroups = Model.ToLookup(api => api.ActionDescriptor.ControllerDescriptor.ControllerName); +} + + + + @ViewBag.Title + + + +
+
+
+

@ViewBag.Title

+
+
+
+
+ +
+ @foreach (IGrouping controllerGroup in apiGroups) + { + @Include("ApiGroup.cshtml", controllerGroup, typeof (IGrouping)) + } +
+
+ + diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/WindowsDataCenter.csproj b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/WindowsDataCenter.csproj index 4dee973..809ad79 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/WindowsDataCenter.csproj +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/WindowsDataCenter.csproj @@ -1,350 +1,389 @@ - - - - - Debug - AnyCPU - {A5FEE048-17A6-4966-9B6B-BF073592A470} - WinExe - Properties - WindowsDataCenter - WindowsDataCenter - v4.5.2 - 512 - true - - - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - bin\Debug\WindowsDataCenter.XML - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - bin\DebugInstallers\ - DEBUG;TRACE - bin\Debug\WindowsDataCenter.XML - full - AnyCPU - prompt - MinimumRecommendedRules.ruleset - true - - - bin\ReleaseInstallers\ - TRACE - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - true - - - - ..\packages\DalSoft.WebApi.HelpPage.0.0.7.0\lib\net451\DalSoft.WebApi.HelpPage.dll - True - - - ..\packages\Microsoft.Owin.3.0.1\lib\net45\Microsoft.Owin.dll - True - - - ..\packages\Microsoft.Owin.FileSystems.3.0.1\lib\net45\Microsoft.Owin.FileSystems.dll - True - - - ..\packages\Microsoft.Owin.Host.HttpListener.3.0.1\lib\net45\Microsoft.Owin.Host.HttpListener.dll - True - - - ..\packages\Microsoft.Owin.Hosting.3.0.1\lib\net45\Microsoft.Owin.Hosting.dll - True - - - ..\packages\Microsoft.Owin.StaticFiles.3.0.1\lib\net45\Microsoft.Owin.StaticFiles.dll - True - - - ..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll - True - - - ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll - True - - - ..\packages\Ninject.3.2.2.0\lib\net45-full\Ninject.dll - True - - - ..\packages\Ninject.Extensions.ContextPreservation.3.2.0.0\lib\net45-full\Ninject.Extensions.ContextPreservation.dll - True - - - ..\packages\Ninject.Extensions.NamedScope.3.2.0.0\lib\net45-full\Ninject.Extensions.NamedScope.dll - True - - - ..\packages\Ninject.Extensions.Xml.3.2.0.0\lib\net45-full\Ninject.Extensions.Xml.dll - True - - - ..\packages\Ninject.Web.Common.3.2.3.0\lib\net45-full\Ninject.Web.Common.dll - True - - - ..\packages\Ninject.Web.Common.OwinHost.3.2.3.0\lib\net45-full\Ninject.Web.Common.OwinHost.dll - True - - - ..\packages\Ninject.Web.WebApi.3.2.4.0\lib\net45-full\Ninject.Web.WebApi.dll - True - - - ..\packages\Ninject.Web.WebApi.OwinHost.3.2.4.0\lib\net45-full\Ninject.Web.WebApi.OwinHost.dll - True - - - ..\packages\Owin.1.0\lib\net40\Owin.dll - True - - - ..\packages\RazorEngine.3.7.2\lib\net45\RazorEngine.dll - True - - - - - - - ..\packages\System.Data.SQLite.Core.1.0.104.0\lib\net451\System.Data.SQLite.dll - True - - - ..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll - True - - - - ..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll - True - - - ..\packages\Microsoft.AspNet.WebApi.Owin.5.2.3\lib\net45\System.Web.Http.Owin.dll - True - - - ..\packages\Microsoft.AspNet.WebApi.WebHost.5.0.0\lib\net45\System.Web.Http.WebHost.dll - True - - - - - - - - - - ..\packages\WebActivatorEx.2.0\lib\net40\WebActivatorEx.dll - True - - - - - - - - - - - - - - - - - - - - Component - - - DataCenterService.cs - - - - - - - - - - - - Always - - - Always - - - Always - - - Always - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - Always - - - Always - - - PreserveNewest - - - Always - - - Always - - - Always - - - PreserveNewest - - - PreserveNewest - - - Always - - - Always - - - Always - - - Always - - - Always - - - Designer - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - - - PreserveNewest - - - - - - - {115250F6-F8C4-4F9B-A15F-251EA258D963} - ConfigurationHandler - - - {B7347B72-E208-423A-9D99-723B558EA3D7} - Interfaces - - - {B3510C81-F069-48A2-B826-EBE0CE7AB0B2} - SQLiteRepository - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - call "$(ProjectDir)Minifier\Minify.bat" "$(SolutionDir)" - + + + + + Debug + AnyCPU + {A5FEE048-17A6-4966-9B6B-BF073592A470} + WinExe + Properties + WindowsDataCenter + WindowsDataCenter + v4.5.2 + 512 + true + + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + bin\Debug\WindowsDataCenter.XML + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\DebugInstallers\ + DEBUG;TRACE + bin\Debug\WindowsDataCenter.XML + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + true + + + bin\ReleaseInstallers\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + true + bin\ReleaseInstallers\WindowsDataCenter.XML + + + + ..\packages\Castle.Core.4.2.0\lib\net45\Castle.Core.dll + True + + + ..\packages\DalSoft.WebApi.HelpPage.0.0.7.0\lib\net451\DalSoft.WebApi.HelpPage.dll + True + + + ..\packages\Microsoft.Owin.3.1.0\lib\net45\Microsoft.Owin.dll + True + + + ..\packages\Microsoft.Owin.FileSystems.3.0.1\lib\net45\Microsoft.Owin.FileSystems.dll + True + + + ..\packages\Microsoft.Owin.Host.HttpListener.3.0.1\lib\net45\Microsoft.Owin.Host.HttpListener.dll + True + + + ..\packages\Microsoft.Owin.Hosting.3.0.1\lib\net45\Microsoft.Owin.Hosting.dll + True + + + ..\packages\Microsoft.Owin.StaticFiles.3.0.1\lib\net45\Microsoft.Owin.StaticFiles.dll + True + + + ..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll + True + + + ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll + True + + + ..\packages\Ninject.3.3.4\lib\net45\Ninject.dll + True + + + ..\packages\Ninject.Extensions.ContextPreservation.3.3.1\lib\net45\Ninject.Extensions.ContextPreservation.dll + True + + + ..\packages\Ninject.Extensions.Factory.3.3.2\lib\net45\Ninject.Extensions.Factory.dll + True + + + ..\packages\Ninject.Extensions.NamedScope.3.3.0\lib\net45\Ninject.Extensions.NamedScope.dll + True + + + ..\packages\Ninject.Extensions.Xml.3.3.0\lib\net45\Ninject.Extensions.Xml.dll + True + + + ..\packages\Ninject.Web.Common.3.3.1\lib\net45\Ninject.Web.Common.dll + True + + + ..\packages\Ninject.Web.Common.OwinHost.3.3.1\lib\net45\Ninject.Web.Common.OwinHost.dll + True + + + ..\packages\Ninject.Web.Common.WebHost.3.3.1\lib\net45\Ninject.Web.Common.WebHost.dll + True + + + ..\packages\Ninject.Web.WebApi.3.3.0\lib\net45\Ninject.Web.WebApi.dll + True + + + ..\packages\Ninject.Web.WebApi.OwinHost.3.3.0\lib\net45\Ninject.Web.WebApi.OwinHost.dll + True + + + ..\packages\Owin.1.0\lib\net40\Owin.dll + True + + + ..\packages\RazorEngine.3.7.2\lib\net45\RazorEngine.dll + True + + + + + + + ..\packages\System.Data.SQLite.Core.1.0.104.0\lib\net451\System.Data.SQLite.dll + True + + + ..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll + True + + + + ..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll + True + + + ..\packages\Microsoft.AspNet.WebApi.Owin.5.2.3\lib\net45\System.Web.Http.Owin.dll + True + + + ..\packages\Microsoft.AspNet.WebApi.WebHost.5.0.0\lib\net45\System.Web.Http.WebHost.dll + True + + + ..\packages\Microsoft.AspNet.Razor.3.0.0\lib\net45\System.Web.Razor.dll + True + + + + + + + + + + ..\packages\WebActivatorEx.2.2.0\lib\net40\WebActivatorEx.dll + True + + + + + + + + + + + + + + + + + + + + + Component + + + DataCenterService.cs + + + + + + + + + + + PreserveNewest + + + + Always + + + Always + + + Always + + + Always + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + Always + + + Always + + + PreserveNewest + + + Always + + + Always + + + Always + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + Always + + + PreserveNewest + + + Always + + + Always + + + Always + + + Always + + + Always + + + Designer + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + + + + + + {115250F6-F8C4-4F9B-A15F-251EA258D963} + ConfigurationHandler + + + {B7347B72-E208-423A-9D99-723B558EA3D7} + Interfaces + + + {B3510C81-F069-48A2-B826-EBE0CE7AB0B2} + SQLiteRepository + + + + + call "$(ProjectDir)Minifier\Minify.bat" "$(SolutionDir)" + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + --> \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/WindowsDataCenter.csproj.user b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/WindowsDataCenter.csproj.user index ca1d04b..1efe784 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/WindowsDataCenter.csproj.user +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/WindowsDataCenter.csproj.user @@ -1,6 +1,6 @@ - - - - ProjectFiles - + + + + ProjectFiles + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/packages.config b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/packages.config index 0363aa3..027aa92 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/packages.config +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/packages.config @@ -1,30 +1,33 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/Admin.html b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/Admin.html index b6667d0..4f9efba 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/Admin.html +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/Admin.html @@ -1,109 +1,171 @@ - - - - - - Flexitime Admin page - - - - - - - - - - -
-
-

Groups

- -
-
-
-
- - - - - - - - - - - - - - - -
NameUser Count
-
-
- -
- - -
- - - -
-
-
-
-
-

Unassigned Cards

- -
-
-
- - - - - - - - - - - - - -
Card Unique IdLast Used Date
-
-
-
- - - + + + + + + Flexitime Admin page + + + + + + + + + + + + + +
+
+

Groups

+ +
+
+
+
+ + + + + + + + + + + + + + + +
NameUser Count
+
+
+ +
+ + +
+ + + +
+
+
+
+
+

Unassigned Cards

+ +
+
+
+ + + + + + + + + + + + + +
Card Unique IdLast Used Date
+
+
+
+
+
+ +
+
+ +
+
+
+
+
+ + +
+
+ + + + + + + + + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/admin.js b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/admin.js index b912835..61713dd 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/admin.js +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/admin.js @@ -1,126 +1,221 @@ -function AdminVM() { - var self = this; - self.groupsList = ko.observable(null); - self.groupEditItem = ko.observable(null); - self.unassignedCardList = ko.observable(null); - self.helpers = new Helpers(); - self.uiPages = { - overview: "overview", - group: "groups", - home: function () { return this.overview; } - }; - self.apiEndpoints = { - deleteGroups:"/api/groups/delete", - getGroups: "/api/groups", - editGroup: "/api/groups/edit", - getUnassignedCards: "/api/cards/unassigned", - clearUnassignedCards: "/api/cards/unassigned" - }; - self.clearGroupForm = function () { - self.helpers.goToMenuOption(self.uiPages.group); - self.groupEditItem(null); - }; - self.hideGroupForm = function () { - self.groupEditItem(null); - }; - self.newGroupForm = function () { - self.groupEditItem({ Id: -1, Name: "" }); - self.helpers.goToMenuOption(self.uiPages.group); - }; - self.groupFormHidden = ko.computed(function () { - return self.groupEditItem() == null; - }, self); - self.editGroupClick = function (data) { - self.helpers.goToMenuOption(self.uiPages.group); - self.groupEditItem(data); - }; - self.getGroups = function () { - var url = self.helpers.createRequestUrl(self.apiEndpoints.getGroups, null, false); - $.getJSON(url, function (res) { - self.groupsList(res); - }).fail(function (resp, status, error) { - console.log("error - getGroups"); - var errorObj = self.helpers.processRequestFailure(resp, status, error); - }); - }; - self.deleteGroup = function (groupId) { - var url = self.helpers.createRequestUrl(self.apiEndpoints.deleteGroups, - [{ key: "groupId", value: groupId }], - false, - false); - $.ajax({ - url: url, - type: 'DELETE', - success: function () { - console.log("deleted " + groupId); - self.hideGroupForm(); - self.helpers.goToMenuOption(self.uiPages.home()); - } - }); - console.log("delete: " + groupId); - }; - self.submitGroupEdit = function(group) { - var url = self.helpers.createRequestUrl(self.apiEndpoints.editGroup, null, false); - $.post(url, group, function () { - }, "json") - .done(function () { - self.groupEditItem(null); - self.helpers.goToMenuOption(self.uiPages.home()); - }) - .fail(function (resp, status, error) { - self.helpers.goToMenuOption(self.uiPages.home()); - var errorObj = self.helpers.processRequestFailure(resp, status, error); - }); - }; - self.getUnassignedCardData = function() { - var url = self.helpers.createRequestUrl(self.apiEndpoints.getUnassignedCards, null, false); - $.getJSON(url, - function(res) { - self.unassignedCardList(res); - }).fail(function(resp, status, error) { - console.log("error - getUnassignedCards"); - var errorObj = self.helpers.processRequestFailure(resp, status, error); - }); - }; - self.clearUnassignedCards = function() { - var url = self.helpers.createRequestUrl(self.apiEndpoints.clearUnassignedCards, null, false); - $.ajax({ - type: "DELETE", - url: url, - data: "", - success: function() { - self.getUnassignedCardData(); //update - }, - error: function(jqxhr, status, error) { - console.log("error - clearUnassignedCards"); - var errorObj = self.helpers.processRequestFailure(resp, status, error); - } - }); - }; - self.padNumber = function (number) { - return (number < 10 ? "0" : "") + number; - }; - self.convertToDisplayDateTime = function (dateValue) { - var date = new Date(dateValue); // dd MM YY HH:mm:ss e.g.: 01 Mar 17 17:34:02 - return date.getDate() + " " - + date.toLocaleString("en-us", { month: "long" }) + " " - + (date.getYear()-100) + " " - + self.padNumber(date.getHours()) + ":" - + self.padNumber(date.getMinutes()) + ":" - + self.padNumber(date.getSeconds()); - }; - Sammy(function () { - this.disable_push_state = true; - this.get("#overview", function () { - self.getGroups(); - self.getUnassignedCardData(); - }); - this.post("#editgroup", function () { - self.submitGroupEdit(self.groupEditItem()); - return false; - }); - //default route (home page) - this.get("", function () { this.app.runRoute("get", "#" + self.uiPages.home()) }); - }).run(); -}; +function AdminVM() { + var self = this; + self.groupsList = ko.observable(null); + self.groupEditItem = ko.observable(null); + self.unassignedCardList = ko.observable(null); + self.helpers = new Helpers(); + self.policyMarkdown = ""; + self.policyData = new policy(); + self.renderer = new marked.Renderer(); + self.renderer.blockquote = function(quote) { + return "
" + quote + "
"; + }; + self.renderer.heading = function (text, level) { + + var parserHandler = new Tautologistics.NodeHtmlParser.DefaultHandler(function (error) { + if (error) + throw new Error("Cannot parse \"" + text + "\" in markdown file."); + }); + var parser = new Tautologistics.NodeHtmlParser.Parser(parserHandler); + + parser.parseComplete(text); + var escaped = "unknown"; + + if (parserHandler.dom.length > 0) { + escaped = parserHandler.dom[0].raw.toLowerCase().trim().replace(/ /g, "-"); + } + + return "" + // NOTE: We're setting display none INLINE, so you have + // to override with !important if you want it to show. + + " ' + + " " + + " " + + text + + ""; + }; + self.renderer.table = function(header, body) { + return "" + + "" + + header + + "" + + "" + + body + + "" + + "
"; + }; + /* + * Adds highlight.js classes to `code` blocks + */ + self.renderer.code = function(code, language) { + + var valid = !!(language && hljs.getLanguage(language)); + var highlighted = valid ? hljs.highlight(language, code).value : code + + return "
" + highlighted + "
"; + }; + self.editor = new EasyMDE({ + element: document.getElementById("policyEditor"), + showIcons: ["bold", "italic", "strikethrough", "heading", "heading-smaller", "heading-bigger", "heading-1", "heading-2", "heading-3", "code", "quote", "unordered-list", "ordered-list", "clean-block", "link", "table", "horizontal-rule", "guide", "table"], + hideIcons: ["preview", "side-by-side", "fullscreen"], + renderingConfig: { + markedOptions: { + renderer: self.renderer + } + } + }); + self.editor.codemirror.on("changes", + function () { + self.policyData.html(self.editor.options.previewRender(self.editor.value())); + }); + self.uiPages = { + overview: "overview", + group: "groups", + home: function () { return this.overview; } + }; + self.apiEndpoints = { + deleteGroups:"/api/groups/delete", + getGroups: "/api/groups", + editGroup: "/api/groups/edit", + getUnassignedCards: "/api/cards/unassigned", + clearUnassignedCards: "/api/cards/unassigned", + getPolicy:"/api/app/policy", + savePolicy:"/api/app/policy" + }; + self.clearGroupForm = function () { + self.helpers.goToMenuOption(self.uiPages.group); + self.groupEditItem(null); + }; + self.hideGroupForm = function () { + self.groupEditItem(null); + }; + self.newGroupForm = function () { + self.groupEditItem({ Id: -1, Name: "" }); + self.helpers.goToMenuOption(self.uiPages.group); + }; + self.groupFormHidden = ko.computed(function () { + return self.groupEditItem() == null; + }, self); + self.editGroupClick = function (data) { + self.helpers.goToMenuOption(self.uiPages.group); + self.groupEditItem(data); + }; + self.getGroups = function () { + var url = self.helpers.createRequestUrl(self.apiEndpoints.getGroups, null, false); + $.getJSON(url, function (res) { + self.groupsList(res); + }).fail(function (resp, status, error) { + console.log("error - getGroups"); + var errorObj = self.helpers.processRequestFailure(resp, status, error); + }); + }; + self.deleteGroup = function (groupId) { + var url = self.helpers.createRequestUrl(self.apiEndpoints.deleteGroups, + [{ key: "groupId", value: groupId }], + false, + false); + $.ajax({ + url: url, + type: "DELETE", + success: function () { + console.log("deleted " + groupId); + self.hideGroupForm(); + self.helpers.goToMenuOption(self.uiPages.home()); + } + }); + console.log("delete: " + groupId); + }; + self.submitGroupEdit = function(group) { + var url = self.helpers.createRequestUrl(self.apiEndpoints.editGroup, null, false); + $.post(url, group, function () { + }, "json") + .done(function () { + self.groupEditItem(null); + self.helpers.goToMenuOption(self.uiPages.home()); + }) + .fail(function (resp, status, error) { + self.helpers.goToMenuOption(self.uiPages.home()); + var errorObj = self.helpers.processRequestFailure(resp, status, error); + }); + }; + self.getUnassignedCardData = function() { + var url = self.helpers.createRequestUrl(self.apiEndpoints.getUnassignedCards, null, false); + $.getJSON(url, + function(res) { + self.unassignedCardList(res); + }).fail(function(resp, status, error) { + console.log("error - getUnassignedCards"); + var errorObj = self.helpers.processRequestFailure(resp, status, error); + }); + }; + self.clearUnassignedCards = function() { + var url = self.helpers.createRequestUrl(self.apiEndpoints.clearUnassignedCards, null, false); + $.ajax({ + type: "DELETE", + url: url, + data: "", + success: function() { + self.getUnassignedCardData(); //update + }, + error: function(jqxhr, status, error) { + console.log("error - clearUnassignedCards"); + var errorObj = self.helpers.processRequestFailure(resp, status, error); + } + }); + }; + self.padNumber = function (number) { + return (number < 10 ? "0" : "") + number; + }; + self.policySave = function () { + var url = self.helpers.createRequestUrl(self.apiEndpoints.savePolicy, null, false); + self.policyData.Markdown(self.editor.value()); //make sure we update it, as it doesnt push the value back into the variable + //console.log(self.policyData()); + $.post(url, self.policyData(), function() { + }, "json") //todo: check this serialisation as the object is now complex. + .done(function() { + self.policyReload(); + }).fail(function(resp, status, error) { + var errorObj = self.helpers.processRequestFailure(resp, status, error); + console.log(errorObj); + }); + }; + self.policyReload = function() { + var url = self.helpers.createRequestUrl(self.apiEndpoints.getPolicy, + [], false, false); + $.getJSON(url, function (res) { + //console.log(res); + self.editor.value(res.Markdown); + res.Version = (parseInt(res.Version) + 1).toString(); + self.policyData.update(res); + $('#saveDialog').modal('hide'); + }).fail(function (resp, status, error) { + console.log("error - policyReload"); + var errObj = self.helpers.processRequestFailure(resp, status, error); + self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "policyReload"); + }); + }; + self.convertToDisplayDateTime = function (dateValue) { + var date = new Date(dateValue); // dd MM YY HH:mm:ss e.g.: 01 Mar 17 17:34:02 + return date.getDate() + " " + + date.toLocaleString("en-us", { month: "long" }) + " " + + (date.getYear()-100) + " " + + self.padNumber(date.getHours()) + ":" + + self.padNumber(date.getMinutes()) + ":" + + self.padNumber(date.getSeconds()); + }; + Sammy(function () { + this.disable_push_state = true; + this.get("#overview", function () { + self.getGroups(); + self.getUnassignedCardData(); + self.policyReload(); + }); + this.post("#editgroup", function () { + self.submitGroupEdit(self.groupEditItem()); + return false; + }); + //default route (home page) + this.get("", function () { this.app.runRoute("get", "#" + self.uiPages.home()) }); + }).run(); +}; ko.applyBindings(new AdminVM()); \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/admin.min.js b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/admin.min.js index 6a6123e..1e8dff2 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/admin.min.js +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/admin.min.js @@ -1 +1 @@ -function AdminVM(){var n=this;n.groupsList=ko.observable(null);n.groupEditItem=ko.observable(null);n.unassignedCardList=ko.observable(null);n.helpers=new Helpers;n.uiPages={overview:"overview",group:"groups",home:function(){return this.overview}};n.apiEndpoints={deleteGroups:"/api/groups/delete",getGroups:"/api/groups",editGroup:"/api/groups/edit",getUnassignedCards:"/api/cards/unassigned",clearUnassignedCards:"/api/cards/unassigned"};n.clearGroupForm=function(){n.helpers.goToMenuOption(n.uiPages.group);n.groupEditItem(null)};n.hideGroupForm=function(){n.groupEditItem(null)};n.newGroupForm=function(){n.groupEditItem({Id:-1,Name:""});n.helpers.goToMenuOption(n.uiPages.group)};n.groupFormHidden=ko.computed(function(){return n.groupEditItem()==null},n);n.editGroupClick=function(t){n.helpers.goToMenuOption(n.uiPages.group);n.groupEditItem(t)};n.getGroups=function(){var t=n.helpers.createRequestUrl(n.apiEndpoints.getGroups,null,!1);$.getJSON(t,function(t){n.groupsList(t)}).fail(function(t,i,r){console.log("error - getGroups");var u=n.helpers.processRequestFailure(t,i,r)})};n.deleteGroup=function(t){var i=n.helpers.createRequestUrl(n.apiEndpoints.deleteGroups,[{key:"groupId",value:t}],!1,!1);$.ajax({url:i,type:"DELETE",success:function(){console.log("deleted "+t);n.hideGroupForm();n.helpers.goToMenuOption(n.uiPages.home())}});console.log("delete: "+t)};n.submitGroupEdit=function(t){var i=n.helpers.createRequestUrl(n.apiEndpoints.editGroup,null,!1);$.post(i,t,function(){},"json").done(function(){n.groupEditItem(null);n.helpers.goToMenuOption(n.uiPages.home())}).fail(function(t,i,r){n.helpers.goToMenuOption(n.uiPages.home());var u=n.helpers.processRequestFailure(t,i,r)})};n.getUnassignedCardData=function(){var t=n.helpers.createRequestUrl(n.apiEndpoints.getUnassignedCards,null,!1);$.getJSON(t,function(t){n.unassignedCardList(t)}).fail(function(t,i,r){console.log("error - getUnassignedCards");var u=n.helpers.processRequestFailure(t,i,r)})};n.clearUnassignedCards=function(){var t=n.helpers.createRequestUrl(n.apiEndpoints.clearUnassignedCards,null,!1);$.ajax({type:"DELETE",url:t,data:"",success:function(){n.getUnassignedCardData()},error:function(t,i,r){console.log("error - clearUnassignedCards");var u=n.helpers.processRequestFailure(resp,i,r)}})};n.padNumber=function(n){return(n<10?"0":"")+n};n.convertToDisplayDateTime=function(t){var i=new Date(t);return i.getDate()+" "+i.toLocaleString("en-us",{month:"long"})+" "+(i.getYear()-100)+" "+n.padNumber(i.getHours())+":"+n.padNumber(i.getMinutes())+":"+n.padNumber(i.getSeconds())};Sammy(function(){this.disable_push_state=!0;this.get("#overview",function(){n.getGroups();n.getUnassignedCardData()});this.post("#editgroup",function(){return n.submitGroupEdit(n.groupEditItem()),!1});this.get("",function(){this.app.runRoute("get","#"+n.uiPages.home())})}).run()}ko.applyBindings(new AdminVM) \ No newline at end of file +function AdminVM(){var n=this;n.groupsList=ko.observable(null);n.groupEditItem=ko.observable(null);n.unassignedCardList=ko.observable(null);n.helpers=new Helpers;n.policyMarkdown="";n.policyData=new policy;n.renderer=new marked.Renderer;n.renderer.blockquote=function(n){return'
'+n+"<\/blockquote>"};n.renderer.heading=function(n,t){var r=new Tautologistics.NodeHtmlParser.DefaultHandler(function(t){if(t)throw new Error('Cannot parse "'+n+'" in markdown file.');}),u=new Tautologistics.NodeHtmlParser.Parser(r),i;return u.parseComplete(n),i="unknown",r.dom.length>0&&(i=r.dom[0].raw.toLowerCase().trim().replace(/ /g,"-"))," "},s.prototype.image=function(e,t,n){if(null===(e=p(this.options.sanitize,this.options.baseUrl,e)))return n;var r=''+n+'":">"},s.prototype.text=function(e){return e},l.prototype.strong=l.prototype.em=l.prototype.codespan=l.prototype.del=l.prototype.text=function(e){return e},l.prototype.link=l.prototype.image=function(e,t,n){return""+n},l.prototype.br=function(){return""},u.parse=function(e,t){return new u(t).parse(e)},u.prototype.parse=function(e){this.inline=new a(e.links,this.options),this.inlineText=new a(e.links,y({},this.options,{renderer:new l})),this.tokens=e.reverse();for(var t="";this.next();)t+=this.tok();return t},u.prototype.next=function(){return this.token=this.tokens.pop(),this.token},u.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0},u.prototype.parseText=function(){for(var e=this.token.text;"text"===this.peek().type;)e+="\n"+this.next().text;return this.inline.output(e)},u.prototype.tok=function(){switch(this.token.type){case"space":return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,f(this.inlineText.output(this.token.text)),this.slugger);case"code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table":var e,t,n,r,i="",o="";for(n="",e=0;e?@[\]^`{|}~]/g,"").replace(/\s/g,"-");if(this.seen.hasOwnProperty(t)){var n=t;do{this.seen[n]++,t=n+"-"+this.seen[n]}while(this.seen.hasOwnProperty(t))}return this.seen[t]=0,t},h.escapeTest=/[&<>"']/,h.escapeReplace=/[&<>"']/g,h.replacements={"&":"&","<":"<",">":">",'"':""","'":"'"},h.escapeTestNoEncode=/[<>"']|&(?!#?\w+;)/,h.escapeReplaceNoEncode=/[<>"']|&(?!#?\w+;)/g;var m={},g=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function v(){}function y(e){for(var t,n,r=1;r=0&&"\\"===n[i];)r=!r;return r?"|":" |"}).split(/ \|/),r=0;if(n.length>t)n.splice(t);else for(;n.lengthAn error occurred:

"+h(e.message+"",!0)+"
";throw e}}v.exec=v,C.options=C.setOptions=function(e){return y(C.defaults,e),C},C.getDefaults=function(){return{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:new s,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,xhtml:!1}},C.defaults=C.getDefaults(),C.Parser=u,C.parser=u.parse,C.Renderer=s,C.TextRenderer=l,C.Lexer=i,C.lexer=i.lex,C.InlineLexer=a,C.inlineLexer=a.output,C.Slugger=c,C.parse=C,void 0!==t&&"object"==typeof n?t.exports=C:e.marked=C}(this||("undefined"!=typeof window?window:e))}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],18:[function(e,t,n){(function(n,r){var i;!function(){"use strict";(i=function(e,t,n,i){i=i||{},this.dictionary=null,this.rules={},this.dictionaryTable={},this.compoundRules=[],this.compoundRuleCodes={},this.replacementTable=[],this.flags=i.flags||{},this.memoized={},this.loaded=!1;var o,a,s,l,u,c=this;function h(e,t){var n=c._readFile(e,null,i.asyncLoad);i.asyncLoad?n.then(function(e){t(e)}):t(n)}function f(e){t=e,n&&p()}function d(e){n=e,t&&p()}function p(){for(c.rules=c._parseAFF(t),c.compoundRuleCodes={},a=0,l=c.compoundRules.length;a0&&(b.continuationClasses=y),"."!==x&&(b.match="SFX"===h?new RegExp(x+"$"):new RegExp("^"+x)),"0"!=m&&(b.remove="SFX"===h?new RegExp(m+"$"):m),p.push(b)}l[f]={type:h,combineable:"Y"==d,entries:p},i+=n}else if("COMPOUNDRULE"===h){for(o=i+1,s=i+1+(n=parseInt(c[1],10));o0&&(null===n[e]&&(n[e]=[]),n[e].push(t))}for(var i=1,o=t.length;i1){var l=this.parseRuleCodes(a[1]);"NEEDAFFIX"in this.flags&&-1!=l.indexOf(this.flags.NEEDAFFIX)||r(s,l);for(var u=0,c=l.length;u=this.flags.COMPOUNDMIN)for(t=0,n=this.compoundRules.length;t1&&c[1][1]!==c[1][0]&&l.push(c[0]+c[1][1]+c[1][0]+c[1].substring(2)),c[1])for(r=0,a=s.alphabet.length;r)+?/g),l={toggleBold:y,toggleItalic:x,drawLink:D,toggleHeadingSmaller:C,toggleHeadingBigger:S,drawImage:F,toggleBlockquote:k,toggleOrderedList:E,toggleUnorderedList:A,toggleCodeBlock:w,togglePreview:H,toggleStrikethrough:b,toggleHeading1:L,toggleHeading2:T,toggleHeading3:M,cleanBlock:N,drawTable:I,drawHorizontalRule:B,undo:R,redo:z,toggleSideBySide:P,toggleFullScreen:v},u={toggleBold:"Cmd-B",toggleItalic:"Cmd-I",drawLink:"Cmd-K",toggleHeadingSmaller:"Cmd-H",toggleHeadingBigger:"Shift-Cmd-H",cleanBlock:"Cmd-E",drawImage:"Cmd-Alt-I",toggleBlockquote:"Cmd-'",toggleOrderedList:"Cmd-Alt-L",toggleUnorderedList:"Cmd-L",toggleCodeBlock:"Cmd-Alt-C",togglePreview:"Cmd-P",toggleSideBySide:"F9",toggleFullScreen:"F11"},c=function(e){for(var t in l)if(l[t]===e)return t;return null},h=function(){var e,t=!1;return e=navigator.userAgent||navigator.vendor||window.opera,(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(e.substr(0,4)))&&(t=!0),t};function f(e){return e=a?e.replace("Ctrl","Cmd"):e.replace("Cmd","Ctrl")}function d(e,t,n){e=e||{};var r=document.createElement("button");r.className=e.name,r.setAttribute("type","button"),t=null==t||t,e.name&&e.name in n&&(l[e.name]=e.action),e.title&&t&&(r.title=function(e,t,n){var r,i=e;t&&(r=c(t),n[r]&&(i+=" ("+f(n[r])+")"));return i}(e.title,e.action,n),a&&(r.title=r.title.replace("Ctrl","⌘"),r.title=r.title.replace("Alt","⌥"))),e.noDisable&&r.classList.add("no-disable"),e.noMobile&&r.classList.add("no-mobile");for(var i=e.className.split(" "),o=[],s=0;s=0&&!n(f=l.getLineHandle(o));o--);var g,v,y,x,b=r(l.getTokenAt({line:o,ch:1})).fencedChars;n(l.getLineHandle(u.line))?(g="",v=u.line):n(l.getLineHandle(u.line-1))?(g="",v=u.line-1):(g=b+"\n",v=u.line),n(l.getLineHandle(c.line))?(y="",x=c.line,0===c.ch&&(x+=1)):0!==c.ch&&n(l.getLineHandle(c.line+1))?(y="",x=c.line+1):(y=b+"\n",x=c.line+1),0===c.ch&&(x-=1),l.operation(function(){l.replaceRange(y,{line:x,ch:0},{line:x+(y?0:1),ch:0}),l.replaceRange(g,{line:v,ch:0},{line:v+(g?0:1),ch:0})}),l.setSelection({line:v+(g?1:0),ch:0},{line:x+(g?1:-1),ch:0}),l.focus()}else{var w=u.line;if(n(l.getLineHandle(u.line))&&("fenced"===i(l,u.line+1)?(o=u.line,w=u.line+1):(a=u.line,w=u.line-1)),void 0===o)for(o=w;o>=0&&!n(f=l.getLineHandle(o));o--);if(void 0===a)for(s=l.lineCount(),a=w;a=0;o--)if(!(f=l.getLineHandle(o)).text.match(/^\s*$/)&&"indented"!==i(l,o,f)){o+=1;break}for(s=l.lineCount(),a=u.line;a ]+|[0-9]+(.|\)))[ ]*/,""),e.replaceRange(t,{line:i,ch:0},{line:i,ch:99999999999999})}(e.codemirror)}function D(e){var t=e.codemirror,n=m(t),r=e.options,i="https://";if(r.promptURLs&&!(i=prompt(r.promptTexts.link,"https://")))return!1;_(t,n.link,r.insertTexts.link,i)}function F(e){var t=e.codemirror,n=m(t),r=e.options,i="https://";if(r.promptURLs&&!(i=prompt(r.promptTexts.image,"https://")))return!1;_(t,n.image,r.insertTexts.image,i)}function O(e,t){var n=e.codemirror,r=m(n),i=e.options,o=t.substr(t.lastIndexOf("/")+1);_(n,r.image,i.insertTexts.uploadedImage,t),e.updateStatusBar("upload-image",e.options.imageTexts.sbOnUploaded.replace("#image_name#",o)),setTimeout(function(){e.updateStatusBar("upload-image",e.options.imageTexts.sbInit)},1e3)}function I(e){var t=e.codemirror,n=m(t),r=e.options;_(t,n.table,r.insertTexts.table)}function B(e){var t=e.codemirror,n=m(t),r=e.options;_(t,n.image,r.insertTexts.horizontalRule)}function R(e){var t=e.codemirror;t.undo(),t.focus()}function z(e){var t=e.codemirror;t.redo(),t.focus()}function P(e){var t=e.codemirror,n=t.getWrapperElement(),r=n.nextSibling,i=e.toolbarElements&&e.toolbarElements["side-by-side"],o=!1;/editor-preview-active-side/.test(r.className)?(r.className=r.className.replace(/\s*editor-preview-active-side\s*/g,""),i&&(i.className=i.className.replace(/\s*active\s*/g,"")),n.className=n.className.replace(/\s*CodeMirror-sided\s*/g," ")):(setTimeout(function(){t.getOption("fullScreen")||v(e),r.className+=" editor-preview-active-side"},1),i&&(i.className+=" active"),n.className+=" CodeMirror-sided",o=!0);var a=n.lastChild;if(/editor-preview-active/.test(a.className)){a.className=a.className.replace(/\s*editor-preview-active\s*/g,"");var s=e.toolbarElements.preview,l=n.previousSibling;s.className=s.className.replace(/\s*active\s*/g,""),l.className=l.className.replace(/\s*disabled-for-preview*/g,"")}if(t.sideBySideRenderingFunction||(t.sideBySideRenderingFunction=function(){var t=e.options.previewRender(e.value(),r);null!=t&&(r.innerHTML=t)}),o){var u=e.options.previewRender(e.value(),r);null!=u&&(r.innerHTML=u),t.on("update",t.sideBySideRenderingFunction)}else t.off("update",t.sideBySideRenderingFunction);t.refresh()}function H(e){var t=e.codemirror,n=t.getWrapperElement(),r=n.previousSibling,i=!!e.options.toolbar&&e.toolbarElements.preview,o=n.lastChild;if(!o||!/editor-preview-full/.test(o.className)){if((o=document.createElement("div")).className="editor-preview-full",e.options.previewClass)if(Array.isArray(e.options.previewClass))for(var a=0;a\s+/,"unordered-list":n,"ordered-list":n},l=function(e,t,i){var o=n.exec(t),a=function(e,t){return{quote:">","unordered-list":"*","ordered-list":"%%i."}[e].replace("%%i",t)}(e,u);return null!==o?(function(e,t){var n=new RegExp({quote:">","unordered-list":"*","ordered-list":"\\d+."}[e]);return t&&n.test(t)}(e,o[2])&&(a=""),t=o[1]+a+o[3]+t.replace(r,"").replace(s[e],"$1")):0==i&&(t=a+" "+t),t},u=1,c=o.line;c<=a.line;c++)!function(n){var r=e.getLine(n);i[t]?r=r.replace(s[t],"$1"):("unordered-list"==t&&(r=l("ordered-list",r,!0)),r=l(t,r,!1),u+=1),e.replaceRange(r,{line:n,ch:0},{line:n,ch:99999999999999})}(c);e.focus()}}function U(e,t,n,r){if(!/editor-preview-active/.test(e.codemirror.getWrapperElement().lastChild.className)){r=void 0===r?n:r;var i,o=e.codemirror,a=m(o),s=n,l=r,u=o.getCursor("start"),c=o.getCursor("end");a[t]?(s=(i=o.getLine(u.line)).slice(0,u.ch),l=i.slice(u.ch),"bold"==t?(s=s.replace(/(\*\*|__)(?![\s\S]*(\*\*|__))/,""),l=l.replace(/(\*\*|__)/,"")):"italic"==t?(s=s.replace(/(\*|_)(?![\s\S]*(\*|_))/,""),l=l.replace(/(\*|_)/,"")):"strikethrough"==t&&(s=s.replace(/(\*\*|~~)(?![\s\S]*(\*\*|~~))/,""),l=l.replace(/(\*\*|~~)/,"")),o.replaceRange(s+l,{line:u.line,ch:0},{line:u.line,ch:99999999999999}),"bold"==t||"strikethrough"==t?(u.ch-=2,u!==c&&(c.ch-=2)):"italic"==t&&(u.ch-=1,u!==c&&(c.ch-=1))):(i=o.getSelection(),"bold"==t?i=(i=i.split("**").join("")).split("__").join(""):"italic"==t?i=(i=i.split("*").join("")).split("_").join(""):"strikethrough"==t&&(i=i.split("~~").join("")),o.replaceSelection(s+i+l),u.ch+=n.length,c.ch=u.ch+i.length),o.setSelection(u,c),o.focus()}}function q(e,t){if(Math.abs(e)<1024)return""+e+t[0];var n=0;do{e/=1024,++n}while(Math.abs(e)>=1024&&n=19968?n+=t[r].length:n+=1;return n}var X={bold:{name:"bold",action:y,className:"fa fa-bold",title:"Bold",default:!0},italic:{name:"italic",action:x,className:"fa fa-italic",title:"Italic",default:!0},strikethrough:{name:"strikethrough",action:b,className:"fa fa-strikethrough",title:"Strikethrough"},heading:{name:"heading",action:C,className:"fa fa-header fa-heading",title:"Heading",default:!0},"heading-smaller":{name:"heading-smaller",action:C,className:"fa fa-header fa-heading header-smaller",title:"Smaller Heading"},"heading-bigger":{name:"heading-bigger",action:S,className:"fa fa-header fa-heading header-bigger",title:"Bigger Heading"},"heading-1":{name:"heading-1",action:L,className:"fa fa-header fa-heading header-1",title:"Big Heading"},"heading-2":{name:"heading-2",action:T,className:"fa fa-header fa-heading header-2",title:"Medium Heading"},"heading-3":{name:"heading-3",action:M,className:"fa fa-header fa-heading header-3",title:"Small Heading"},"separator-1":{name:"separator-1"},code:{name:"code",action:w,className:"fa fa-code",title:"Code"},quote:{name:"quote",action:k,className:"fa fa-quote-left",title:"Quote",default:!0},"unordered-list":{name:"unordered-list",action:A,className:"fa fa-list-ul",title:"Generic List",default:!0},"ordered-list":{name:"ordered-list",action:E,className:"fa fa-list-ol",title:"Numbered List",default:!0},"clean-block":{name:"clean-block",action:N,className:"fa fa-eraser",title:"Clean block"},"separator-2":{name:"separator-2"},link:{name:"link",action:D,className:"fa fa-link",title:"Create Link",default:!0},image:{name:"image",action:F,className:"fa fa-image",title:"Insert Image",default:!0},"upload-image":{name:"upload-image",action:function(e){e.openBrowseFileWindow()},className:"fa fa-image",title:"Import an image"},table:{name:"table",action:I,className:"fa fa-table",title:"Insert Table"},"horizontal-rule":{name:"horizontal-rule",action:B,className:"fa fa-minus",title:"Insert Horizontal Line"},"separator-3":{name:"separator-3"},preview:{name:"preview",action:H,className:"fa fa-eye",noDisable:!0,title:"Toggle Preview",default:!0},"side-by-side":{name:"side-by-side",action:P,className:"fa fa-columns",noDisable:!0,noMobile:!0,title:"Toggle Side by Side",default:!0},fullscreen:{name:"fullscreen",action:v,className:"fa fa-arrows-alt",noDisable:!0,noMobile:!0,title:"Toggle Fullscreen",default:!0},"separator-4":{name:"separator-4"},guide:{name:"guide",action:"https://www.markdownguide.org/basic-syntax/",className:"fa fa-question-circle",noDisable:!0,title:"Markdown Guide",default:!0},"separator-5":{name:"separator-5"},undo:{name:"undo",action:R,className:"fa fa-undo",noDisable:!0,title:"Undo"},redo:{name:"redo",action:z,className:"fa fa-repeat fa-redo",noDisable:!0,title:"Redo"}},K={link:["[","](#url#)"],image:["![](","#url#)"],uploadedImage:["![](#url#)",""],table:["","\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text | Text | Text |\n\n"],horizontalRule:["","\n\n-----\n\n"]},Y={link:"URL for the link:",image:"URL of the image:"},Z={bold:"**",code:"```",italic:"*"},J={sbInit:"Attach files by drag and dropping or pasting from clipboard.",sbOnDragEnter:"Drop image to upload it.",sbOnDrop:"Uploading image #images_names#...",sbProgress:"Uploading #file_name#: #progress#%",sbOnUploaded:"Uploaded #image_name#",sizeUnits:"b,Kb,Mb"},Q={noFileGiven:"You must select a file.",typeNotAllowed:"This image type is not allowed.",fileTooLarge:"Image #image_name# is too big (#image_size#).\nMaximum file size is #image_max_size#.",importError:"Something went wrong when uploading the image #image_name#."};function ee(e){(e=e||{}).parent=this;var t=!0;if(!1===e.autoDownloadFontAwesome&&(t=!1),!0!==e.autoDownloadFontAwesome)for(var n=document.styleSheets,r=0;r-1&&(t=!1);if(t){var i=document.createElement("link");i.rel="stylesheet",i.href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css",document.getElementsByTagName("head")[0].appendChild(i)}if(e.element)this.element=e.element;else if(null===e.element)return void console.log("EasyMDE: Error. No element was found.");if(void 0===e.toolbar)for(var o in e.toolbar=[],X)Object.prototype.hasOwnProperty.call(X,o)&&(-1!=o.indexOf("separator-")&&e.toolbar.push("|"),(!0===X[o].default||e.showIcons&&e.showIcons.constructor===Array&&-1!=e.showIcons.indexOf(o))&&e.toolbar.push(o));if(Object.prototype.hasOwnProperty.call(e,"previewClass")||(e.previewClass="editor-preview"),Object.prototype.hasOwnProperty.call(e,"status")||(e.status=["autosave","lines","words","cursor"],e.uploadImage&&e.status.unshift("upload-image")),e.previewRender||(e.previewRender=function(e){return this.parent.markdown(e)}),e.parsingConfig=G({highlightFormatting:!0},e.parsingConfig||{}),e.insertTexts=G({},K,e.insertTexts||{}),e.promptTexts=G({},Y,e.promptTexts||{}),e.blockStyles=G({},Z,e.blockStyles||{}),e.shortcuts=G({},u,e.shortcuts||{}),e.minHeight=e.minHeight||"300px",e.errorCallback=e.errorCallback||function(e){alert(e)},e.uploadImage=e.uploadImage||!1,e.imageMaxSize=e.imageMaxSize||2097152,e.imageAccept=e.imageAccept||"image/png, image/jpeg",e.imageTexts=G({},J,e.imageTexts||{}),e.errorMessages=G({},Q,e.errorMessages||{}),null!=e.autosave&&null!=e.autosave.unique_id&&""!=e.autosave.unique_id&&(e.autosave.uniqueId=e.autosave.unique_id),this.options=e,this.render(),!e.initialValue||this.options.autosave&&!0===this.options.autosave.foundSavedValue||this.value(e.initialValue),e.uploadImage){var a=this;this.codemirror.on("dragenter",function(e,t){a.updateStatusBar("upload-image",a.options.imageTexts.sbOnDragEnter),t.stopPropagation(),t.preventDefault()}),this.codemirror.on("dragend",function(e,t){a.updateStatusBar("upload-image",a.options.imageTexts.sbInit),t.stopPropagation(),t.preventDefault()}),this.codemirror.on("dragleave",function(e,t){a.updateStatusBar("upload-image",a.options.imageTexts.sbInit),t.stopPropagation(),t.preventDefault()}),this.codemirror.on("dragover",function(e,t){a.updateStatusBar("upload-image",a.options.imageTexts.sbOnDragEnter),t.stopPropagation(),t.preventDefault()}),this.codemirror.on("drop",function(t,n){n.stopPropagation(),n.preventDefault(),e.imageUploadFunction?a.uploadImagesUsingCustomFunction(e.imageUploadFunction,n.dataTransfer.files):a.uploadImages(n.dataTransfer.files)}),this.codemirror.on("paste",function(t,n){e.imageUploadFunction?a.uploadImagesUsingCustomFunction(e.imageUploadFunction,n.clipboardData.files):a.uploadImages(n.clipboardData.files)})}}function te(){if("object"!=typeof localStorage)return!1;try{localStorage.setItem("smde_localStorage",1),localStorage.removeItem("smde_localStorage")}catch(e){return!1}return!0}ee.prototype.uploadImages=function(e,t,n){if(0!==e.length){for(var r=[],i=0;i$/,' target="_blank">');e=e.replace(n,r)}}return e}(r)}},ee.prototype.render=function(e){if(e||(e=this.element||document.getElementsByTagName("textarea")[0]),!this._rendered||this._rendered!==e){this.element=e;var t,n,o=this.options,a=this,s={};for(var u in o.shortcuts)null!==o.shortcuts[u]&&null!==l[u]&&function(e){s[f(o.shortcuts[e])]=function(){var t=l[e];"function"==typeof t?t(a):"string"==typeof t&&window.open(t,"_blank")}}(u);if(s.Enter="newlineAndIndentContinueMarkdownList",s.Tab="tabAndIndentMarkdownList",s["Shift-Tab"]="shiftTabAndUnindentMarkdownList",s.Esc=function(e){e.getOption("fullScreen")&&v(a)},document.addEventListener("keydown",function(e){27==(e=e||window.event).keyCode&&a.codemirror.getOption("fullScreen")&&v(a)},!1),!1!==o.spellChecker?(t="spell-checker",(n=o.parsingConfig).name="gfm",n.gitHubSpice=!1,i({codeMirrorInstance:r})):((t=o.parsingConfig).name="gfm",t.gitHubSpice=!1),this.codemirror=r.fromTextArea(e,{mode:t,backdrop:n,theme:null!=o.theme?o.theme:"easymde",tabSize:null!=o.tabSize?o.tabSize:2,indentUnit:null!=o.tabSize?o.tabSize:2,indentWithTabs:!1!==o.indentWithTabs,lineNumbers:!1,autofocus:!0===o.autofocus,extraKeys:s,lineWrapping:!1!==o.lineWrapping,allowDropFileTypes:["text/plain"],placeholder:o.placeholder||e.getAttribute("placeholder")||"",styleSelectedText:null!=o.styleSelectedText?o.styleSelectedText:!h(),configureMouse:function(e,t,n){return{addNew:!1}}}),this.codemirror.getScrollerElement().style.minHeight=o.minHeight,!0===o.forceSync){var c=this.codemirror;c.on("change",function(){c.save()})}this.gui={},!1!==o.toolbar&&(this.gui.toolbar=this.createToolbar()),!1!==o.status&&(this.gui.statusbar=this.createStatusbar()),null!=o.autosave&&!0===o.autosave.enabled&&this.autosave(),this.gui.sideBySide=this.createSideBySide(),this._rendered=this.element;var d=this.codemirror;setTimeout(function(){d.refresh()}.bind(d),0)}},ee.prototype.autosave=function(){if(te()){var e=this;if(null==this.options.autosave.uniqueId||""==this.options.autosave.uniqueId)return void console.log("EasyMDE: You must set a uniqueId to use the autosave feature");!0!==this.options.autosave.binded&&(null!=e.element.form&&null!=e.element.form&&e.element.form.addEventListener("submit",function(){clearTimeout(e.autosaveTimeoutId),e.autosaveTimeoutId=void 0,localStorage.removeItem("smde_"+e.options.autosave.uniqueId),setTimeout(function(){e.autosave()},e.options.autosave.delay||1e4)}),this.options.autosave.binded=!0),!0!==this.options.autosave.loaded&&("string"==typeof localStorage.getItem("smde_"+this.options.autosave.uniqueId)&&""!=localStorage.getItem("smde_"+this.options.autosave.uniqueId)&&(this.codemirror.setValue(localStorage.getItem("smde_"+this.options.autosave.uniqueId)),this.options.autosave.foundSavedValue=!0),this.options.autosave.loaded=!0),localStorage.setItem("smde_"+this.options.autosave.uniqueId,e.value());var t=document.getElementById("autosaved");if(null!=t&&null!=t&&""!=t){var n=new Date,r=n.getHours(),i=n.getMinutes(),o="am",a=r;a>=12&&(a=r-12,o="pm"),0==a&&(a=12),i=i<10?"0"+i:i,t.innerHTML="Autosaved: "+a+":"+i+" "+o}this.autosaveTimeoutId=setTimeout(function(){e.autosave()},this.options.autosave.delay||1e4)}else console.log("EasyMDE: localStorage not available, cannot autosave")},ee.prototype.clearAutosavedValue=function(){if(te()){if(null==this.options.autosave||null==this.options.autosave.uniqueId||""==this.options.autosave.uniqueId)return void console.log("EasyMDE: You must set a uniqueId to clear the autosave value");localStorage.removeItem("smde_"+this.options.autosave.uniqueId)}else console.log("EasyMDE: localStorage not available, cannot autosave")},ee.prototype.openBrowseFileWindow=function(e,t){var n=this,r=this.gui.toolbar.getElementsByClassName("imageInput")[0];r.click(),r.addEventListener("change",function i(o){n.options.imageUploadFunction?n.uploadImagesUsingCustomFunction(n.options.imageUploadFunction,o.target.files):n.uploadImages(o.target.files,e,t),r.removeEventListener("change",i)})},ee.prototype.uploadImage=function(e,t,n){var r=this;function i(e){r.updateStatusBar("upload-image",e),setTimeout(function(){r.updateStatusBar("upload-image",r.options.imageTexts.sbInit)},1e4),n&&"function"==typeof n&&n(e),r.options.errorCallback(e)}function o(t){var n=r.options.imageTexts.sizeUnits.split(",");return t.replace("#image_name#",e.name).replace("#image_size#",q(e.size,n)).replace("#image_max_size#",q(r.options.imageMaxSize,n))}if(t=t||function(e){O(r,e)},e.size>this.options.imageMaxSize)i(o(this.options.errorMessages.fileTooLarge));else{var a=new FormData;a.append("image",e),r.options.imageCSRFToken&&a.append("csrfmiddlewaretoken",r.options.imageCSRFToken);var s=new XMLHttpRequest;s.upload.onprogress=function(t){if(t.lengthComputable){var n=""+Math.round(100*t.loaded/t.total);r.updateStatusBar("upload-image",r.options.imageTexts.sbProgress.replace("#file_name#",e.name).replace("#progress#",n))}},s.open("POST",this.options.imageUploadEndpoint),s.onload=function(){try{var e=JSON.parse(this.responseText)}catch(e){return console.error("EasyMDE: The server did not return a valid json."),void i(o(r.options.errorMessages.importError))}200===this.status&&e&&!e.error&&e.data&&e.data.filePath?t(window.location.origin+"/"+e.data.filePath):e.error&&e.error in r.options.errorMessages?i(o(r.options.errorMessages[e.error])):e.error?i(o(e.error)):(console.error("EasyMDE: Received an unexpected response after uploading the image."+this.status+" ("+this.statusText+")"),i(o(r.options.errorMessages.importError)))},s.onerror=function(e){console.error("EasyMDE: An unexpected error occurred when trying to upload the image."+e.target.status+" ("+e.target.statusText+")"),i(r.options.errorMessages.importError)},s.send(a)}},ee.prototype.uploadImageUsingCustomFunction=function(e,t){var n=this;e(t,function(e){O(n,e)},function(e){var r=function(e){var r=n.options.imageTexts.sizeUnits.split(",");return e.replace("#image_name#",t.name).replace("#image_size#",q(t.size,r)).replace("#image_max_size#",q(n.options.imageMaxSize,r))}(e);n.updateStatusBar("upload-image",r),setTimeout(function(){n.updateStatusBar("upload-image",n.options.imageTexts.sbInit)},1e4),n.options.errorCallback(r)})},ee.prototype.createSideBySide=function(){var e=this.codemirror,t=e.getWrapperElement(),n=t.nextSibling;if(!n||!/editor-preview-side/.test(n.className)){if((n=document.createElement("div")).className="editor-preview-side",this.options.previewClass)if(Array.isArray(this.options.previewClass))for(var r=0;r]+>|\t|)+|(?:\n)))/gm, a = { case_insensitive: "cI", lexemes: "l", contains: "c", keywords: "k", subLanguage: "sL", className: "cN", begin: "b", beginKeywords: "bK", end: "e", endsWithParent: "eW", illegal: "i", excludeBegin: "eB", excludeEnd: "eE", returnBegin: "rB", returnEnd: "rE", relevance: "r", variants: "v", IDENT_RE: "IR", UNDERSCORE_IDENT_RE: "UIR", NUMBER_RE: "NR", C_NUMBER_RE: "CNR", BINARY_NUMBER_RE: "BNR", RE_STARTERS_RE: "RSR", BACKSLASH_ESCAPE: "BE", APOS_STRING_MODE: "ASM", QUOTE_STRING_MODE: "QSM", PHRASAL_WORDS_MODE: "PWM", C_LINE_COMMENT_MODE: "CLCM", C_BLOCK_COMMENT_MODE: "CBCM", HASH_COMMENT_MODE: "HCM", NUMBER_MODE: "NM", C_NUMBER_MODE: "CNM", BINARY_NUMBER_MODE: "BNM", CSS_NUMBER_MODE: "CSSNM", REGEXP_MODE: "RM", TITLE_MODE: "TM", UNDERSCORE_TITLE_MODE: "UTM", COMMENT: "C", beginRe: "bR", endRe: "eR", illegalRe: "iR", lexemesRe: "lR", terminators: "t", terminator_end: "tE" }, N = "", v = { classPrefix: "hljs-", tabReplace: null, useBR: !1, languages: void 0 }; function y(e) { return e.replace(/&/g, "&").replace(//g, ">") } function b(e) { return e.nodeName.toLowerCase() } function w(e, t) { var r = e && e.exec(t); return r && 0 === r.index } function u(e) { return t.test(e) } function p(e) { var t, r = {}, a = Array.prototype.slice.call(arguments, 1); for (t in e) r[t] = e[t]; return a.forEach(function (e) { for (t in e) r[t] = e[t] }), r } function m(e) { var n = []; return function e(t, r) { for (var a = t.firstChild; a; a = a.nextSibling) 3 === a.nodeType ? r += a.nodeValue.length : 1 === a.nodeType && (n.push({ event: "start", offset: r, node: a }), r = e(a, r), b(a).match(/br|hr|img|input/) || n.push({ event: "stop", offset: r, node: a })); return r }(e, 0), n } function i(e) { if (a && !e.langApiRestored) { for (var t in e.langApiRestored = !0, a) e[t] && (e[a[t]] = e[t]); (e.c || []).concat(e.v || []).forEach(i) } } function E(s) { function l(e) { return e && e.source || e } function c(e, t) { return new RegExp(l(e), "m" + (s.cI ? "i" : "") + (t ? "g" : "")) } !function t(r, e) { if (!r.compiled) { if (r.compiled = !0, r.k = r.k || r.bK, r.k) { function a(r, e) { s.cI && (e = e.toLowerCase()), e.split(" ").forEach(function (e) { var t = e.split("|"); n[t[0]] = [r, t[1] ? Number(t[1]) : 1] }) } var n = {}; "string" == typeof r.k ? a("keyword", r.k) : o(r.k).forEach(function (e) { a(e, r.k[e]) }), r.k = n } r.lR = c(r.l || /\w+/, !0), e && (r.bK && (r.b = "\\b(" + r.bK.split(" ").join("|") + ")\\b"), r.b || (r.b = /\B|\b/), r.bR = c(r.b), r.endSameAsBegin && (r.e = r.b), r.e || r.eW || (r.e = /\B|\b/), r.e && (r.eR = c(r.e)), r.tE = l(r.e) || "", r.eW && e.tE && (r.tE += (r.e ? "|" : "") + e.tE)), r.i && (r.iR = c(r.i)), null == r.r && (r.r = 1), r.c || (r.c = []), r.c = Array.prototype.concat.apply([], r.c.map(function (e) { return function (t) { return t.v && !t.cached_variants && (t.cached_variants = t.v.map(function (e) { return p(t, { v: null }, e) })), t.cached_variants || t.eW && [p(t)] || [t] }("self" === e ? r : e) })), r.c.forEach(function (e) { t(e, r) }), r.starts && t(r.starts, e); var i = r.c.map(function (e) { return e.bK ? "\\.?(?:" + e.b + ")\\.?" : e.b }).concat([r.tE, r.i]).map(l).filter(Boolean); r.t = i.length ? c(function (e, t) { for (var r = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./, a = 0, n = "", i = 0; i < e.length; i++) { var s = a, c = l(e[i]); for (0 < i && (n += t) ; 0 < c.length;) { var o = r.exec(c); if (null == o) { n += c; break } n += c.substring(0, o.index), c = c.substring(o.index + o[0].length), "\\" == o[0][0] && o[1] ? n += "\\" + String(Number(o[1]) + s) : (n += o[0], "(" == o[0] && a++) } } return n }(i, "|"), !0) : { exec: function () { return null } } } }(s) } function k(e, t, i, r) { function c(e, t, r, a) { var n = '') + t + (r ? "" : N) : t } function s() { b += null != u.sL ? function () { var e = "string" == typeof u.sL; if (e && !h[u.sL]) return y(p); var t = e ? k(u.sL, p, !0, d[u.sL]) : x(p, u.sL.length ? u.sL : void 0); return 0 < u.r && (m += t.r), e && (d[u.sL] = t.top), c(t.language, t.value, !1, !0) }() : function () { var e, t, r, a, n, i, s; if (!u.k) return y(p); for (a = "", t = 0, u.lR.lastIndex = 0, r = u.lR.exec(p) ; r;) a += y(p.substring(t, r.index)), n = u, i = r, void 0, s = l.cI ? i[0].toLowerCase() : i[0], (e = n.k.hasOwnProperty(s) && n.k[s]) ? (m += e[1], a += c(e[0], y(r[0]))) : a += y(r[0]), t = u.lR.lastIndex, r = u.lR.exec(p); return a + y(p.substr(t)) }(), p = "" } function o(e) { b += e.cN ? c(e.cN, "", !0) : "", u = Object.create(e, { parent: { value: u } }) } function a(e, t) { if (p += e, null == t) return s(), 0; var r = function (e, t) { var r, a, n; for (r = 0, a = t.c.length; r < a; r++) if (w(t.c[r].bR, e)) return t.c[r].endSameAsBegin && (t.c[r].eR = (n = t.c[r].bR.exec(e)[0], new RegExp(n.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"), "m"))), t.c[r] }(t, u); if (r) return r.skip ? p += t : (r.eB && (p += t), s(), r.rB || r.eB || (p = t)), o(r), r.rB ? 0 : t.length; var a = function e(t, r) { if (w(t.eR, r)) { for (; t.endsParent && t.parent;) t = t.parent; return t } if (t.eW) return e(t.parent, r) }(u, t); if (a) { var n = u; for (n.skip ? p += t : (n.rE || n.eE || (p += t), s(), n.eE && (p = t)) ; u.cN && (b += N), u.skip || u.sL || (m += u.r), (u = u.parent) !== a.parent;); return a.starts && (a.endSameAsBegin && (a.starts.eR = a.eR), o(a.starts)), n.rE ? 0 : t.length } if (function (e, t) { return !i && w(t.iR, e) }(t, u)) throw new Error('Illegal lexeme "' + t + '" for mode "' + (u.cN || "") + '"'); return p += t, t.length || 1 } var l = M(e); if (!l) throw new Error('Unknown language: "' + e + '"'); E(l); var n, u = r || l, d = {}, b = ""; for (n = u; n !== l; n = n.parent) n.cN && (b = c(n.cN, "", !0) + b); var p = "", m = 0; try { for (var f, g, _ = 0; u.t.lastIndex = _, f = u.t.exec(t) ;) g = a(t.substring(_, f.index), f[0]), _ = f.index + g; for (a(t.substr(_)), n = u; n.parent; n = n.parent) n.cN && (b += N); return { r: m, value: b, language: e, top: u } } catch (e) { if (e.message && -1 !== e.message.indexOf("Illegal")) return { r: 0, value: y(t) }; throw e } } function x(r, e) { e = e || v.languages || o(h); var a = { r: 0, value: y(r) }, n = a; return e.filter(M).filter(_).forEach(function (e) { var t = k(e, r, !1); t.language = e, t.r > n.r && (n = t), t.r > a.r && (n = a, a = t) }), n.language && (a.second_best = n), a } function f(e) { return v.tabReplace || v.useBR ? e.replace(r, function (e, t) { return v.useBR && "\n" === e ? "
" : v.tabReplace ? t.replace(/\t/g, v.tabReplace) : "" }) : e } function s(e) { var t, r, a, n, i, s = function (e) { var t, r, a, n, i = e.className + " "; if (i += e.parentNode ? e.parentNode.className : "", r = l.exec(i)) return M(r[1]) ? r[1] : "no-highlight"; for (t = 0, a = (i = i.split(/\s+/)).length; t < a; t++) if (u(n = i[t]) || M(n)) return n }(e); u(s) || (v.useBR ? (t = document.createElementNS("http://www.w3.org/1999/xhtml", "div")).innerHTML = e.innerHTML.replace(/\n/g, "").replace(//g, "\n") : t = e, i = t.textContent, a = s ? k(s, i, !0) : x(i), (r = m(t)).length && ((n = document.createElementNS("http://www.w3.org/1999/xhtml", "div")).innerHTML = a.value, a.value = function (e, t, r) { var a = 0, n = "", i = []; function s() { return e.length && t.length ? e[0].offset !== t[0].offset ? e[0].offset < t[0].offset ? e : t : "start" === t[0].event ? e : t : e.length ? e : t } function c(e) { n += "<" + b(e) + d.map.call(e.attributes, function (e) { return " " + e.nodeName + '="' + y(e.value).replace('"', """) + '"' }).join("") + ">" } function o(e) { n += "" } function l(e) { ("start" === e.event ? c : o)(e.node) } for (; e.length || t.length;) { var u = s(); if (n += y(r.substring(a, u[0].offset)), a = u[0].offset, u === e) { for (i.reverse().forEach(o) ; l(u.splice(0, 1)[0]), (u = s()) === e && u.length && u[0].offset === a;); i.reverse().forEach(c) } else "start" === u[0].event ? i.push(u[0].node) : i.pop(), l(u.splice(0, 1)[0]) } return n + y(r.substr(a)) }(r, m(n), i)), a.value = f(a.value), e.innerHTML = a.value, e.className = function (e, t, r) { var a = t ? c[t] : r, n = [e.trim()]; return e.match(/\bhljs\b/) || n.push("hljs"), -1 === e.indexOf(a) && n.push(a), n.join(" ").trim() }(e.className, s, a.language), e.result = { language: a.language, re: a.r }, a.second_best && (e.second_best = { language: a.second_best.language, re: a.second_best.r })) } function g() { if (!g.called) { g.called = !0; var e = document.querySelectorAll("pre code"); d.forEach.call(e, s) } } function M(e) { return e = (e || "").toLowerCase(), h[e] || h[c[e]] } function _(e) { var t = M(e); return t && !t.disableAutodetect } return n.highlight = k, n.highlightAuto = x, n.fixMarkup = f, n.highlightBlock = s, n.configure = function (e) { v = p(v, e) }, n.initHighlighting = g, n.initHighlightingOnLoad = function () { addEventListener("DOMContentLoaded", g, !1), addEventListener("load", g, !1) }, n.registerLanguage = function (t, e) { var r = h[t] = e(n); i(r), r.aliases && r.aliases.forEach(function (e) { c[e] = t }) }, n.listLanguages = function () { return o(h) }, n.getLanguage = M, n.autoDetection = _, n.inherit = p, n.IR = n.IDENT_RE = "[a-zA-Z]\\w*", n.UIR = n.UNDERSCORE_IDENT_RE = "[a-zA-Z_]\\w*", n.NR = n.NUMBER_RE = "\\b\\d+(\\.\\d+)?", n.CNR = n.C_NUMBER_RE = "(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)", n.BNR = n.BINARY_NUMBER_RE = "\\b(0b[01]+)", n.RSR = n.RE_STARTERS_RE = "!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~", n.BE = n.BACKSLASH_ESCAPE = { b: "\\\\[\\s\\S]", r: 0 }, n.ASM = n.APOS_STRING_MODE = { cN: "string", b: "'", e: "'", i: "\\n", c: [n.BE] }, n.QSM = n.QUOTE_STRING_MODE = { cN: "string", b: '"', e: '"', i: "\\n", c: [n.BE] }, n.PWM = n.PHRASAL_WORDS_MODE = { b: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/ }, n.C = n.COMMENT = function (e, t, r) { var a = n.inherit({ cN: "comment", b: e, e: t, c: [] }, r || {}); return a.c.push(n.PWM), a.c.push({ cN: "doctag", b: "(?:TODO|FIXME|NOTE|BUG|XXX):", r: 0 }), a }, n.CLCM = n.C_LINE_COMMENT_MODE = n.C("//", "$"), n.CBCM = n.C_BLOCK_COMMENT_MODE = n.C("/\\*", "\\*/"), n.HCM = n.HASH_COMMENT_MODE = n.C("#", "$"), n.NM = n.NUMBER_MODE = { cN: "number", b: n.NR, r: 0 }, n.CNM = n.C_NUMBER_MODE = { cN: "number", b: n.CNR, r: 0 }, n.BNM = n.BINARY_NUMBER_MODE = { cN: "number", b: n.BNR, r: 0 }, n.CSSNM = n.CSS_NUMBER_MODE = { cN: "number", b: n.NR + "(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?", r: 0 }, n.RM = n.REGEXP_MODE = { cN: "regexp", b: /\//, e: /\/[gimuy]*/, i: /\n/, c: [n.BE, { b: /\[/, e: /\]/, r: 0, c: [n.BE] }] }, n.TM = n.TITLE_MODE = { cN: "title", b: n.IR, r: 0 }, n.UTM = n.UNDERSCORE_TITLE_MODE = { cN: "title", b: n.UIR, r: 0 }, n.METHOD_GUARD = { b: "\\.\\s*" + n.UIR, r: 0 }, n.registerLanguage("apache", function (e) { var t = { cN: "number", b: "[\\$%]\\d+" }; return { aliases: ["apacheconf"], cI: !0, c: [e.HCM, { cN: "section", b: "" }, { cN: "attribute", b: /\w+/, r: 0, k: { nomarkup: "order deny allow setenv rewriterule rewriteengine rewritecond documentroot sethandler errordocument loadmodule options header listen serverroot servername" }, starts: { e: /$/, r: 0, k: { literal: "on off all" }, c: [{ cN: "meta", b: "\\s\\[", e: "\\]$" }, { cN: "variable", b: "[\\$%]\\{", e: "\\}", c: ["self", t] }, t, e.QSM] } }], i: /\S/ } }), n.registerLanguage("bash", function (e) { var t = { cN: "variable", v: [{ b: /\$[\w\d#@][\w\d_]*/ }, { b: /\$\{(.*?)}/ }] }, r = { cN: "string", b: /"/, e: /"/, c: [e.BE, t, { cN: "variable", b: /\$\(/, e: /\)/, c: [e.BE] }] }; return { aliases: ["sh", "zsh"], l: /\b-?[a-z\._]+\b/, k: { keyword: "if then else elif fi for while in do done case esac function", literal: "true false", built_in: "break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp", _: "-ne -eq -lt -gt -f -d -e -s -l -a" }, c: [{ cN: "meta", b: /^#![^\n]+sh\s*$/, r: 10 }, { cN: "function", b: /\w[\w\d_]*\s*\(\s*\)\s*\{/, rB: !0, c: [e.inherit(e.TM, { b: /\w[\w\d_]*/ })], r: 0 }, e.HCM, r, { cN: "", b: /\\"/ }, { cN: "string", b: /'/, e: /'/ }, t] } }), n.registerLanguage("coffeescript", function (e) { var t = { keyword: "in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super yield import export from as default await then unless until loop of by when and or is isnt not", literal: "true false null undefined yes no on off", built_in: "npm require console print module global window document" }, r = "[A-Za-z$_][0-9A-Za-z$_]*", a = { cN: "subst", b: /#\{/, e: /}/, k: t }, n = [e.BNM, e.inherit(e.CNM, { starts: { e: "(\\s*/)?", r: 0 } }), { cN: "string", v: [{ b: /'''/, e: /'''/, c: [e.BE] }, { b: /'/, e: /'/, c: [e.BE] }, { b: /"""/, e: /"""/, c: [e.BE, a] }, { b: /"/, e: /"/, c: [e.BE, a] }] }, { cN: "regexp", v: [{ b: "///", e: "///", c: [a, e.HCM] }, { b: "//[gim]*", r: 0 }, { b: /\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/ }] }, { b: "@" + r }, { sL: "javascript", eB: !0, eE: !0, v: [{ b: "```", e: "```" }, { b: "`", e: "`" }] }]; a.c = n; var i = e.inherit(e.TM, { b: r }), s = "(\\(.*\\))?\\s*\\B[-=]>", c = { cN: "params", b: "\\([^\\(]", rB: !0, c: [{ b: /\(/, e: /\)/, k: t, c: ["self"].concat(n) }] }; return { aliases: ["coffee", "cson", "iced"], k: t, i: /\/\*/, c: n.concat([e.C("###", "###"), e.HCM, { cN: "function", b: "^\\s*" + r + "\\s*=\\s*" + s, e: "[-=]>", rB: !0, c: [i, c] }, { b: /[:\(,=]\s*/, r: 0, c: [{ cN: "function", b: s, e: "[-=]>", rB: !0, c: [c] }] }, { cN: "class", bK: "class", e: "$", i: /[:="\[\]]/, c: [{ bK: "extends", eW: !0, i: /[:="\[\]]/, c: [i] }, i] }, { b: r + ":", e: ":", rB: !0, rE: !0, r: 0 }]) } }), n.registerLanguage("cpp", function (e) { var t = { cN: "keyword", b: "\\b[a-z\\d_]*_t\\b" }, r = { cN: "string", v: [{ b: '(u8?|U|L)?"', e: '"', i: "\\n", c: [e.BE] }, { b: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\((?:.|\n)*?\)\1"/ }, { b: "'\\\\?.", e: "'", i: "." }] }, a = { cN: "number", v: [{ b: "\\b(0b[01']+)" }, { b: "(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)" }, { b: "(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)" }], r: 0 }, n = { cN: "meta", b: /#\s*[a-z]+\b/, e: /$/, k: { "meta-keyword": "if else elif endif define undef warning error line pragma ifdef ifndef include" }, c: [{ b: /\\\n/, r: 0 }, e.inherit(r, { cN: "meta-string" }), { cN: "meta-string", b: /<[^\n>]*>/, e: /$/, i: "\\n" }, e.CLCM, e.CBCM] }, i = e.IR + "\\s*\\(", s = { keyword: "int float while private char catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignof constexpr decltype noexcept static_assert thread_local restrict _Bool complex _Complex _Imaginary atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and or not", built_in: "std string cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr", literal: "true false nullptr NULL" }, c = [t, e.CLCM, e.CBCM, a, r]; return { aliases: ["c", "cc", "h", "c++", "h++", "hpp", "hh", "hxx", "cxx"], k: s, i: "", k: s, c: ["self", t] }, { b: e.IR + "::", k: s }, { v: [{ b: /=/, e: /;/ }, { b: /\(/, e: /\)/ }, { bK: "new throw return else", e: /;/ }], k: s, c: c.concat([{ b: /\(/, e: /\)/, k: s, c: c.concat(["self"]), r: 0 }]), r: 0 }, { cN: "function", b: "(" + e.IR + "[\\*&\\s]+)+" + i, rB: !0, e: /[{;=]/, eE: !0, k: s, i: /[^\w\s\*&]/, c: [{ b: i, rB: !0, c: [e.TM], r: 0 }, { cN: "params", b: /\(/, e: /\)/, k: s, r: 0, c: [e.CLCM, e.CBCM, r, a, t, { b: /\(/, e: /\)/, k: s, r: 0, c: ["self", e.CLCM, e.CBCM, r, a, t] }] }, e.CLCM, e.CBCM, n] }, { cN: "class", bK: "class struct", e: /[{;:]/, c: [{ b: //, c: ["self"] }, e.TM] }]), exports: { preprocessor: n, strings: r, k: s } } }), n.registerLanguage("cs", function (e) { var t = { keyword: "abstract as base bool break byte case catch char checked const continue decimal default delegate do double enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long nameof object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual void volatile while add alias ascending async await by descending dynamic equals from get global group into join let on orderby partial remove select set value var where yield", literal: "null false true" }, r = { cN: "number", v: [{ b: "\\b(0b[01']+)" }, { b: "(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)" }, { b: "(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)" }], r: 0 }, a = { cN: "string", b: '@"', e: '"', c: [{ b: '""' }] }, n = e.inherit(a, { i: /\n/ }), i = { cN: "subst", b: "{", e: "}", k: t }, s = e.inherit(i, { i: /\n/ }), c = { cN: "string", b: /\$"/, e: '"', i: /\n/, c: [{ b: "{{" }, { b: "}}" }, e.BE, s] }, o = { cN: "string", b: /\$@"/, e: '"', c: [{ b: "{{" }, { b: "}}" }, { b: '""' }, i] }, l = e.inherit(o, { i: /\n/, c: [{ b: "{{" }, { b: "}}" }, { b: '""' }, s] }); i.c = [o, c, a, e.ASM, e.QSM, r, e.CBCM], s.c = [l, c, n, e.ASM, e.QSM, r, e.inherit(e.CBCM, { i: /\n/ })]; var u = { v: [o, c, a, e.ASM, e.QSM] }, d = e.IR + "(<" + e.IR + "(\\s*,\\s*" + e.IR + ")*>)?(\\[\\])?"; return { aliases: ["csharp", "c#"], k: t, i: /::/, c: [e.C("///", "$", { rB: !0, c: [{ cN: "doctag", v: [{ b: "///", r: 0 }, { b: "\x3c!--|--\x3e" }, { b: "" }] }] }), e.CLCM, e.CBCM, { cN: "meta", b: "#", e: "$", k: { "meta-keyword": "if else elif endif define undef warning error line region endregion pragma checksum" } }, u, r, { bK: "class interface", e: /[{;=]/, i: /[^\s:,]/, c: [e.TM, e.CLCM, e.CBCM] }, { bK: "namespace", e: /[{;=]/, i: /[^\s:]/, c: [e.inherit(e.TM, { b: "[a-zA-Z](\\.?\\w)*" }), e.CLCM, e.CBCM] }, { cN: "meta", b: "^\\s*\\[", eB: !0, e: "\\]", eE: !0, c: [{ cN: "meta-string", b: /"/, e: /"/ }] }, { bK: "new return throw await else", r: 0 }, { cN: "function", b: "(" + d + "\\s+)+" + e.IR + "\\s*\\(", rB: !0, e: /\s*[{;=]/, eE: !0, k: t, c: [{ b: e.IR + "\\s*\\(", rB: !0, c: [e.TM], r: 0 }, { cN: "params", b: /\(/, e: /\)/, eB: !0, eE: !0, k: t, r: 0, c: [u, r, e.CBCM] }, e.CLCM, e.CBCM] }] } }), n.registerLanguage("css", function (e) { var t = { b: /(?:[A-Z\_\.\-]+|--[a-zA-Z0-9_-]+)\s*:/, rB: !0, e: ";", eW: !0, c: [{ cN: "attribute", b: /\S/, e: ":", eE: !0, starts: { eW: !0, eE: !0, c: [{ b: /[\w-]+\(/, rB: !0, c: [{ cN: "built_in", b: /[\w-]+/ }, { b: /\(/, e: /\)/, c: [e.ASM, e.QSM] }] }, e.CSSNM, e.QSM, e.ASM, e.CBCM, { cN: "number", b: "#[0-9A-Fa-f]+" }, { cN: "meta", b: "!important" }] } }] }; return { cI: !0, i: /[=\/|'\$]/, c: [e.CBCM, { cN: "selector-id", b: /#[A-Za-z0-9_-]+/ }, { cN: "selector-class", b: /\.[A-Za-z0-9_-]+/ }, { cN: "selector-attr", b: /\[/, e: /\]/, i: "$" }, { cN: "selector-pseudo", b: /:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/ }, { b: "@(font-face|page)", l: "[a-z-]+", k: "font-face page" }, { b: "@", e: "[{;]", i: /:/, c: [{ cN: "keyword", b: /\w+/ }, { b: /\s/, eW: !0, eE: !0, r: 0, c: [e.ASM, e.QSM, e.CSSNM] }] }, { cN: "selector-tag", b: "[a-zA-Z-][a-zA-Z0-9_-]*", r: 0 }, { b: "{", e: "}", i: /\S/, c: [e.CBCM, t] }] } }), n.registerLanguage("diff", function (e) { return { aliases: ["patch"], c: [{ cN: "meta", r: 10, v: [{ b: /^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/ }, { b: /^\*\*\* +\d+,\d+ +\*\*\*\*$/ }, { b: /^\-\-\- +\d+,\d+ +\-\-\-\-$/ }] }, { cN: "comment", v: [{ b: /Index: /, e: /$/ }, { b: /={3,}/, e: /$/ }, { b: /^\-{3}/, e: /$/ }, { b: /^\*{3} /, e: /$/ }, { b: /^\+{3}/, e: /$/ }, { b: /\*{5}/, e: /\*{5}$/ }] }, { cN: "addition", b: "^\\+", e: "$" }, { cN: "deletion", b: "^\\-", e: "$" }, { cN: "addition", b: "^\\!", e: "$" }] } }), n.registerLanguage("http", function (e) { var t = "HTTP/[0-9\\.]+"; return { aliases: ["https"], i: "\\S", c: [{ b: "^" + t, e: "$", c: [{ cN: "number", b: "\\b\\d{3}\\b" }] }, { b: "^[A-Z]+ (.*?) " + t + "$", rB: !0, e: "$", c: [{ cN: "string", b: " ", e: " ", eB: !0, eE: !0 }, { b: t }, { cN: "keyword", b: "[A-Z]+" }] }, { cN: "attribute", b: "^\\w", e: ": ", eE: !0, i: "\\n|\\s|=", starts: { e: "$", r: 0 } }, { b: "\\n\\n", starts: { sL: [], eW: !0 } }] } }), n.registerLanguage("ini", function (e) { var t = { cN: "string", c: [e.BE], v: [{ b: "'''", e: "'''", r: 10 }, { b: '"""', e: '"""', r: 10 }, { b: '"', e: '"' }, { b: "'", e: "'" }] }; return { aliases: ["toml"], cI: !0, i: /\S/, c: [e.C(";", "$"), e.HCM, { cN: "section", b: /^\s*\[+/, e: /\]+/ }, { b: /^[a-z0-9\[\]_\.-]+\s*=\s*/, e: "$", rB: !0, c: [{ cN: "attr", b: /[a-z0-9\[\]_\.-]+/ }, { b: /=/, eW: !0, r: 0, c: [e.C(";", "$"), e.HCM, { cN: "literal", b: /\bon|off|true|false|yes|no\b/ }, { cN: "variable", v: [{ b: /\$[\w\d"][\w\d_]*/ }, { b: /\$\{(.*?)}/ }] }, t, { cN: "number", b: /([\+\-]+)?[\d]+_[\d_]+/ }, e.NM] }] }] } }), n.registerLanguage("java", function (e) { var t = "false synchronized int abstract float private char boolean var static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do", r = { cN: "number", b: "\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?", r: 0 }; return { aliases: ["jsp"], k: t, i: /<\/|#/, c: [e.C("/\\*\\*", "\\*/", { r: 0, c: [{ b: /\w+@/, r: 0 }, { cN: "doctag", b: "@[A-Za-z]+" }] }), e.CLCM, e.CBCM, e.ASM, e.QSM, { cN: "class", bK: "class interface", e: /[{;=]/, eE: !0, k: "class interface", i: /[:"\[\]]/, c: [{ bK: "extends implements" }, e.UTM] }, { bK: "new throw return else", r: 0 }, { cN: "function", b: "([À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*(<[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*(\\s*,\\s*[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*)*>)?\\s+)+" + e.UIR + "\\s*\\(", rB: !0, e: /[{;=]/, eE: !0, k: t, c: [{ b: e.UIR + "\\s*\\(", rB: !0, r: 0, c: [e.UTM] }, { cN: "params", b: /\(/, e: /\)/, k: t, r: 0, c: [e.ASM, e.QSM, e.CNM, e.CBCM] }, e.CLCM, e.CBCM] }, r, { cN: "meta", b: "@[A-Za-z]+" }] } }), n.registerLanguage("javascript", function (e) { var t = "[A-Za-z$_][0-9A-Za-z$_]*", r = { keyword: "in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as", literal: "true false null undefined NaN Infinity", built_in: "eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise" }, a = { cN: "number", v: [{ b: "\\b(0[bB][01]+)" }, { b: "\\b(0[oO][0-7]+)" }, { b: e.CNR }], r: 0 }, n = { cN: "subst", b: "\\$\\{", e: "\\}", k: r, c: [] }, i = { b: "html`", e: "", starts: { e: "`", rE: !1, c: [e.BE, n], sL: "xml" } }, s = { b: "css`", e: "", starts: { e: "`", rE: !1, c: [e.BE, n], sL: "css" } }, c = { cN: "string", b: "`", e: "`", c: [e.BE, n] }; n.c = [e.ASM, e.QSM, i, s, c, a, e.RM]; var o = n.c.concat([e.CBCM, e.CLCM]); return { aliases: ["js", "jsx"], k: r, c: [{ cN: "meta", r: 10, b: /^\s*['"]use (strict|asm)['"]/ }, { cN: "meta", b: /^#!/, e: /$/ }, e.ASM, e.QSM, i, s, c, e.CLCM, e.CBCM, a, { b: /[{,]\s*/, r: 0, c: [{ b: t + "\\s*:", rB: !0, r: 0, c: [{ cN: "attr", b: t, r: 0 }] }] }, { b: "(" + e.RSR + "|\\b(case|return|throw)\\b)\\s*", k: "return throw case", c: [e.CLCM, e.CBCM, e.RM, { cN: "function", b: "(\\(.*?\\)|" + t + ")\\s*=>", rB: !0, e: "\\s*=>", c: [{ cN: "params", v: [{ b: t }, { b: /\(\s*\)/ }, { b: /\(/, e: /\)/, eB: !0, eE: !0, k: r, c: o }] }] }, { cN: "", b: /\s/, e: /\s*/, skip: !0 }, { b: //, sL: "xml", c: [{ b: /<[A-Za-z0-9\\._:-]+\s*\/>/, skip: !0 }, { b: /<[A-Za-z0-9\\._:-]+/, e: /(\/[A-Za-z0-9\\._:-]+|[A-Za-z0-9\\._:-]+\/)>/, skip: !0, c: [{ b: /<[A-Za-z0-9\\._:-]+\s*\/>/, skip: !0 }, "self"] }] }], r: 0 }, { cN: "function", bK: "function", e: /\{/, eE: !0, c: [e.inherit(e.TM, { b: t }), { cN: "params", b: /\(/, e: /\)/, eB: !0, eE: !0, c: o }], i: /\[|%/ }, { b: /\$[(.]/ }, e.METHOD_GUARD, { cN: "class", bK: "class", e: /[{;=]/, eE: !0, i: /[:"\[\]]/, c: [{ bK: "extends" }, e.UTM] }, { bK: "constructor get set", e: /\{/, eE: !0 }], i: /#(?!!)/ } }), n.registerLanguage("json", function (e) { var t = { literal: "true false null" }, r = [e.QSM, e.CNM], a = { e: ",", eW: !0, eE: !0, c: r, k: t }, n = { b: "{", e: "}", c: [{ cN: "attr", b: /"/, e: /"/, c: [e.BE], i: "\\n" }, e.inherit(a, { b: /:/ })], i: "\\S" }, i = { b: "\\[", e: "\\]", c: [e.inherit(a)], i: "\\S" }; return r.splice(r.length, 0, n, i), { c: r, k: t, i: "\\S" } }), n.registerLanguage("makefile", function (e) { var t = { cN: "variable", v: [{ b: "\\$\\(" + e.UIR + "\\)", c: [e.BE] }, { b: /\$[@%`]+/ }] }] }] }; return { aliases: ["html", "xhtml", "rss", "atom", "xjb", "xsd", "xsl", "plist", "wsf"], cI: !0, c: [{ cN: "meta", b: "", r: 10, c: [{ b: "\\[", e: "\\]" }] }, e.C("\x3c!--", "--\x3e", { r: 10 }), { b: "<\\!\\[CDATA\\[", e: "\\]\\]>", r: 10 }, { cN: "meta", b: /<\?xml/, e: /\?>/, r: 10 }, { b: /<\?(php)?/, e: /\?>/, sL: "php", c: [{ b: "/\\*", e: "\\*/", skip: !0 }, { b: 'b"', e: '"', skip: !0 }, { b: "b'", e: "'", skip: !0 }, e.inherit(e.ASM, { i: null, cN: null, c: null, skip: !0 }), e.inherit(e.QSM, { i: null, cN: null, c: null, skip: !0 })] }, { cN: "tag", b: "|$)", e: ">", k: { name: "style" }, c: [t], starts: { e: "", rE: !0, sL: ["css", "xml"] } }, { cN: "tag", b: "|$)", e: ">", k: { name: "script" }, c: [t], starts: { e: "<\/script>", rE: !0, sL: ["actionscript", "javascript", "handlebars", "xml", "vbscript"] } }, { cN: "tag", b: "", c: [{ cN: "name", b: /[^\/><\s]+/, r: 0 }, t] }] } }), n.registerLanguage("markdown", function (e) { return { aliases: ["md", "mkdown", "mkd"], c: [{ cN: "section", v: [{ b: "^#{1,6}", e: "$" }, { b: "^.+?\\n[=-]{2,}$" }] }, { b: "<", e: ">", sL: "xml", r: 0 }, { cN: "bullet", b: "^\\s*([*+-]|(\\d+\\.))\\s+" }, { cN: "strong", b: "[*_]{2}.+?[*_]{2}" }, { cN: "emphasis", v: [{ b: "\\*.+?\\*" }, { b: "_.+?_", r: 0 }] }, { cN: "quote", b: "^>\\s+", e: "$" }, { cN: "code", v: [{ b: "^```w*s*$", e: "^```s*$" }, { b: "`.+?`" }, { b: "^( {4}|\t)", e: "$", r: 0 }] }, { b: "^[-\\*]{3,}", e: "$" }, { b: "\\[.+?\\][\\(\\[].*?[\\)\\]]", rB: !0, c: [{ cN: "string", b: "\\[", e: "\\]", eB: !0, rE: !0, r: 0 }, { cN: "link", b: "\\]\\(", e: "\\)", eB: !0, eE: !0 }, { cN: "symbol", b: "\\]\\[", e: "\\]", eB: !0, eE: !0 }], r: 10 }, { b: /^\[[^\n]+\]:/, rB: !0, c: [{ cN: "symbol", b: /\[/, e: /\]/, eB: !0, eE: !0 }, { cN: "link", b: /:\s*/, e: /$/, eB: !0 }] }] } }), n.registerLanguage("nginx", function (e) { var t = { cN: "variable", v: [{ b: /\$\d+/ }, { b: /\$\{/, e: /}/ }, { b: "[\\$\\@]" + e.UIR }] }, r = { eW: !0, l: "[a-z/_]+", k: { literal: "on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll" }, r: 0, i: "=>", c: [e.HCM, { cN: "string", c: [e.BE, t], v: [{ b: /"/, e: /"/ }, { b: /'/, e: /'/ }] }, { b: "([a-z]+):/", e: "\\s", eW: !0, eE: !0, c: [t] }, { cN: "regexp", c: [e.BE, t], v: [{ b: "\\s\\^", e: "\\s|{|;", rE: !0 }, { b: "~\\*?\\s+", e: "\\s|{|;", rE: !0 }, { b: "\\*(\\.[a-z\\-]+)+" }, { b: "([a-z\\-]+\\.)+\\*" }] }, { cN: "number", b: "\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b" }, { cN: "number", b: "\\b\\d+[kKmMgGdshdwy]*\\b", r: 0 }, t] }; return { aliases: ["nginxconf"], c: [e.HCM, { b: e.UIR + "\\s+{", rB: !0, e: "{", c: [{ cN: "section", b: e.UIR }], r: 0 }, { b: e.UIR + "\\s", e: ";|{", rB: !0, c: [{ cN: "attribute", b: e.UIR, starts: r }], r: 0 }], i: "[^\\s\\}]" } }), n.registerLanguage("objectivec", function (e) { var t = /[a-zA-Z@][a-zA-Z0-9_]*/, r = "@interface @class @protocol @implementation"; return { aliases: ["mm", "objc", "obj-c"], k: { keyword: "int float while char export sizeof typedef const struct for union unsigned long volatile static bool mutable if do return goto void enum else break extern asm case short default double register explicit signed typename this switch continue wchar_t inline readonly assign readwrite self @synchronized id typeof nonatomic super unichar IBOutlet IBAction strong weak copy in out inout bycopy byref oneway __strong __weak __block __autoreleasing @private @protected @public @try @property @end @throw @catch @finally @autoreleasepool @synthesize @dynamic @selector @optional @required @encode @package @import @defs @compatibility_alias __bridge __bridge_transfer __bridge_retained __bridge_retain __covariant __contravariant __kindof _Nonnull _Nullable _Null_unspecified __FUNCTION__ __PRETTY_FUNCTION__ __attribute__ getter setter retain unsafe_unretained nonnull nullable null_unspecified null_resettable class instancetype NS_DESIGNATED_INITIALIZER NS_UNAVAILABLE NS_REQUIRES_SUPER NS_RETURNS_INNER_POINTER NS_INLINE NS_AVAILABLE NS_DEPRECATED NS_ENUM NS_OPTIONS NS_SWIFT_UNAVAILABLE NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_REFINED_FOR_SWIFT NS_SWIFT_NAME NS_SWIFT_NOTHROW NS_DURING NS_HANDLER NS_ENDHANDLER NS_VALUERETURN NS_VOIDRETURN", literal: "false true FALSE TRUE nil YES NO NULL", built_in: "BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once" }, l: t, i: "" }] }] }, { cN: "class", b: "(" + r.split(" ").join("|") + ")\\b", e: "({|$)", eE: !0, k: r, l: t, c: [e.UTM] }, { b: "\\." + e.UIR, r: 0 }] } }), n.registerLanguage("perl", function (e) { var t = "getpwent getservent quotemeta msgrcv scalar kill dbmclose undef lc ma syswrite tr send umask sysopen shmwrite vec qx utime local oct semctl localtime readpipe do return format read sprintf dbmopen pop getpgrp not getpwnam rewinddir qqfileno qw endprotoent wait sethostent bless s|0 opendir continue each sleep endgrent shutdown dump chomp connect getsockname die socketpair close flock exists index shmgetsub for endpwent redo lstat msgctl setpgrp abs exit select print ref gethostbyaddr unshift fcntl syscall goto getnetbyaddr join gmtime symlink semget splice x|0 getpeername recv log setsockopt cos last reverse gethostbyname getgrnam study formline endhostent times chop length gethostent getnetent pack getprotoent getservbyname rand mkdir pos chmod y|0 substr endnetent printf next open msgsnd readdir use unlink getsockopt getpriority rindex wantarray hex system getservbyport endservent int chr untie rmdir prototype tell listen fork shmread ucfirst setprotoent else sysseek link getgrgid shmctl waitpid unpack getnetbyname reset chdir grep split require caller lcfirst until warn while values shift telldir getpwuid my getprotobynumber delete and sort uc defined srand accept package seekdir getprotobyname semop our rename seek if q|0 chroot sysread setpwent no crypt getc chown sqrt write setnetent setpriority foreach tie sin msgget map stat getlogin unless elsif truncate exec keys glob tied closedirioctl socket readlink eval xor readline binmode setservent eof ord bind alarm pipe atan2 getgrent exp time push setgrent gt lt or ne m|0 break given say state when", r = { cN: "subst", b: "[$@]\\{", e: "\\}", k: t }, a = { b: "->{", e: "}" }, n = { v: [{ b: /\$\d/ }, { b: /[\$%@](\^\w\b|#\w+(::\w+)*|{\w+}|\w+(::\w*)*)/ }, { b: /[\$%@][^\s\w{]/, r: 0 }] }, i = [e.BE, r, n], s = [n, e.HCM, e.C("^\\=\\w", "\\=cut", { eW: !0 }), a, { cN: "string", c: i, v: [{ b: "q[qwxr]?\\s*\\(", e: "\\)", r: 5 }, { b: "q[qwxr]?\\s*\\[", e: "\\]", r: 5 }, { b: "q[qwxr]?\\s*\\{", e: "\\}", r: 5 }, { b: "q[qwxr]?\\s*\\|", e: "\\|", r: 5 }, { b: "q[qwxr]?\\s*\\<", e: "\\>", r: 5 }, { b: "qw\\s+q", e: "q", r: 5 }, { b: "'", e: "'", c: [e.BE] }, { b: '"', e: '"' }, { b: "`", e: "`", c: [e.BE] }, { b: "{\\w+}", c: [], r: 0 }, { b: "-?\\w+\\s*\\=\\>", c: [], r: 0 }] }, { cN: "number", b: "(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b", r: 0 }, { b: "(\\/\\/|" + e.RSR + "|\\b(split|return|print|reverse|grep)\\b)\\s*", k: "split return print reverse grep", r: 0, c: [e.HCM, { cN: "regexp", b: "(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*", r: 10 }, { cN: "regexp", b: "(m|qr)?/", e: "/[a-z]*", c: [e.BE], r: 0 }] }, { cN: "function", bK: "sub", e: "(\\s*\\(.*?\\))?[;{]", eE: !0, r: 5, c: [e.TM] }, { b: "-\\w\\b", r: 0 }, { b: "^__DATA__$", e: "^__END__$", sL: "mojolicious", c: [{ b: "^@@.*", e: "$", cN: "comment" }] }]; return r.c = s, { aliases: ["pl", "pm"], l: /[\w\.]+/, k: t, c: a.c = s } }), n.registerLanguage("php", function (e) { var t = { b: "\\$+[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]*" }, r = { cN: "meta", b: /<\?(php)?|\?>/ }, a = { cN: "string", c: [e.BE, r], v: [{ b: 'b"', e: '"' }, { b: "b'", e: "'" }, e.inherit(e.ASM, { i: null }), e.inherit(e.QSM, { i: null })] }, n = { v: [e.BNM, e.CNM] }; return { aliases: ["php", "php3", "php4", "php5", "php6", "php7"], cI: !0, k: "and include_once list abstract global private echo interface as static endswitch array null if endwhile or const for endforeach self var while isset public protected exit foreach throw elseif include __FILE__ empty require_once do xor return parent clone use __CLASS__ __LINE__ else break print eval new catch __METHOD__ case exception default die require __FUNCTION__ enddeclare final try switch continue endfor endif declare unset true false trait goto instanceof insteadof __DIR__ __NAMESPACE__ yield finally", c: [e.HCM, e.C("//", "$", { c: [r] }), e.C("/\\*", "\\*/", { c: [{ cN: "doctag", b: "@[A-Za-z]+" }] }), e.C("__halt_compiler.+?;", !1, { eW: !0, k: "__halt_compiler", l: e.UIR }), { cN: "string", b: /<<<['"]?\w+['"]?$/, e: /^\w+;?$/, c: [e.BE, { cN: "subst", v: [{ b: /\$\w+/ }, { b: /\{\$/, e: /\}/ }] }] }, r, { cN: "keyword", b: /\$this\b/ }, t, { b: /(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/ }, { cN: "function", bK: "function", e: /[;{]/, eE: !0, i: "\\$|\\[|%", c: [e.UTM, { cN: "params", b: "\\(", e: "\\)", c: ["self", t, e.CBCM, a, n] }] }, { cN: "class", bK: "class interface", e: "{", eE: !0, i: /[:\(\$"]/, c: [{ bK: "extends implements" }, e.UTM] }, { bK: "namespace", e: ";", i: /[\.']/, c: [e.UTM] }, { bK: "use", e: ";", c: [e.UTM] }, { b: "=>" }, a, n] } }), n.registerLanguage("properties", function (e) { var t = "[ \\t\\f]*", r = "(" + t + "[:=]" + t + "|[ \\t\\f]+)", a = "([^\\\\\\W:= \\t\\f\\n]|\\\\.)+", n = "([^\\\\:= \\t\\f\\n]|\\\\.)+", i = { e: r, r: 0, starts: { cN: "string", e: /$/, r: 0, c: [{ b: "\\\\\\n" }] } }; return { cI: !0, i: /\S/, c: [e.C("^\\s*[!#]", "$"), { b: a + r, rB: !0, c: [{ cN: "attr", b: a, endsParent: !0, r: 0 }], starts: i }, { b: n + r, rB: !0, r: 0, c: [{ cN: "meta", b: n, endsParent: !0, r: 0 }], starts: i }, { cN: "attr", r: 0, b: n + t + "$" }] } }), n.registerLanguage("python", function (e) { var t = { keyword: "and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10", built_in: "Ellipsis NotImplemented", literal: "False None True" }, r = { cN: "meta", b: /^(>>>|\.\.\.) / }, a = { cN: "subst", b: /\{/, e: /\}/, k: t, i: /#/ }, n = { cN: "string", c: [e.BE], v: [{ b: /(u|b)?r?'''/, e: /'''/, c: [e.BE, r], r: 10 }, { b: /(u|b)?r?"""/, e: /"""/, c: [e.BE, r], r: 10 }, { b: /(fr|rf|f)'''/, e: /'''/, c: [e.BE, r, a] }, { b: /(fr|rf|f)"""/, e: /"""/, c: [e.BE, r, a] }, { b: /(u|r|ur)'/, e: /'/, r: 10 }, { b: /(u|r|ur)"/, e: /"/, r: 10 }, { b: /(b|br)'/, e: /'/ }, { b: /(b|br)"/, e: /"/ }, { b: /(fr|rf|f)'/, e: /'/, c: [e.BE, a] }, { b: /(fr|rf|f)"/, e: /"/, c: [e.BE, a] }, e.ASM, e.QSM] }, i = { cN: "number", r: 0, v: [{ b: e.BNR + "[lLjJ]?" }, { b: "\\b(0o[0-7]+)[lLjJ]?" }, { b: e.CNR + "[lLjJ]?" }] }, s = { cN: "params", b: /\(/, e: /\)/, c: ["self", r, i, n] }; return a.c = [n, i, r], { aliases: ["py", "gyp", "ipython"], k: t, i: /(<\/|->|\?)|=>/, c: [r, i, n, e.HCM, { v: [{ cN: "function", bK: "def" }, { cN: "class", bK: "class" }], e: /:/, i: /[${=;\n,]/, c: [e.UTM, s, { b: /->/, eW: !0, k: "None" }] }, { cN: "meta", b: /^[\t ]*@/, e: /$/ }, { b: /\b(print|exec)\(/ }] } }), n.registerLanguage("ruby", function (e) { var t = "[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?", r = { keyword: "and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor", literal: "true false nil" }, a = { cN: "doctag", b: "@[A-Za-z]+" }, n = { b: "#<", e: ">" }, i = [e.C("#", "$", { c: [a] }), e.C("^\\=begin", "^\\=end", { c: [a], r: 10 }), e.C("^__END__", "\\n$")], s = { cN: "subst", b: "#\\{", e: "}", k: r }, c = { cN: "string", c: [e.BE, s], v: [{ b: /'/, e: /'/ }, { b: /"/, e: /"/ }, { b: /`/, e: /`/ }, { b: "%[qQwWx]?\\(", e: "\\)" }, { b: "%[qQwWx]?\\[", e: "\\]" }, { b: "%[qQwWx]?{", e: "}" }, { b: "%[qQwWx]?<", e: ">" }, { b: "%[qQwWx]?/", e: "/" }, { b: "%[qQwWx]?%", e: "%" }, { b: "%[qQwWx]?-", e: "-" }, { b: "%[qQwWx]?\\|", e: "\\|" }, { b: /\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/ }, { b: /<<[-~]?'?(\w+)(?:.|\n)*?\n\s*\1\b/, rB: !0, c: [{ b: /<<[-~]?'?/ }, { b: /\w+/, endSameAsBegin: !0, c: [e.BE, s] }] }] }, o = { cN: "params", b: "\\(", e: "\\)", endsParent: !0, k: r }, l = [c, n, { cN: "class", bK: "class module", e: "$|;", i: /=/, c: [e.inherit(e.TM, { b: "[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?" }), { b: "<\\s*", c: [{ b: "(" + e.IR + "::)?" + e.IR }] }].concat(i) }, { cN: "function", bK: "def", e: "$|;", c: [e.inherit(e.TM, { b: t }), o].concat(i) }, { b: e.IR + "::" }, { cN: "symbol", b: e.UIR + "(\\!|\\?)?:", r: 0 }, { cN: "symbol", b: ":(?!\\s)", c: [c, { b: t }], r: 0 }, { cN: "number", b: "(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b", r: 0 }, { b: "(\\$\\W)|((\\$|\\@\\@?)(\\w+))" }, { cN: "params", b: /\|/, e: /\|/, k: r }, { b: "(" + e.RSR + "|unless)\\s*", k: "unless", c: [n, { cN: "regexp", c: [e.BE, s], i: /\n/, v: [{ b: "/", e: "/[a-z]*" }, { b: "%r{", e: "}[a-z]*" }, { b: "%r\\(", e: "\\)[a-z]*" }, { b: "%r!", e: "![a-z]*" }, { b: "%r\\[", e: "\\][a-z]*" }] }].concat(i), r: 0 }].concat(i); s.c = l; var u = [{ b: /^\s*=>/, starts: { e: "$", c: o.c = l } }, { cN: "meta", b: "^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+>|(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>)", starts: { e: "$", c: l } }]; return { aliases: ["rb", "gemspec", "podspec", "thor", "irb"], k: r, i: /\/\*/, c: i.concat(u).concat(l) } }), n.registerLanguage("shell", function (e) { return { aliases: ["console"], c: [{ cN: "meta", b: "^\\s{0,3}[\\w\\d\\[\\]()@-]*[>%$#]", starts: { e: "$", sL: "bash" } }] } }), n.registerLanguage("sql", function (e) { var t = e.C("--", "$"); return { cI: !0, i: /[<>{}*]/, c: [{ bK: "begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment values with", e: /;/, eW: !0, l: /[\w\.]+/, k: { keyword: "as abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias all allocate allow alter always analyze ancillary and anti any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound bucket buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain explode export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force foreign form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour hours http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lateral lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minutes minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notnull notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second seconds section securefile security seed segment select self semi sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tablesample tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unnest unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace window with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek", literal: "true false null unknown", built_in: "array bigint binary bit blob bool boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text time timestamp tinyint varchar varying void" }, c: [{ cN: "string", b: "'", e: "'", c: [e.BE, { b: "''" }] }, { cN: "string", b: '"', e: '"', c: [e.BE, { b: '""' }] }, { cN: "string", b: "`", e: "`", c: [e.BE] }, e.CNM, e.CBCM, t, e.HCM] }, e.CBCM, t, e.HCM] } }), n.registerLanguage("yaml", function (e) { var t = "true false yes no null", r = "^[ \\-]*", a = "[a-zA-Z_][\\w\\-]*", n = { cN: "attr", v: [{ b: r + a + ":" }, { b: r + '"' + a + '":' }, { b: r + "'" + a + "':" }] }, i = { cN: "string", r: 0, v: [{ b: /'/, e: /'/ }, { b: /"/, e: /"/ }, { b: /\S+/ }], c: [e.BE, { cN: "template-variable", v: [{ b: "{{", e: "}}" }, { b: "%{", e: "}" }] }] }; return { cI: !0, aliases: ["yml", "YAML", "yaml"], c: [n, { cN: "meta", b: "^---s*$", r: 10 }, { cN: "string", b: "[\\|>] *$", rE: !0, c: i.c, e: n.v[0].b }, { b: "<%[%=-]?", e: "[%-]?%>", sL: "ruby", eB: !0, eE: !0, r: 0 }, { cN: "type", b: "!" + e.UIR }, { cN: "type", b: "!!" + e.UIR }, { cN: "meta", b: "&" + e.UIR + "$" }, { cN: "meta", b: "\\*" + e.UIR + "$" }, { cN: "bullet", b: "^ *-", r: 0 }, e.HCM, { bK: t, k: { literal: t } }, e.CNM, i] } }), n }); \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/js/htmlparser.min.js b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/js/htmlparser.min.js new file mode 100644 index 0000000..c1281c5 --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/js/htmlparser.min.js @@ -0,0 +1,22 @@ +/*********************************************** +Copyright 2010, 2011, Chris Winberry . All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +***********************************************/ +/* v1.7.6 */ +(function(){function e(a,c){this._options=c?c:{};void 0==this._options.includeLocation&&(this._options.includeLocation=!1);this.validateHandler(a);this._handler=a;this.reset()}function j(a){j.super_.call(this,a,{ignoreWhitespace:!0,verbose:!1,enforceEmptyTags:!1})}function g(a,c){this.reset();this._options=c?c:{};void 0==this._options.ignoreWhitespace&&(this._options.ignoreWhitespace=!1);void 0==this._options.verbose&&(this._options.verbose=!0);void 0==this._options.enforceEmptyTags&&(this._options.enforceEmptyTags= !0);"function"==typeof a&&(this._callback=a)}if(!("function"==typeof require&&"object"==typeof exports&&"object"==typeof module&&"string"==typeof __filename&&"string"==typeof __dirname)){if(this.Tautologistics){if(this.Tautologistics.NodeHtmlParser)return}else this.Tautologistics={};this.Tautologistics.NodeHtmlParser={};exports=this.Tautologistics.NodeHtmlParser}var d={Text:"text",Directive:"directive",Comment:"comment",Script:"script",Style:"style",Tag:"tag"};e._reTrim=/(^\s+|\s+$)/g;e._reTrimComment= /(^\!--|--$)/g;e._reWhitespace=/\s/g;e._reTagName=/^\s*(\/?)\s*([^\s\/]+)/;e._reAttrib=/([^=<>\"\'\s]+)\s*=\s*"([^"]*)"|([^=<>\"\'\s]+)\s*=\s*'([^']*)'|([^=<>\"\'\s]+)\s*=\s*([^'"\s]+)|([^=<>\"\'\s\/]+)/g;e._reTags=/[\<\>]/g;e.prototype.parseComplete=function(a){this.reset();this.parseChunk(a);this.done()};e.prototype.parseChunk=function(a){this._done&&this.handleError(Error("Attempted to parse chunk after parsing already done"));this._buffer+=a;this.parseTags()};e.prototype.done=function(){if(!this._done){this._done= !0;if(this._buffer.length){var a=this._buffer;this._buffer="";a={raw:a,data:this._parseState==d.Text?a:a.replace(e._reTrim,""),type:this._parseState};if(this._parseState==d.Tag||this._parseState==d.Script||this._parseState==d.Style)a.name=this.parseTagName(a.data);this.parseAttribs(a);this._elements.push(a)}this.writeHandler();this._handler.done()}};e.prototype.reset=function(){this._buffer="";this._done=!1;this._elements=[];this._next=this._current=this._elementsCurrent=0;this._location={row:0,col:0, charOffset:0,inBuffer:0};this._parseState=d.Text;this._prevTagSep="";this._tagStack=[];this._handler.reset()};e.prototype._options=null;e.prototype._handler=null;e.prototype._buffer=null;e.prototype._done=!1;e.prototype._elements=null;e.prototype._elementsCurrent=0;e.prototype._current=0;e.prototype._next=0;e.prototype._location=null;e.prototype._parseState=d.Text;e.prototype._prevTagSep="";e.prototype._tagStack=null;e.prototype.parseTagAttribs=function(a){for(var c=a.length,b=0;bc.length)){var b;for(e._reAttrib.lastIndex=0;b=e._reAttrib.exec(c);)void 0==a.attribs&&(a.attribs={}),"string"==typeof b[1]&&b[1].length?a.attribs[b[1]]=b[2]:"string"==typeof b[3]&&b[3].length?a.attribs[b[3].toString()]=b[4].toString():"string"==typeof b[5]&& b[5].length?a.attribs[b[5]]=b[6]:"string"==typeof b[7]&&b[7].length&&(a.attribs[b[7]]=b[7])}}};e.prototype.parseTagName=function(a){if(null==a||""==a)return"";a=e._reTagName.exec(a);return!a?"":(a[1]?"/":"")+a[2]};e.prototype.parseTags=function(){for(var a=this._buffer.length-1;e._reTags.test(this._buffer);){this._next=e._reTags.lastIndex-1;var c=this._buffer.charAt(this._next),b=this._buffer.substring(this._current,this._next),b={raw:b,data:this._parseState==d.Text?b:b.replace(e._reTrim,""),type:this._parseState}, f=this.parseTagName(b.data);if(this._tagStack.length)if(this._tagStack[this._tagStack.length-1]==d.Script)if("/script"==f.toLowerCase())this._tagStack.pop();else{if(0!=b.raw.indexOf("!--")&&(b.type=d.Text,this._elements.length&&this._elements[this._elements.length-1].type==d.Text)){var h=this._elements[this._elements.length-1];h.raw=h.data=h.raw+this._prevTagSep+b.raw;b.raw=b.data=""}}else this._tagStack[this._tagStack.length-1]==d.Style?"/style"==f.toLowerCase()?this._tagStack.pop():0!=b.raw.indexOf("!--")&& (b.type=d.Text,this._elements.length&&this._elements[this._elements.length-1].type==d.Text?(h=this._elements[this._elements.length-1],""!=b.raw?(h.raw=h.data=h.raw+this._prevTagSep+b.raw,b.raw=b.data=""):h.raw=h.data=h.raw+this._prevTagSep):""!=b.raw&&(b.raw=b.data=b.raw)):this._tagStack[this._tagStack.length-1]==d.Comment&&(h=b.raw.length,"-"==b.raw.charAt(h-2)&&"-"==b.raw.charAt(h-1)&&">"==c?(this._tagStack.pop(),this._elements.length&&this._elements[this._elements.length-1].type==d.Comment?(h= this._elements[this._elements.length-1],h.raw=h.data=(h.raw+b.raw).replace(e._reTrimComment,""),b.raw=b.data="",b.type=d.Text):b.type=d.Comment):(b.type=d.Comment,this._elements.length&&this._elements[this._elements.length-1].type==d.Comment?(h=this._elements[this._elements.length-1],h.raw=h.data=h.raw+b.raw+c,b.raw=b.data="",b.type=d.Text):b.raw=b.data=b.raw+c));if(b.type==d.Tag&&(b.name=f,f=f.toLowerCase(),0==b.raw.indexOf("!--")?(b.type=d.Comment,delete b.name,h=b.raw.length,"-"==b.raw.charAt(h- 1)&&"-"==b.raw.charAt(h-2)&&">"==c?b.raw=b.data=b.raw.replace(e._reTrimComment,""):(b.raw+=c,this._tagStack.push(d.Comment))):0==b.raw.indexOf("!")||0==b.raw.indexOf("?")?b.type=d.Directive:"script"==f?(b.type=d.Script,"/"!=b.data.charAt(b.data.length-1)&&this._tagStack.push(d.Script)):"/script"==f?b.type=d.Script:"style"==f?(b.type=d.Style,"/"!=b.data.charAt(b.data.length-1)&&this._tagStack.push(d.Style)):"/style"==f&&(b.type=d.Style),b.name&&"/"==b.name.charAt(0)))b.data=b.name;if(""!=b.raw||b.type!= d.Text)this._options.includeLocation&&!b.location&&(b.location=this.getLocation(b.type==d.Tag)),this.parseAttribs(b),this._elements.push(b),b.type!=d.Text&&b.type!=d.Comment&&b.type!=d.Directive&&"/"==b.data.charAt(b.data.length-1)&&this._elements.push({raw:"/"+b.name,data:"/"+b.name,name:"/"+b.name,type:b.type});this._parseState="<"==c?d.Tag:d.Text;this._current=this._next+1;this._prevTagSep=c}this._options.includeLocation&&(this.getLocation(),this._location.row+=this._location.inBuffer,this._location.inBuffer= 0,this._location.charOffset=0);this._buffer=this._current<=a?this._buffer.substring(this._current):"";this._current=0;this.writeHandler()};e.prototype.getLocation=function(a){for(var c=this._location,b=this._current-(a?1:0),d=a&&0==c.charOffset&&0==this._current;c.charOffset=d)return g;if(b&&c.children)c= c.children;else if(!(c instanceof Array))return g;for(i=0;i=d);i++);return g},getElementById:function(a,c,b){a=f.getElements({id:a},c,b,1);return a.length?a[0]:null},getElementsByTagName:function(a,c,b,d){return f.getElements({tag_name:a},c,b,d)},getElementsByTagType:function(a,c,b,d){return f.getElements({tag_type:a},c,b,d)}};exports.Parser=e;exports.DefaultHandler=g;exports.RssHandler=j;exports.ElementType=d;exports.DomUtils=f})(); \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/js/marked.min.js b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/js/marked.min.js new file mode 100644 index 0000000..2ff9e28 --- /dev/null +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/js/marked.min.js @@ -0,0 +1,6 @@ +/** + * marked - a markdown parser + * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT Licensed) + * https://github.com/markedjs/marked + */ +!function (e) { "use strict"; var x = { newline: /^\n+/, code: /^( {4}[^\n]+\n*)+/, fences: /^ {0,3}(`{3,}|~{3,})([^`~\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/, hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/, heading: /^ {0,3}(#{1,6}) +([^\n]*?)(?: +#+)? *(?:\n+|$)/, blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/, list: /^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, html: "^ {0,3}(?:<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?\\?>\\n*|\\n*|\\n*|)[\\s\\S]*?(?:\\n{2,}|$)|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$))", def: /^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/, nptable: g, table: g, lheading: /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/, _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html)[^\n]+)*)/, text: /^[^\n]+/ }; function a(e) { this.tokens = [], this.tokens.links = Object.create(null), this.options = e || k.defaults, this.rules = x.normal, this.options.pedantic ? this.rules = x.pedantic : this.options.gfm && (this.rules = x.gfm) } x._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/, x._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/, x.def = i(x.def).replace("label", x._label).replace("title", x._title).getRegex(), x.bullet = /(?:[*+-]|\d{1,9}\.)/, x.item = /^( *)(bull) ?[^\n]*(?:\n(?!\1bull ?)[^\n]*)*/, x.item = i(x.item, "gm").replace(/bull/g, x.bullet).getRegex(), x.list = i(x.list).replace(/bull/g, x.bullet).replace("hr", "\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def", "\\n+(?=" + x.def.source + ")").getRegex(), x._tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul", x._comment = //, x.html = i(x.html, "i").replace("comment", x._comment).replace("tag", x._tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(), x.paragraph = i(x._paragraph).replace("hr", x.hr).replace("heading", " {0,3}#{1,6} +").replace("|lheading", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}|~{3,})[^`\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|!--)").replace("tag", x._tag).getRegex(), x.blockquote = i(x.blockquote).replace("paragraph", x.paragraph).getRegex(), x.normal = f({}, x), x.gfm = f({}, x.normal, { nptable: /^ *([^|\n ].*\|.*)\n *([-:]+ *\|[-| :]*)(?:\n((?:.*[^>\n ].*(?:\n|$))*)\n*|$)/, table: /^ *\|(.+)\n *\|?( *[-:]+[-| :]*)(?:\n((?: *[^>\n ].*(?:\n|$))*)\n*|$)/ }), x.pedantic = f({}, x.normal, { html: i("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment", x._comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/, fences: g, paragraph: i(x.normal._paragraph).replace("hr", x.hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", x.lheading).replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").getRegex() }), a.rules = x, a.lex = function (e, t) { return new a(t).lex(e) }, a.prototype.lex = function (e) { return e = e.replace(/\r\n|\r/g, "\n").replace(/\t/g, " ").replace(/\u00a0/g, " ").replace(/\u2424/g, "\n"), this.token(e, !0) }, a.prototype.token = function (e, t) { var n, r, s, i, l, o, a, h, p, u, c, g, f, d, m, k; for (e = e.replace(/^ +$/gm, "") ; e;) if ((s = this.rules.newline.exec(e)) && (e = e.substring(s[0].length), 1 < s[0].length && this.tokens.push({ type: "space" })), s = this.rules.code.exec(e)) { var b = this.tokens[this.tokens.length - 1]; e = e.substring(s[0].length), b && "paragraph" === b.type ? b.text += "\n" + s[0].trimRight() : (s = s[0].replace(/^ {4}/gm, ""), this.tokens.push({ type: "code", codeBlockStyle: "indented", text: this.options.pedantic ? s : w(s, "\n") })) } else if (s = this.rules.fences.exec(e)) e = e.substring(s[0].length), this.tokens.push({ type: "code", lang: s[2] ? s[2].trim() : s[2], text: s[3] || "" }); else if (s = this.rules.heading.exec(e)) e = e.substring(s[0].length), this.tokens.push({ type: "heading", depth: s[1].length, text: s[2] }); else if ((s = this.rules.nptable.exec(e)) && (o = { type: "table", header: y(s[1].replace(/^ *| *\| *$/g, "")), align: s[2].replace(/^ *|\| *$/g, "").split(/ *\| */), cells: s[3] ? s[3].replace(/\n$/, "").split("\n") : [] }).header.length === o.align.length) { for (e = e.substring(s[0].length), c = 0; c < o.align.length; c++) /^ *-+: *$/.test(o.align[c]) ? o.align[c] = "right" : /^ *:-+: *$/.test(o.align[c]) ? o.align[c] = "center" : /^ *:-+ *$/.test(o.align[c]) ? o.align[c] = "left" : o.align[c] = null; for (c = 0; c < o.cells.length; c++) o.cells[c] = y(o.cells[c], o.header.length); this.tokens.push(o) } else if (s = this.rules.hr.exec(e)) e = e.substring(s[0].length), this.tokens.push({ type: "hr" }); else if (s = this.rules.blockquote.exec(e)) e = e.substring(s[0].length), this.tokens.push({ type: "blockquote_start" }), s = s[0].replace(/^ *> ?/gm, ""), this.token(s, t), this.tokens.push({ type: "blockquote_end" }); else if (s = this.rules.list.exec(e)) { for (e = e.substring(s[0].length), a = { type: "list_start", ordered: d = 1 < (i = s[2]).length, start: d ? +i : "", loose: !1 }, this.tokens.push(a), n = !(h = []), f = (s = s[0].match(this.rules.item)).length, c = 0; c < f; c++) u = (o = s[c]).length, ~(o = o.replace(/^ *([*+-]|\d+\.) */, "")).indexOf("\n ") && (u -= o.length, o = this.options.pedantic ? o.replace(/^ {1,4}/gm, "") : o.replace(new RegExp("^ {1," + u + "}", "gm"), "")), c !== f - 1 && (l = x.bullet.exec(s[c + 1])[0], (1 < i.length ? 1 === l.length : 1 < l.length || this.options.smartLists && l !== i) && (e = s.slice(c + 1).join("\n") + e, c = f - 1)), r = n || /\n\n(?!\s*$)/.test(o), c !== f - 1 && (n = "\n" === o.charAt(o.length - 1), r || (r = n)), r && (a.loose = !0), k = void 0, (m = /^\[[ xX]\] /.test(o)) && (k = " " !== o[1], o = o.replace(/^\[[ xX]\] +/, "")), p = { type: "list_item_start", task: m, checked: k, loose: r }, h.push(p), this.tokens.push(p), this.token(o, !1), this.tokens.push({ type: "list_item_end" }); if (a.loose) for (f = h.length, c = 0; c < f; c++) h[c].loose = !0; this.tokens.push({ type: "list_end" }) } else if (s = this.rules.html.exec(e)) e = e.substring(s[0].length), this.tokens.push({ type: this.options.sanitize ? "paragraph" : "html", pre: !this.options.sanitizer && ("pre" === s[1] || "script" === s[1] || "style" === s[1]), text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(s[0]) : _(s[0]) : s[0] }); else if (t && (s = this.rules.def.exec(e))) e = e.substring(s[0].length), s[3] && (s[3] = s[3].substring(1, s[3].length - 1)), g = s[1].toLowerCase().replace(/\s+/g, " "), this.tokens.links[g] || (this.tokens.links[g] = { href: s[2], title: s[3] }); else if ((s = this.rules.table.exec(e)) && (o = { type: "table", header: y(s[1].replace(/^ *| *\| *$/g, "")), align: s[2].replace(/^ *|\| *$/g, "").split(/ *\| */), cells: s[3] ? s[3].replace(/\n$/, "").split("\n") : [] }).header.length === o.align.length) { for (e = e.substring(s[0].length), c = 0; c < o.align.length; c++) /^ *-+: *$/.test(o.align[c]) ? o.align[c] = "right" : /^ *:-+: *$/.test(o.align[c]) ? o.align[c] = "center" : /^ *:-+ *$/.test(o.align[c]) ? o.align[c] = "left" : o.align[c] = null; for (c = 0; c < o.cells.length; c++) o.cells[c] = y(o.cells[c].replace(/^ *\| *| *\| *$/g, ""), o.header.length); this.tokens.push(o) } else if (s = this.rules.lheading.exec(e)) e = e.substring(s[0].length), this.tokens.push({ type: "heading", depth: "=" === s[2].charAt(0) ? 1 : 2, text: s[1] }); else if (t && (s = this.rules.paragraph.exec(e))) e = e.substring(s[0].length), this.tokens.push({ type: "paragraph", text: "\n" === s[1].charAt(s[1].length - 1) ? s[1].slice(0, -1) : s[1] }); else if (s = this.rules.text.exec(e)) e = e.substring(s[0].length), this.tokens.push({ type: "text", text: s[0] }); else if (e) throw new Error("Infinite loop on byte: " + e.charCodeAt(0)); return this.tokens }; var n = { escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/, url: g, tag: "^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^", link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/, reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/, nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/, strong: /^__([^\s_])__(?!_)|^\*\*([^\s*])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/, em: /^_([^\s_])_(?!_)|^\*([^\s*<\[])\*(?!\*)|^_([^\s<][\s\S]*?[^\s_])_(?!_|[^\spunctuation])|^_([^\s_<][\s\S]*?[^\s])_(?!_|[^\spunctuation])|^\*([^\s<"][\s\S]*?[^\s\*])\*(?!\*|[^\spunctuation])|^\*([^\s*"<\[][\s\S]*?[^\s])\*(?!\*)/, code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, br: /^( {2,}|\\)\n(?!\s*$)/, del: g, text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\?@\\[^_{|}~", n.em = i(n.em).replace(/punctuation/g, n._punctuation).getRegex(), n._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g, n._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/, n._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/, n.autolink = i(n.autolink).replace("scheme", n._scheme).replace("email", n._email).getRegex(), n._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/, n.tag = i(n.tag).replace("comment", x._comment).replace("attribute", n._attribute).getRegex(), n._label = /(?:\[[^\[\]]*\]|\\.|`[^`]*`|[^\[\]\\`])*?/, n._href = /<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*/, n._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/, n.link = i(n.link).replace("label", n._label).replace("href", n._href).replace("title", n._title).getRegex(), n.reflink = i(n.reflink).replace("label", n._label).getRegex(), n.normal = f({}, n), n.pedantic = f({}, n.normal, { strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/, link: i(/^!?\[(label)\]\((.*?)\)/).replace("label", n._label).getRegex(), reflink: i(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", n._label).getRegex() }), n.gfm = f({}, n.normal, { escape: i(n.escape).replace("])", "~|])").getRegex(), _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/, url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, _backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/, del: /^~+(?=\S)([\s\S]*?\S)~+/, text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\/i.test(i[0]) && (this.inLink = !1), !this.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(i[0]) ? this.inRawBlock = !0 : this.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(i[0]) && (this.inRawBlock = !1), e = e.substring(i[0].length), o += this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(i[0]) : _(i[0]) : i[0]; else if (i = this.rules.link.exec(e)) { var a = d(i[2], "()"); if (-1 < a) { var h = 4 + i[1].length + a; i[2] = i[2].substring(0, a), i[0] = i[0].substring(0, h).trim(), i[3] = "" } e = e.substring(i[0].length), this.inLink = !0, r = i[2], s = this.options.pedantic ? (t = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(r)) ? (r = t[1], t[3]) : "" : i[3] ? i[3].slice(1, -1) : "", r = r.trim().replace(/^<([\s\S]*)>$/, "$1"), o += this.outputLink(i, { href: p.escapes(r), title: p.escapes(s) }), this.inLink = !1 } else if ((i = this.rules.reflink.exec(e)) || (i = this.rules.nolink.exec(e))) { if (e = e.substring(i[0].length), t = (i[2] || i[1]).replace(/\s+/g, " "), !(t = this.links[t.toLowerCase()]) || !t.href) { o += i[0].charAt(0), e = i[0].substring(1) + e; continue } this.inLink = !0, o += this.outputLink(i, t), this.inLink = !1 } else if (i = this.rules.strong.exec(e)) e = e.substring(i[0].length), o += this.renderer.strong(this.output(i[4] || i[3] || i[2] || i[1])); else if (i = this.rules.em.exec(e)) e = e.substring(i[0].length), o += this.renderer.em(this.output(i[6] || i[5] || i[4] || i[3] || i[2] || i[1])); else if (i = this.rules.code.exec(e)) e = e.substring(i[0].length), o += this.renderer.codespan(_(i[2].trim(), !0)); else if (i = this.rules.br.exec(e)) e = e.substring(i[0].length), o += this.renderer.br(); else if (i = this.rules.del.exec(e)) e = e.substring(i[0].length), o += this.renderer.del(this.output(i[1])); else if (i = this.rules.autolink.exec(e)) e = e.substring(i[0].length), r = "@" === i[2] ? "mailto:" + (n = _(this.mangle(i[1]))) : n = _(i[1]), o += this.renderer.link(r, null, n); else if (this.inLink || !(i = this.rules.url.exec(e))) { if (i = this.rules.text.exec(e)) e = e.substring(i[0].length), this.inRawBlock ? o += this.renderer.text(this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(i[0]) : _(i[0]) : i[0]) : o += this.renderer.text(_(this.smartypants(i[0]))); else if (e) throw new Error("Infinite loop on byte: " + e.charCodeAt(0)) } else { if ("@" === i[2]) r = "mailto:" + (n = _(i[0])); else { for (; l = i[0], i[0] = this.rules._backpedal.exec(i[0])[0], l !== i[0];); n = _(i[0]), r = "www." === i[1] ? "http://" + n : n } e = e.substring(i[0].length), o += this.renderer.link(r, null, n) } return o }, p.escapes = function (e) { return e ? e.replace(p.rules._escapes, "$1") : e }, p.prototype.outputLink = function (e, t) { var n = t.href, r = t.title ? _(t.title) : null; return "!" !== e[0].charAt(0) ? this.renderer.link(n, r, this.output(e[1])) : this.renderer.image(n, r, _(e[1])) }, p.prototype.smartypants = function (e) { return this.options.smartypants ? e.replace(/---/g, "—").replace(/--/g, "–").replace(/(^|[-\u2014/(\[{"\s])'/g, "$1‘").replace(/'/g, "’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1“").replace(/"/g, "”").replace(/\.{3}/g, "…") : e }, p.prototype.mangle = function (e) { if (!this.options.mangle) return e; for (var t, n = "", r = e.length, s = 0; s < r; s++) t = e.charCodeAt(s), .5 < Math.random() && (t = "x" + t.toString(16)), n += "&#" + t + ";"; return n }, r.prototype.code = function (e, t, n) { var r = (t || "").match(/\S*/)[0]; if (this.options.highlight) { var s = this.options.highlight(e, r); null != s && s !== e && (n = !0, e = s) } return r ? '
' + (n ? e : _(e, !0)) + "
\n" : "
" + (n ? e : _(e, !0)) + "
" }, r.prototype.blockquote = function (e) { return "
\n" + e + "
\n" }, r.prototype.html = function (e) { return e }, r.prototype.heading = function (e, t, n, r) { return this.options.headerIds ? "' + e + "\n" : "" + e + "\n" }, r.prototype.hr = function () { return this.options.xhtml ? "
\n" : "
\n" }, r.prototype.list = function (e, t, n) { var r = t ? "ol" : "ul"; return "<" + r + (t && 1 !== n ? ' start="' + n + '"' : "") + ">\n" + e + "\n" }, r.prototype.listitem = function (e) { return "
  • " + e + "
  • \n" }, r.prototype.checkbox = function (e) { return " " }, r.prototype.paragraph = function (e) { return "

    " + e + "

    \n" }, r.prototype.table = function (e, t) { return t && (t = "" + t + ""), "\n\n" + e + "\n" + t + "
    \n" }, r.prototype.tablerow = function (e) { return "\n" + e + "\n" }, r.prototype.tablecell = function (e, t) { var n = t.header ? "th" : "td"; return (t.align ? "<" + n + ' align="' + t.align + '">' : "<" + n + ">") + e + "\n" }, r.prototype.strong = function (e) { return "" + e + "" }, r.prototype.em = function (e) { return "" + e + "" }, r.prototype.codespan = function (e) { return "" + e + "" }, r.prototype.br = function () { return this.options.xhtml ? "
    " : "
    " }, r.prototype.del = function (e) { return "" + e + "" }, r.prototype.link = function (e, t, n) { if (null === (e = l(this.options.sanitize, this.options.baseUrl, e))) return n; var r = '
    " }, r.prototype.image = function (e, t, n) { if (null === (e = l(this.options.sanitize, this.options.baseUrl, e))) return n; var r = '' + n + '" : ">" }, r.prototype.text = function (e) { return e }, s.prototype.strong = s.prototype.em = s.prototype.codespan = s.prototype.del = s.prototype.text = function (e) { return e }, s.prototype.link = s.prototype.image = function (e, t, n) { return "" + n }, s.prototype.br = function () { return "" }, h.parse = function (e, t) { return new h(t).parse(e) }, h.prototype.parse = function (e) { this.inline = new p(e.links, this.options), this.inlineText = new p(e.links, f({}, this.options, { renderer: new s })), this.tokens = e.reverse(); for (var t = ""; this.next() ;) t += this.tok(); return t }, h.prototype.next = function () { return this.token = this.tokens.pop(), this.token }, h.prototype.peek = function () { return this.tokens[this.tokens.length - 1] || 0 }, h.prototype.parseText = function () { for (var e = this.token.text; "text" === this.peek().type;) e += "\n" + this.next().text; return this.inline.output(e) }, h.prototype.tok = function () { switch (this.token.type) { case "space": return ""; case "hr": return this.renderer.hr(); case "heading": return this.renderer.heading(this.inline.output(this.token.text), this.token.depth, c(this.inlineText.output(this.token.text)), this.slugger); case "code": return this.renderer.code(this.token.text, this.token.lang, this.token.escaped); case "table": var e, t, n, r, s = "", i = ""; for (n = "", e = 0; e < this.token.header.length; e++) n += this.renderer.tablecell(this.inline.output(this.token.header[e]), { header: !0, align: this.token.align[e] }); for (s += this.renderer.tablerow(n), e = 0; e < this.token.cells.length; e++) { for (t = this.token.cells[e], n = "", r = 0; r < t.length; r++) n += this.renderer.tablecell(this.inline.output(t[r]), { header: !1, align: this.token.align[r] }); i += this.renderer.tablerow(n) } return this.renderer.table(s, i); case "blockquote_start": for (i = ""; "blockquote_end" !== this.next().type;) i += this.tok(); return this.renderer.blockquote(i); case "list_start": i = ""; for (var l = this.token.ordered, o = this.token.start; "list_end" !== this.next().type;) i += this.tok(); return this.renderer.list(i, l, o); case "list_item_start": i = ""; var a = this.token.loose, h = this.token.checked, p = this.token.task; for (this.token.task && (i += this.renderer.checkbox(h)) ; "list_item_end" !== this.next().type;) i += a || "text" !== this.token.type ? this.tok() : this.parseText(); return this.renderer.listitem(i, p, h); case "html": return this.renderer.html(this.token.text); case "paragraph": return this.renderer.paragraph(this.inline.output(this.token.text)); case "text": return this.renderer.paragraph(this.parseText()); default: var u = 'Token with "' + this.token.type + '" type was not found.'; if (!this.options.silent) throw new Error(u); console.log(u) } }, t.prototype.slug = function (e) { var t = e.toLowerCase().trim().replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, "").replace(/\s/g, "-"); if (this.seen.hasOwnProperty(t)) for (var n = t; this.seen[n]++, t = n + "-" + this.seen[n], this.seen.hasOwnProperty(t) ;); return this.seen[t] = 0, t }, _.escapeTest = /[&<>"']/, _.escapeReplace = /[&<>"']/g, _.replacements = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }, _.escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/, _.escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g; var o = {}, u = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i; function g() { } function f(e) { for (var t, n, r = 1; r < arguments.length; r++) for (n in t = arguments[r]) Object.prototype.hasOwnProperty.call(t, n) && (e[n] = t[n]); return e } function y(e, t) { var n = e.replace(/\|/g, function (e, t, n) { for (var r = !1, s = t; 0 <= --s && "\\" === n[s];) r = !r; return r ? "|" : " |" }).split(/ \|/), r = 0; if (n.length > t) n.splice(t); else for (; n.length < t;) n.push(""); for (; r < n.length; r++) n[r] = n[r].trim().replace(/\\\|/g, "|"); return n } function w(e, t, n) { if (0 === e.length) return ""; for (var r = 0; r < e.length;) { var s = e.charAt(e.length - r - 1); if (s !== t || n) { if (s === t || !n) break; r++ } else r++ } return e.substr(0, e.length - r) } function d(e, t) { if (-1 === e.indexOf(t[1])) return -1; for (var n = 0, r = 0; r < e.length; r++) if ("\\" === e[r]) r++; else if (e[r] === t[0]) n++; else if (e[r] === t[1] && --n < 0) return r; return -1 } function m(e) { e && e.sanitize && !e.silent && console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options") } function k(e, n, r) { if (null == e) throw new Error("marked(): input parameter is undefined or null"); if ("string" != typeof e) throw new Error("marked(): input parameter is of type " + Object.prototype.toString.call(e) + ", string expected"); if (r || "function" == typeof n) { r || (r = n, n = null), m(n = f({}, k.defaults, n || {})); var s, i, l = n.highlight, t = 0; try { s = a.lex(e, n) } catch (e) { return r(e) } i = s.length; var o = function (t) { if (t) return n.highlight = l, r(t); var e; try { e = h.parse(s, n) } catch (e) { t = e } return n.highlight = l, t ? r(t) : r(null, e) }; if (!l || l.length < 3) return o(); if (delete n.highlight, !i) return o(); for (; t < s.length; t++) !function (n) { "code" !== n.type ? --i || o() : l(n.text, n.lang, function (e, t) { return e ? o(e) : null == t || t === n.text ? --i || o() : (n.text = t, n.escaped = !0, void (--i || o())) }) }(s[t]) } else try { return n && (n = f({}, k.defaults, n)), m(n), h.parse(a.lex(e, n), n) } catch (e) { if (e.message += "\nPlease report this to https://github.com/markedjs/marked.", (n || k.defaults).silent) return "

    An error occurred:

    " + _(e.message + "", !0) + "
    "; throw e } } g.exec = g, k.options = k.setOptions = function (e) { return f(k.defaults, e), k }, k.getDefaults = function () { return { baseUrl: null, breaks: !1, gfm: !0, headerIds: !0, headerPrefix: "", highlight: null, langPrefix: "language-", mangle: !0, pedantic: !1, renderer: new r, sanitize: !1, sanitizer: null, silent: !1, smartLists: !1, smartypants: !1, xhtml: !1 } }, k.defaults = k.getDefaults(), k.Parser = h, k.parser = h.parse, k.Renderer = r, k.TextRenderer = s, k.Lexer = a, k.lexer = a.lex, k.InlineLexer = p, k.inlineLexer = p.output, k.Slugger = t, k.parse = k, "undefined" != typeof module && "object" == typeof exports ? module.exports = k : "function" == typeof define && define.amd ? define(function () { return k }) : e.marked = k }(this || ("undefined" != typeof window ? window : global)); \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/spa.js b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/spa.js index 4feac60..94e05f4 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/spa.js +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataCenter/www/spa.js @@ -1,513 +1,592 @@ -function DataVM() { - "use strict"; - var self = this; - self.helpers = new Helpers(); - self.menuOptions = ["Home"]; - self.possibleLogDirections = ko.observableArray([ - { Text: "In", value: 1 }, - { Text: "Out", value: 2 } - ]), - self.chosenMenuItemId = ko.observable(); - self.appDetails = ko.observable(null); - self.userList = ko.observable(null); - self.groupsList = ko.observable(null); - self.chosenUserDetails = ko.observable(null); - self.userTimeLogData = ko.observable(null); - self.unassignedCardData = ko.observable(null); - self.chosenTimeLogUserId = -1; - self.selectedTimeLogDate = ko.observable(null); - self.selectedCalendarWeek = ko.observable(0); - self.errorData = ko.observable(null); - self.manualLog = ko.observable(null); - self.apiEndpoints = { - root: "http://localhost:8800", - getUserList: "/api/users", - getUserDetails: "/api/users", - editUser: "/api/users/edit", - getTimeLogs: "/api/timelogs", - getUnassignedCards: "/api/cards/unassigned", - getGroups: "/api/groups", - getAppDetails: "/api/app", - manualLogsCreate: "/api/logs/create", - manualLogsDelete: "/api/logs/delete" - }; - self.uiPages = { - users: "users", - userDetails: "userData", - timeLogs: "timelogs", - home: function () { return this.users; } - }; - self.goToMenuOption = function (menu) { location.hash = menu; console.log("goToMenuOption: " + menu); }; - self.goToUserDetails = function (user) { location.hash = self.uiPages.userDetails + "/" + user.UserId; }; - self.goToTimeLogs = function (user, data, args) { - var userId; - if (user.UserId) { - userId = user.UserId; - } else { - userId = user; - } - var url = "timelogs" + "/" + userId; - if (args) { - url = self.helpers.createRequestUrl(url, args, false, false); - } - location.hash = url; - }; - self.goToToday = function() { - self.goToTimeLogs(self.chosenTimeLogUserId, - null, - null); - }; - self.assignErrorObject = function(errCode, errMessage, errorSource) { - var errDat = { - errorCode: errCode, - errorMessage: errMessage, - errorSource: errorSource, - errorDate: new Date().toDateString("yyyy-mm-dd") - }; - self.errorData(errDat); - } - self.returnButtonClick = function (data, event) { - var destination = self.helpers.getPageDestination(data, event); - if (destination !== "") { - self.goToMenuOption(destination); //redirect to whereever the button is telling us to go.. - } - }; - self.convertToHours = function (value) { - var hrs = value / 60; - if (hrs < 1) { - return value + " mins"; - } - var h = Math.floor(hrs); - var m = Math.floor((hrs % 1) * 60); - return h + " hrs " + m + " minutes"; - }; - self.convertToDisplayTime = function (dateValue) { - var date = new Date(dateValue); - return date.getHours() + ":" + self.padNumber(date.getMinutes()); - }; - self.correctLogOffset = function(logCount) { - if (logCount % 2 !== 0) { - logCount += 1; - } - return logCount; - }; - self.round = function(value, decimals) { - return parseFloat(Math.round(value * 100) / 100).toFixed(decimals); - }; - self.getTimeLogEntryArrayLength = function(maxDailyLogs) { - return Math.round(maxDailyLogs/2); - }; - self.padNumber = function(number) { - return (number < 10 ? "0" : "") + number; - }; - self.convertToDisplayDateTime = function (dateValue) { - var date = new Date(dateValue); // dd MM YY HH:mm:ss e.g.: 01 Mar 17 17:34:02 - return date.getDate() + " " - + date.toLocaleString("en-us", { month: "long" }) + " " - + (date.getYear()-100) + " " - + self.padNumber(date.getHours()) + ":" - + self.padNumber(date.getMinutes()) + ":" - + self.padNumber(date.getSeconds()); - }; - self.dismissAlert = function(data, event) { - self.errorData(null); - }; - self.setPageSize = function(data) { - if (self.userList().PageSize !== data && self.userList().PageSize !== -1) { - self.setPagination(data, 1); - } - }; - self.goToUserPage = function (data) { - if (self.userList().PageNumber !== data && self.userList().PageNumber !== -1) { - self.setPagination(self.userList().PageSize, data); - } - }; - self.getCurrentGroupFilter = function() { - if (self.userList() !== null) { - if (self.userList().GroupFilter !== null) { - return self.userList().GroupFilter.Name; - } - } - return ""; - }; - self.clearGroupFilter = function () { - self.setPagination(20, 1); - }; - self.hasGroupFilter = function() { - if(self.userList() !== null) - if (self.userList().GroupFilter) - return true; - return false; - }; - self.hasQuery = function() { - if (self.userList() !== null) { - if (self.userList().Query && self.userList().Query !== "") - return true; - } - return false; - }; - self.groupFilter = function(data) { - console.log("filter by group: " + data); - var args = [ - { - key: "groupId", - value: data - } - ]; - var url = self.helpers.createRequestUrl("users", args, false, false); - location.hash = url; - console.log(url); - }; - self.setPagination = function(pageSize, pageNumber) { - var args = [ - { - key: "pageSize", - value: pageSize - }, - { - key: "pageNumber", - value: pageNumber - } - ]; - var url = self.helpers.createRequestUrl("users", args, false, false); - location.hash = url; - console.log(url); - }; - self.initDatePicker = function (selectedDate) { - if (!selectedDate) { - selectedDate = new Date(); - } else { - selectedDate = new Date(selectedDate); - } - moment.locale("en", { week: { dow: 1 } }); - $("#weeklyDatePicker").datetimepicker({ - //showTodayButton: true, - format: "DD/MM/YYYY", - inline: true, - calendarWeeks: true, - maxDate: "now", - date: selectedDate - }); - }; - self.assignHandler = function() { - var elem = $("#weeklyDatePicker")[0]; - var data = jQuery.hasData(elem) && jQuery._data(elem); - if (!data.events) { - $("#weeklyDatePicker") - .on("dp.change", - function(e) { - var value = e.date; - self.selectedCalendarWeek(moment(value).isoWeek()); - self.goToTimeLogs(self.chosenTimeLogUserId, - null, - [{ key: "selectedDate", value: moment(value).format("MM-DD-YYYY") }]); - }); - } - }; - self.assignUpdateHandler = function() { - var elem = $("#datetimepicker1")[0]; - var data = jQuery.hasData(elem) && jQuery._data(elem); - if (!data.events) { - $("#datetimepicker1") - .on("dp.change", - function(e) { - var value = e.date.toISOString(); - self.manualLog().EventTime = value; - }); - } - }; - self.getUserList = function (pageSize, pageNumber, groupId) { - var args = null; - if (pageSize && pageNumber) { - args = [ - { - key: "pageSize", - value: pageSize - }, - { - key: "pageNumber", - value: pageNumber - } - ]; - } else if(groupId) { - args = [ - { - key: "groupId", - value: groupId - }]; - } - var url = self.helpers.createRequestUrl(self.apiEndpoints.getUserList, args, false); - $.getJSON(url, function (res) { - self.userList(res); - $('[data-toggle="tooltip"]').tooltip(); - }).fail(function (response, status, error) { - console.log("error - getusers"); - var errObj = self.helpers.processRequestFailure(response, status, error); - self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getUserList"); - }); - }; - self.getAppDetails = function() { - var url = self.helpers.createRequestUrl(self.apiEndpoints.getAppDetails, null, false, false); - $.getJSON(url, function (res) { - self.appDetails(res); - }).fail(function (response, status, error) { - console.log("error - getusers"); - var errObj = self.helpers.processRequestFailure(response, status, error); - self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getUserList"); - }); - }; - self.searchUsers = function(query) { - var url = self.helpers.createRequestUrl(self.apiEndpoints.getUserList, - [{ key: "query", value: query }], false, false); - $.getJSON(url, - function(res) { - self.userList(res); - }).fail(function(resp, status, error) { - self.goToMenuOption(self.uiPages.home()); - var errObj = self.helpers.processRequestFailure(resp, status, error); - self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "searchUsers"); - } - ); - }; - self.getUserDetails = function (userId) { - var url = self.helpers.createRequestUrl(self.apiEndpoints.getUserDetails + "/" + userId, null, false); - $.getJSON(url, function (res) { - self.chosenUserDetails(res); - }).fail(function (resp, status, error) { - console.log("error - getuserdetails"); - var errObj = self.helpers.processRequestFailure(resp, status, error); - self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getUserDetails"); - self.goToMenuOption(self.uiPages.home()); - }); - }; - self.submitChangedUser = function (user) { - var url = self.helpers.createRequestUrl(self.apiEndpoints.editUser, null, false, false); - $.post(url, user, function () { - }, "json") - .done(function () { - self.chosenUserDetails(null); - self.goToMenuOption(self.uiPages.home()); - }) - .fail(function (resp, status, error) { - var errObj = self.helpers.processRequestFailure(resp, status, error); - self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "submitChangedUser"); - self.chosenUserDetails(null); - self.goToMenuOption(self.uiPages.home()); - }); - }; - self.getTimeLogData = function (userId, selectedDate) { - var urlArgs = [{ key: "userId", value: userId }]; - if (selectedDate) { - urlArgs.push({ key: "selectedDate", value: selectedDate }); - } - var url = self.helpers.createRequestUrl(self.apiEndpoints.getTimeLogs, - urlArgs, - false); - $.getJSON(url, function (res) { - self.userTimeLogData(res); - self.initDatePicker(res.SelectedDate); - self.assignHandler(); - }).fail(function (resp, status, error) { - console.log("error - getuserdetails"); - var errObj = self.helpers.processRequestFailure(resp, status, error); - self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getTimeLogData"); - self.goToMenuOption(self.uiPages.home()); //go home. - }); - }; - self.getUnassignedCardData = function () { - var url = self.helpers.createRequestUrl(self.apiEndpoints.getUnassignedCards, null, false); - $.getJSON(url, function (res) { - self.unassignedCardData(res); - }).fail(function (resp, status, error) { - console.log("error - getuserdetails"); - var errObj = self.helpers.processRequestFailure(resp, status, error); - self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getUnassignedCardData"); - }); - }; - self.getGroups = function (successFunc) { - var url = self.helpers.createRequestUrl(self.apiEndpoints.getGroups, null, false); - return $.getJSON(url, function (res) { - successFunc(res); - //self.chosenUserDetails().Groups = res; - //self.chosenUserDetails.valueHasMutated(); - }).fail(function (resp, status, error) { - console.log("error - getGroups"); - var errObj = self.helpers.processRequestFailure(resp, status, error); - self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getGroups"); - }); - }; - self.createManualLog = function(newLog) { - var url = self.helpers.createRequestUrl(self.apiEndpoints.manualLogsCreate, null, false, false); - $.post(url, newLog, function () { - }, "json") - .done(function () { - self.manualLog(null); - $('#manualLogDialog').modal("hide"); - location.reload(); //stay on this users logs page, but just reload the timelogs. - }) - .fail(function (resp, status, error) { - var errObj = self.helpers.processRequestFailure(resp, status, error); - self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "createManualLog"); - self.chosenUserDetails(null); - self.goToMenuOption(self.uiPages.home()); - }); - }; - self.deleteManualLog = function (logToDelete) { - var url = self.helpers.createRequestUrl(self.apiEndpoints.manualLogsDelete, null, false, false); - $.ajax({ - url: url, - type: "DELETE", - data: logToDelete, - success: function (result) { - console.log("successfully deleted .." + result); - location.reload(); //stay on this page but just reload the timelogs. - } - }); - }; - self.createContextMenu = ko.observableArray([ - { text: "Create", action: createlog } - ]); - self.editContextMenu = ko.observableArray([ - { text: "Create", action: createlog }, - { text: "Edit", action: editlog }, - { text: "Delete", action: deleteLog } - ]); - function editlog (data) { - self.manualLog(data); - $("#manualLogDialog").modal("show"); - self.initialiseManualLogDateTimePicker(data.EventTime); - self.assignUpdateHandler(); - }; - function createlog(data, event) { - self.manualLog({ - CalendarWeek:-1, - Direction:-1, - EventTime: new Date().toISOString(), - Id: -1, - IdentifierId: -1, - UserId: self.chosenTimeLogUserId, - Year: 0 - }); - $('#manualLogDialog').modal("show"); - self.initialiseManualLogDateTimePicker(self.selectedTimeLogDate()); - self.assignUpdateHandler(); - }; - function deleteLog(data) { - if (confirm("Are you sure you want to delete this log?")) { - self.deleteManualLog(data); - } - }; - self.initialiseManualLogDateTimePicker = function (date) { - $('#datetimepicker1') - .datetimepicker({ - format: "YYYY-DD-MM HH:mm:ss", - date: new Date(date), - inline:true, - sideBySide:true, - minDate: moment(date).startOf("week"), - maxDate: moment(date).endOf("week") - }); - }; - Sammy(function () { - this.get("#users", function () { - var query = this.params.query; - var pageSize = this.params.pageSize; - var pageNumber = this.params.pageNumber; - var groupId = this.params.groupId; - self.chosenMenuItemId("Home"); - self.groupsList(null); - self.chosenUserDetails(null); - self.userList(null); - self.userTimeLogData(null); - self.manualLog(null); - if (self.appDetails() === null) { - self.getAppDetails(); - } - self.getGroups(function (data) { self.groupsList(data); }); - if (query) - self.searchUsers(query); - else if (groupId && groupId > 0) - self.getUserList(null, null, groupId); - else - self.getUserList(pageSize, pageNumber); - }); - this.get("#userData/:userId", function () { - self.chosenMenuItemId("Data"); - self.groupsList(null); - self.chosenUserDetails(null); - self.userList(null); - self.userTimeLogData(null); - self.manualLog(null); - self.getUserDetails(this.params.userId); - self.getUnassignedCardData(); - }); - this.get("#timelogs/:userId", function () { - if (this.params.selectedDate) { - self.selectedTimeLogDate(this.params.selectedDate); - } else { - self.selectedTimeLogDate(new Date()); - } - self.chosenTimeLogUserId = this.params.userId; - self.chosenMenuItemId("Other"); - self.groupsList(null); - self.chosenUserDetails(null); - self.userList(null); - self.userTimeLogData(null); - self.manualLog(null); - self.getTimeLogData(this.params.userId, self.selectedTimeLogDate()); - }); - this.get("#newUser", function () { - self.chosenMenuItemId("newUser"); - self.userList(null); - self.userTimeLogData(null); - self.chosenUserDetails({ - "UserId": -1, - "FirstName": null, - "LastName": null, - "HoursPerWeek": null, - "AssociatedIdentifiers": [], - "Groups": [], - "IsContractor": false - }); - self.getGroups(function(data) { - self.chosenUserDetails().Groups = data.Groups; - self.chosenUserDetails.valueHasMutated(); - }); - self.getUnassignedCardData(); - }); - this.get("#stats", function () { - self.goToMenuOption("users"); - }); - this.post("#edituser", function () { - $.each(self.chosenUserDetails().AssociatedIdentifiers, - function (k, v) { - if (v.IsAssociatedToUser !== true) { - self.chosenUserDetails().AssociatedIdentifiers.splice(k, 1); - } - }); - $.each(self.unassignedCardData().data, function (k, v) { - if (v.IsAssociatedToUser === true) { - self.chosenUserDetails().AssociatedIdentifiers.push(v); - } - }); - self.submitChangedUser(self.chosenUserDetails()); - return false; - }); - this.post("#manualLog", - function() { - self.createManualLog(self.manualLog()); - - $('#manualLogDialog').modal("hide"); - //self.goToTimeLogs(self.chosenTimeLogUserId, null, [{ key: "selectedDate", value: self.selectedTimeLogDate() }]); - }); - //default route (home page) - this.get("", function () { this.app.runRoute("get", "#" + self.uiPages.home()) }); - }).run(); -}; -ko.applyBindings(new DataVM()); -//$(document).on("mouseenter", ".datepicker-days tbody tr", function () { -// $(this).addClass("highlight"); -//}); -//$(document).on("mouseleave", ".datepicker-days tbody tr", function () { -// $(this).removeClass("highlight"); +const SortOptions = { + LastAsc: "LastNameAscending", + LastDesc: "LastNameDescending", + FirstAsc: "FirstNameAscending", + FirstDesc: "FirstNameDescending" + }; +function DataVM() { + "use strict"; + var self = this; + self.helpers = new Helpers(); + self.menuOptions = ["Home", "Policy"]; + self.possibleLogDirections = ko.observableArray([ + { Text: "In", value: 1 }, + { Text: "Out", value: 2 } + ]), + self.chosenMenuItemId = ko.observable(); + self.appDetails = ko.observable(null); + self.userList = ko.observable(null); + self.groupsList = ko.observable(null); + self.chosenUserDetails = ko.observable(null); + self.userTimeLogData = ko.observable(null); + self.unassignedCardData = ko.observable(null); + self.chosenTimeLogUserId = -1; + self.selectedTimeLogDate = ko.observable(null); + self.selectedCalendarWeek = ko.observable(0); + self.errorData = ko.observable(null); + self.manualLog = ko.observable(null); + self.policyData = ko.observable(null); + self.policyChangeDate = ko.observable(null); + self.policyChangeAuthor = ko.observable(null); + self.policyVersion = ko.observable(null); + self.selectedSort = ko.observable(null); + self.apiEndpoints = { + root: "http://localhost:8800", + getUserList: "/api/users", + getUserDetails: "/api/users", + editUser: "/api/users/edit", + getTimeLogs: "/api/timelogs", + getUnassignedCards: "/api/cards/unassigned", + getGroups: "/api/groups", + getAppDetails: "/api/app", + manualLogsCreate: "/api/logs/create", + manualLogsDelete: "/api/logs/delete", + getPolicy: "/api/app/policy" + }; + self.uiPages = { + users: "users", + userDetails: "userData", + timeLogs: "timelogs", + home: function () { return this.users; } + }; + self.goToMenuOption = function (menu) { location.hash = menu; console.log("goToMenuOption: " + menu); }; + self.goToUserDetails = function (user) { location.hash = self.uiPages.userDetails + "/" + user.UserId; }; + self.goToTimeLogs = function (user, data, args) { + var userId; + if (user.UserId) { + userId = user.UserId; + } else { + userId = user; + } + var url = "timelogs" + "/" + userId; + if (args) { + url = self.helpers.createRequestUrl(url, args, false, false); + } + location.hash = url; + }; + self.goToToday = function() { + self.goToTimeLogs(self.chosenTimeLogUserId, + null, + null); + }; + self.assignErrorObject = function(errCode, errMessage, errorSource) { + var errDat = { + errorCode: errCode, + errorMessage: errMessage, + errorSource: errorSource, + errorDate: new Date().toDateString("yyyy-mm-dd") + }; + self.errorData(errDat); + } + self.returnButtonClick = function (data, event) { + var destination = self.helpers.getPageDestination(data, event); + if (destination !== "") { + self.goToMenuOption(destination); //redirect to whereever the button is telling us to go.. + } + }; + self.convertToHours = function (value) { + var hrs = value / 60; + if (hrs < 1) { + return value + " mins"; + } + var h = Math.floor(hrs); + var m = Math.floor((hrs % 1) * 60); + return h + " hrs " + m + " minutes"; + }; + self.convertToDisplayTime = function (dateValue) { + var date = new Date(dateValue); + return date.getHours() + ":" + self.padNumber(date.getMinutes()); + }; + self.correctLogOffset = function(logCount) { + if (logCount % 2 !== 0) { + logCount += 1; + } + return logCount; + }; + self.round = function(value, decimals) { + return parseFloat(Math.round(value * 100) / 100).toFixed(decimals); + }; + self.getTimeLogEntryArrayLength = function(maxDailyLogs) { + return Math.round(maxDailyLogs/2); + }; + self.padNumber = function(number) { + return (number < 10 ? "0" : "") + number; + }; + self.convertToDisplayDateTime = function (dateValue) { + var date = new Date(dateValue); // dd MM YY HH:mm:ss e.g.: 01 Mar 17 17:34:02 + return date.getDate() + " " + + date.toLocaleString("en-us", { month: "long" }) + " " + + (date.getYear()-100) + " " + + self.padNumber(date.getHours()) + ":" + + self.padNumber(date.getMinutes()) + ":" + + self.padNumber(date.getSeconds()); + }; + self.dismissAlert = function(data, event) { + self.errorData(null); + }; + self.setPageSize = function(data) { + if (self.userList().PageSize !== data && self.userList().PageSize !== -1) { + self.setPagination(data, 1); + } + }; + self.goToUserPage = function (data) { + if (self.userList().PageNumber !== data && self.userList().PageNumber !== -1) { + self.setPagination(self.userList().PageSize, data); + } + }; + self.getCurrentGroupFilter = function() { + if (self.userList() !== null) { + if (self.userList().GroupFilter !== null) { + return self.userList().GroupFilter.Name; + } + } + return ""; + }; + self.clearGroupFilter = function () { + self.setPagination(20, 1); + }; + self.hasGroupFilter = function() { + if(self.userList() !== null) + if (self.userList().GroupFilter) + return true; + return false; + }; + self.hasQuery = function() { + if (self.userList() !== null) { + if (self.userList().Query && self.userList().Query !== "") + return true; + } + return false; + }; + self.groupFilter = function(data) { + console.log("filter by group: " + data); + var args = [ + { + key: "groupId", + value: data + } + ]; + var url = self.helpers.createRequestUrl("users", args, false, false); + location.hash = url; + console.log(url); + }; + self.setPagination = function(pageSize, pageNumber) { + var args = [ + { + key: "pageSize", + value: pageSize + }, + { + key: "pageNumber", + value: pageNumber + } + ]; + var url = self.helpers.createRequestUrl("users", args, false, false); + location.hash = url; + console.log(url); + }; + self.initDatePicker = function (selectedDate) { + if (!selectedDate) { + selectedDate = new Date(); + } else { + selectedDate = new Date(selectedDate); + } + moment.locale("en", { week: { dow: 1 } }); + $("#weeklyDatePicker").datetimepicker({ + //showTodayButton: true, + format: "DD/MM/YYYY", + inline: true, + calendarWeeks: true, + maxDate: "now", + date: selectedDate + }); + }; + self.assignHandler = function() { + var elem = $("#weeklyDatePicker")[0]; + var data = jQuery.hasData(elem) && jQuery._data(elem); + if (!data.events) { + $("#weeklyDatePicker") + .on("dp.change", + function(e) { + var value = e.date; + self.selectedCalendarWeek(moment(value).isoWeek()); + self.goToTimeLogs(self.chosenTimeLogUserId, + null, + [{ key: "selectedDate", value: moment(value).format("MM-DD-YYYY") }]); + }); + } + }; + self.assignUpdateHandler = function() { + var elem = $("#datetimepicker1")[0]; + var data = jQuery.hasData(elem) && jQuery._data(elem); + if (!data.events) { + $("#datetimepicker1") + .on("dp.change", + function(e) { + var value = e.date.toISOString(); + self.manualLog().EventTime = value; + }); + } + }; + self.getUserList = function (pageSize, pageNumber, groupId, sort) { + var args = []; + if (pageSize && pageNumber) { + args.push( + { + key: "pageSize", + value: pageSize + }); + args.push( + { + key: "pageNumber", + value: pageNumber + }); + } + if (groupId) { + args.push( + { + key: "groupId", + value: groupId + }); + } + if (sort) { + args.push({ + key: "sort", + value: sort + }); + } + var url = self.helpers.createRequestUrl(self.apiEndpoints.getUserList, args, false); + $.getJSON(url, function (res) { + self.userList(res); + $('[data-toggle="tooltip"]').tooltip(); + }).fail(function (response, status, error) { + console.log("error - getusers"); + var errObj = self.helpers.processRequestFailure(response, status, error); + self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getUserList"); + }); + }; + self.getAppDetails = function() { + var url = self.helpers.createRequestUrl(self.apiEndpoints.getAppDetails, null, false, false); + $.getJSON(url, function (res) { + self.appDetails(res); + }).fail(function (response, status, error) { + console.log("error - getusers"); + var errObj = self.helpers.processRequestFailure(response, status, error); + self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getUserList"); + }); + }; + self.searchUsers = function(query, sort) { + var url = self.helpers.createRequestUrl(self.apiEndpoints.getUserList, + [{ key: "query", value: query }, {key:"sort",value:sort}], false, false); + $.getJSON(url, + function(res) { + self.userList(res); + }).fail(function(resp, status, error) { + self.goToMenuOption(self.uiPages.home()); + var errObj = self.helpers.processRequestFailure(resp, status, error); + self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "searchUsers"); + } + ); + }; + self.getUserDetails = function (userId) { + var url = self.helpers.createRequestUrl(self.apiEndpoints.getUserDetails + "/" + userId, null, false); + $.getJSON(url, function (res) { + self.chosenUserDetails(res); + }).fail(function (resp, status, error) { + console.log("error - getuserdetails"); + var errObj = self.helpers.processRequestFailure(resp, status, error); + self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getUserDetails"); + self.goToMenuOption(self.uiPages.home()); + }); + }; + self.submitChangedUser = function (user) { + var url = self.helpers.createRequestUrl(self.apiEndpoints.editUser, null, false, false); + $.post(url, user, function () { + }, "json") + .done(function () { + self.chosenUserDetails(null); + self.goToMenuOption(self.uiPages.home()); + }) + .fail(function (resp, status, error) { + var errObj = self.helpers.processRequestFailure(resp, status, error); + self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "submitChangedUser"); + self.chosenUserDetails(null); + self.goToMenuOption(self.uiPages.home()); + }); + }; + self.getTimeLogData = function (userId, selectedDate) { + var urlArgs = [{ key: "userId", value: userId }]; + if (selectedDate) { + urlArgs.push({ key: "selectedDate", value: selectedDate }); + } + var url = self.helpers.createRequestUrl(self.apiEndpoints.getTimeLogs, + urlArgs, + false); + $.getJSON(url, function (res) { + self.userTimeLogData(res); + self.initDatePicker(res.SelectedDate); + self.assignHandler(); + }).fail(function (resp, status, error) { + console.log("error - getuserdetails"); + var errObj = self.helpers.processRequestFailure(resp, status, error); + self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getTimeLogData"); + self.goToMenuOption(self.uiPages.home()); //go home. + }); + }; + self.getUnassignedCardData = function () { + var url = self.helpers.createRequestUrl(self.apiEndpoints.getUnassignedCards, null, false); + $.getJSON(url, function (res) { + self.unassignedCardData(res); + }).fail(function (resp, status, error) { + console.log("error - getuserdetails"); + var errObj = self.helpers.processRequestFailure(resp, status, error); + self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getUnassignedCardData"); + }); + }; + self.getGroups = function (successFunc) { + var url = self.helpers.createRequestUrl(self.apiEndpoints.getGroups, null, false); + return $.getJSON(url, function (res) { + successFunc(res); + //self.chosenUserDetails().Groups = res; + //self.chosenUserDetails.valueHasMutated(); + }).fail(function (resp, status, error) { + console.log("error - getGroups"); + var errObj = self.helpers.processRequestFailure(resp, status, error); + self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getGroups"); + }); + }; + self.getPolicyData = function () { + var url = self.helpers.createRequestUrl(self.apiEndpoints.getPolicy, null, false); + $.getJSON(url, function (res) { + console.log(res); + self.policyData(res); + }).fail(function (resp, status, error) { + console.log("error - getPolicyData"); + var errObj = self.helpers.processRequestFailure(resp, status, error); + self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "getPolicyData"); + }); + + }; + self.createManualLog = function(newLog) { + var url = self.helpers.createRequestUrl(self.apiEndpoints.manualLogsCreate, null, false, false); + $.post(url, newLog, function () { + }, "json") + .done(function () { + self.manualLog(null); + $("#manualLogDialog").modal("hide"); + location.reload(); //stay on this users logs page, but just reload the timelogs. + }) + .fail(function (resp, status, error) { + var errObj = self.helpers.processRequestFailure(resp, status, error); + self.assignErrorObject(errObj.errorCode, errObj.errorMessage, "createManualLog"); + self.chosenUserDetails(null); + self.goToMenuOption(self.uiPages.home()); + }); + }; + self.deleteManualLog = function (logToDelete) { + var url = self.helpers.createRequestUrl(self.apiEndpoints.manualLogsDelete, null, false, false); + $.ajax({ + url: url, + type: "DELETE", + data: logToDelete, + success: function (result) { + console.log("successfully deleted .." + result); + location.reload(); //stay on this page but just reload the timelogs. + } + }); + }; + self.createContextMenu = ko.observableArray([ + { text: "Create", action: createlog } + ]); + self.editContextMenu = ko.observableArray([ + { text: "Create", action: createlog }, + { text: "Edit", action: editlog }, + { text: "Delete", action: deleteLog } + ]); + function editlog (data) { + self.manualLog(data); + $("#manualLogDialog").modal("show"); + self.initialiseManualLogDateTimePicker(data.EventTime); + self.assignUpdateHandler(); + }; + function createlog(data, event) { + var logDateInitVal = moment(self.selectedTimeLogDate()).add((data.Day - 1), 'days').toISOString(); + self.manualLog({ + CalendarWeek:-1, + Direction:-1, + EventTime: logDateInitVal, + Id: -1, + IdentifierId: -1, + UserId: self.chosenTimeLogUserId, + Year: 0 + }); + $('#manualLogDialog').modal("show"); + self.initialiseManualLogDateTimePicker(logDateInitVal); + self.assignUpdateHandler(); + }; + function deleteLog(data) { + if (confirm("Are you sure you want to delete this log?")) { + self.deleteManualLog(data); + } + }; + self.initialiseManualLogDateTimePicker = function (date) { + $('#datetimepicker1') + .datetimepicker({ + format: "YYYY-DD-MM HH:mm:ss", + date: new Date(date), + inline:true, + sideBySide:true, + minDate: moment(date).startOf("week"), + maxDate: moment(date).endOf("week") + }); + }; + function convertSortOption(opt) { + if (!opt) { + return null + } + if (opt === "firstAsc") { + return SortOptions.FirstAsc; + } + if (opt === "firstDesc") { + return SortOptions.FirstDesc; + } + if (opt === "lastAsc") { + return SortOptions.LastAsc; + } + if (opt === "lastDesc") { + return SortOptions.LastDesc; + } + }; + self.sortIsActive = function (option) { + if (option === "firstAsc" && self.userList().SelectedSortOption === SortOptions.FirstAsc) { + return true; + } + if (option === "firstDesc" && self.userList().SelectedSortOption === SortOptions.FirstDesc) { + return true; + } + if (option === "lastAsc" && self.userList().SelectedSortOption === SortOptions.LastAsc) { + return true; + } + if (option === "lastDesc" && self.userList().SelectedSortOption === SortOptions.LastDesc) { + return true; + } + return false; + }; + Sammy(function () { + this.get("#users", function () { + var query = this.params.query; + var pageSize = this.params.pageSize; + var pageNumber = this.params.pageNumber; + var groupId = this.params.groupId; + var sort = convertSortOption(this.params.sort); + console.log(sort); + self.chosenMenuItemId("Home"); + self.groupsList(null); + self.chosenUserDetails(null); + self.userList(null); + self.userTimeLogData(null); + self.policyData(null); + self.manualLog(null); + if (self.appDetails() === null) { + self.getAppDetails(); + } + self.getGroups(function (data) { self.groupsList(data); }); + if (query) + self.searchUsers(query, sort); + else if (groupId && groupId > 0) + self.getUserList(null, null, groupId, sort); + else + self.getUserList(pageSize, pageNumber, null,sort); + }); + this.get("#userData/:userId", function () { + self.chosenMenuItemId("Data"); + self.groupsList(null); + self.chosenUserDetails(null); + self.userList(null); + self.userTimeLogData(null); + self.policyData(null); + self.manualLog(null); + self.getUserDetails(this.params.userId); + self.getUnassignedCardData(); + }); + this.get("#timelogs/:userId", function () { + if (this.params.selectedDate) { + self.selectedTimeLogDate(this.params.selectedDate); + } else { + self.selectedTimeLogDate(new Date()); + } + self.chosenTimeLogUserId = this.params.userId; + self.chosenMenuItemId("Other"); + self.groupsList(null); + self.chosenUserDetails(null); + self.userList(null); + self.userTimeLogData(null); + self.manualLog(null); + self.policyData(null); + self.getTimeLogData(this.params.userId, self.selectedTimeLogDate()); + }); + this.get("#newUser", function () { + self.chosenMenuItemId("newUser"); + self.userList(null); + self.userTimeLogData(null); + self.policyData(null); + self.chosenUserDetails({ + "UserId": -1, + "FirstName": null, + "LastName": null, + "HoursPerWeek": null, + "AssociatedIdentifiers": [], + "Groups": [], + "IsContractor": false + }); + self.getGroups(function(data) { + self.chosenUserDetails().Groups = data.Groups; + self.chosenUserDetails.valueHasMutated(); + }); + self.getUnassignedCardData(); + }); + this.get("#stats", function () { + self.goToMenuOption("users"); + }); + this.get("#Policy", + function () { + self.groupsList(null); + self.chosenUserDetails(null); + self.userList(null); + self.userTimeLogData(null); + self.manualLog(null); + + self.getPolicyData(); + }); + this.post("#edituser", function () { + $.each(self.chosenUserDetails().AssociatedIdentifiers, + function (k, v) { + if (v.IsAssociatedToUser !== true) { + self.chosenUserDetails().AssociatedIdentifiers.splice(k, 1); + } + }); + $.each(self.unassignedCardData().data, function (k, v) { + if (v.IsAssociatedToUser === true) { + self.chosenUserDetails().AssociatedIdentifiers.push(v); + } + }); + self.submitChangedUser(self.chosenUserDetails()); + return false; + }); + this.post("#manualLog", + function() { + self.createManualLog(self.manualLog()); + $('#manualLogDialog').modal("hide"); + //self.goToTimeLogs(self.chosenTimeLogUserId, null, [{ key: "selectedDate", value: self.selectedTimeLogDate() }]); + }); + //default route (home page) + this.get("", function () { this.app.runRoute("get", "#" + self.uiPages.home()) }); + }).run(); +}; +ko.applyBindings(new DataVM()); +//$(document).on("mouseenter", ".datepicker-days tbody tr", function () { +// $(this).addClass("highlight"); +//}); +//$(document).on("mouseleave", ".datepicker-days tbody tr", function () { +// $(this).removeClass("highlight"); //}); \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataServiceHost/App.config b/DataCenter_Windows/WindowsDataCenter/WindowsDataServiceHost/App.config index d2ebb4c..26fa84b 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataServiceHost/App.config +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataServiceHost/App.config @@ -1,36 +1,48 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataServiceHost/WindowsDataServiceHost.csproj b/DataCenter_Windows/WindowsDataCenter/WindowsDataServiceHost/WindowsDataServiceHost.csproj index 895a7b9..37c2c74 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataServiceHost/WindowsDataServiceHost.csproj +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataServiceHost/WindowsDataServiceHost.csproj @@ -1,133 +1,137 @@ - - - - - Debug - AnyCPU - {5A4E2CF2-FA51-413E-82C7-14A19A50766D} - Exe - Properties - WindowsDataServiceHost - WindowsDataServiceHost - v4.5.2 - 512 - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - bin\DebugInstallers\ - DEBUG;TRACE - full - AnyCPU - prompt - MinimumRecommendedRules.ruleset - true - - - bin\ReleaseInstallers\ - TRACE - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - true - - - - ..\packages\Microsoft.Owin.3.0.1\lib\net45\Microsoft.Owin.dll - True - - - ..\packages\Microsoft.Owin.Host.HttpListener.3.0.1\lib\net45\Microsoft.Owin.Host.HttpListener.dll - True - - - ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll - True - - - ..\packages\Owin.1.0\lib\net40\Owin.dll - True - - - - - ..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll - True - - - - ..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll - True - - - ..\packages\Microsoft.AspNet.Razor.3.0.0\lib\net45\System.Web.Razor.dll - True - - - - - - - - - - - - - - - Designer - - - - - - {A5FEE048-17A6-4966-9B6B-BF073592A470} - WindowsDataCenter - - - - - copy "$(SolutionDir)SQLiteRepository\$(OutDir)SQLiteRepository.dll" "$(TargetDir)" -copy "$(SolutionDir)SQLiteRepository\$(OutDir)SQLite.Net.Platform.Win32.dll" "$(TargetDir)" -copy "$(SolutionDir)SQLiteRepository\$(OutDir)SQLite.Net.Platform.Generic.dll" "$(TargetDir)" -copy "$(SolutionDir)SQLiteRepository\$(OutDir)SQLite.Net.dll" "$(TargetDir)" -mkdir "$(TargetDir)Configs" -copy "$(SolutionDir)NLogLogger\$(OutDir)NLogLogger.dll" "$(TargetDir)" -copy "$(SolutionDir)NLogLogger\$(OutDir)NLog.dll" "$(TargetDir)" -copy "$(SolutionDir)NLogLogger\$(OutDir)NLogLogger.dll.config" "$(TargetDir)" -copy "$(SolutionDir)NLogLogger\$(OutDir)NLogConfig.xml" "$(TargetDir)Configs\" - -copy "$(SolutionDir)WindowsDataCenter\$(OutDir)Ninject.Extensions.Xml.dll" "$(TargetDir)" - -copy "$(SolutionDir)WindowsDataCenter\$(OutDir)RazorEngine.dll" "$(TargetDir)" - - + + + + + Debug + AnyCPU + {5A4E2CF2-FA51-413E-82C7-14A19A50766D} + Exe + Properties + WindowsDataServiceHost + WindowsDataServiceHost + v4.5.2 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\DebugInstallers\ + DEBUG;TRACE + full + AnyCPU + prompt + MinimumRecommendedRules.ruleset + true + + + bin\ReleaseInstallers\ + TRACE + true + pdbonly + AnyCPU + prompt + MinimumRecommendedRules.ruleset + true + + + + ..\packages\Microsoft.Owin.3.0.1\lib\net45\Microsoft.Owin.dll + True + + + ..\packages\Microsoft.Owin.FileSystems.3.0.1\lib\net45\Microsoft.Owin.FileSystems.dll + True + + + ..\packages\Microsoft.Owin.Host.HttpListener.3.0.1\lib\net45\Microsoft.Owin.Host.HttpListener.dll + True + + + ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll + True + + + ..\packages\Owin.1.0\lib\net40\Owin.dll + True + + + + + ..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll + True + + + + ..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll + True + + + ..\packages\Microsoft.AspNet.Razor.3.0.0\lib\net45\System.Web.Razor.dll + True + + + + + + + + + + + + + + + Designer + + + + + + {A5FEE048-17A6-4966-9B6B-BF073592A470} + WindowsDataCenter + + + + + copy "$(SolutionDir)SQLiteRepository\$(OutDir)SQLiteRepository.dll" "$(TargetDir)" +copy "$(SolutionDir)SQLiteRepository\$(OutDir)SQLite.Net.Platform.Win32.dll" "$(TargetDir)" +copy "$(SolutionDir)SQLiteRepository\$(OutDir)SQLite.Net.Platform.Generic.dll" "$(TargetDir)" +copy "$(SolutionDir)SQLiteRepository\$(OutDir)SQLite.Net.dll" "$(TargetDir)" +mkdir "$(TargetDir)Configs" +copy "$(SolutionDir)NLogLogger\$(OutDir)NLogLogger.dll" "$(TargetDir)" +copy "$(SolutionDir)NLogLogger\$(OutDir)NLog.dll" "$(TargetDir)" +copy "$(SolutionDir)NLogLogger\$(OutDir)NLogLogger.dll.config" "$(TargetDir)" +copy "$(SolutionDir)NLogLogger\$(OutDir)NLogConfig.xml" "$(TargetDir)Configs\" + +copy "$(SolutionDir)WindowsDataCenter\$(OutDir)Ninject.Extensions.Xml.dll" "$(TargetDir)" + +copy "$(SolutionDir)WindowsDataCenter\$(OutDir)RazorEngine.dll" "$(TargetDir)" + + \ No newline at end of file diff --git a/DataCenter_Windows/WindowsDataCenter/WindowsDataServiceHost/packages.config b/DataCenter_Windows/WindowsDataCenter/WindowsDataServiceHost/packages.config index b50cb7b..a23faf9 100644 --- a/DataCenter_Windows/WindowsDataCenter/WindowsDataServiceHost/packages.config +++ b/DataCenter_Windows/WindowsDataCenter/WindowsDataServiceHost/packages.config @@ -1,8 +1,8 @@ - - - - - - - + + + + + + + \ No newline at end of file diff --git a/Tools/Sentinel.zip b/Tools/Sentinel.zip new file mode 100644 index 0000000..dd24c00 Binary files /dev/null and b/Tools/Sentinel.zip differ